-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.js
54 lines (45 loc) · 1.52 KB
/
encoder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var encoder = (str, cb) => {
const myNumber = '1234567890'.split('');
let newString = '',
myMap = {},
currentCharacter = '',
previousCharacter,
strArr = str.split(''); // convert the input string to string array
const strLength = strArr.length;
// if this is a empty string
if (strLength <= 0) {
return cb(null, str);
}
previousCharacter = strArr[0];
newString += strArr[0]; // add the first character to the new string
for (let index = 0; index < strLength; index++) {
currentCharacter = strArr[index];
if (previousCharacter == currentCharacter) {
if (myMap[currentCharacter]) {
myMap[currentCharacter] ++;
} else {
myMap[currentCharacter] = 1;
}
} else {
if (myMap[previousCharacter] > 0) {
newString += myMap[previousCharacter];
if (myNumber.includes(currentCharacter)) {
newString += '/';
}
}
newString += currentCharacter;
myMap[previousCharacter] = 0;
previousCharacter = currentCharacter;
myMap[currentCharacter] = 1;
}
}
// add the last character number to the new string
if (myMap[previousCharacter] > 0) {
newString += myMap[previousCharacter];
if (myNumber.includes(previousCharacter)) {
newString += '/';
}
}
cb(null, newString);
};
module.exports = encoder;