Skip to content

Instantly share code, notes, and snippets.

@DanielFGray
Last active March 2, 2016 04:17
Show Gist options
  • Save DanielFGray/cefe1b6afc364bac0ee9 to your computer and use it in GitHub Desktop.
Save DanielFGray/cefe1b6afc364bac0ee9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
'use strict';
const runlength = {};
runlength.decode = function(str) {
return str.match(/\d*\w/g)
.reduce((prev, curr) =>
prev + (curr.length > 1
? curr.slice(-1)
.repeat(curr.slice(0, curr.length - 1))
: curr)
, '');
}
runlength.encode = function(str) {
return str.match(/(.)\1*/g)
.reduce((prev, curr) =>
prev + (curr.length === 1
? curr
: curr.length + curr.slice(-1))
, '');
}
const test = [
[ 'foo', 'f2o' ],
[ 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW', '12WB12W3B24WB14W' ],
[ 'abcdefghijklmnopqrstuvwxyzzzzzzzzzzzz', 'abcdefghijklmnopqrstuvwxy12z' ]
];
console.log('encoding');
test.forEach(t => console.log(runlength.encode(t[0]) == t[1], `${t[0]} == ${t[1]}`));
console.log('decoding');
test.forEach(t => console.log(runlength.decode(t[1]) == t[0], `${t[1]} == ${t[0]}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment