Created
October 23, 2020 21:58
-
-
Save StreetStrider/754bb3a9267d3f3045cf706c5b17b395 to your computer and use it in GitHub Desktop.
compress-decompress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var log = console.log | |
var input = 'LLLAABBBBBEE' | |
log(input) | |
var c = compress(input) | |
log(c) | |
var d = decompress(c) | |
log(d) | |
function compress (str) | |
{ | |
return str | |
.match(/(.)\1*/g) | |
.map(chunk => | |
{ | |
var initial = chunk.charAt(0) | |
var length = chunk.length | |
if (length > 2) | |
{ | |
return `${ initial }${ length }` | |
} | |
else | |
{ | |
return chunk | |
} | |
}) | |
.join('') | |
} | |
function decompress (str) | |
{ | |
return str | |
.match(/\w\d+|\w\w/g) | |
.map(chunk => | |
{ | |
var mm = chunk.match(/(\w)(\d+)/) | |
if (mm) | |
{ | |
var initial = mm[1] | |
var length = Number(mm[2]) | |
return initial.repeat(length) | |
} | |
else | |
{ | |
return chunk | |
} | |
}) | |
.join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment