Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created January 18, 2023 23:01
Show Gist options
  • Select an option

  • Save anushshukla/854feeba452344469f09afa049e8033d to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/854feeba452344469f09afa049e8033d to your computer and use it in GitHub Desktop.
Encode-Decode string count
var fs = require('fs');
const readline = require('readline');
const getDecodedStr = async (filePath) => {
let output = '';
let charCounts = [];
const rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
for await (const line of rl) {
let char = line;
let parsedInt = parseInt(char);
if (parsedInt == char) {
charCounts.push(parsedInt);
} else {
let charRepeats = 0;
let charRepeatCount = charCounts.length;
let index = 0;
while (charRepeatCount > 0) {
charRepeats += charCounts[index] * 10 ** (charRepeatCount - 1);
charRepeatCount--;
index++;
}
while (charRepeats > 1) {
output += char;
charRepeats--;
}
output += char;
charCounts = [];
}
}
return output;
};
const main = async () => {
const expectedOutput = 'AAAAAAAAAAAABBBCCCCCAAABCD';
const encodeStr = await getDecodedStr('encoded-str.txt');
console.log('expected output', expectedOutput);
// console.log('actual output', encodeStr);
console.log('test case passed', encodeStr === expectedOutput);
}
main()
A
A
B
B
B
C
C
C
C
C
A
A
A
B
C
var fs = require('fs');
const readline = require('readline');
const getEncodeStr = async (filePath) => {
let prevChar = '';
let output = '';
let occurences = 0;
const rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
for await (const line of rl) {
let char = line;
if (char === prevChar) {
occurences++;
} else {
output += `${occurences > 1 ? occurences : ''}${prevChar}`;
occurences = 1;
}
prevChar = char;
}
output += `${occurences > 1 ? occurences : ''}${prevChar}`;
return output;
};
const main = async () => {
const expectedOutput = '2A3B5C3ABCD';
const encodeStr = await getEncodeStr('decoded-str.txt');
console.log('expected output', expectedOutput);
console.log('actual output', encodeStr);
console.log('test case passed', encodeStr === expectedOutput);
}
main()
1
2
A
3
B
5
C
3
A
B
C
D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment