Skip to content

Instantly share code, notes, and snippets.

@StreetStrider
Created October 23, 2020 21:58
Show Gist options
  • Save StreetStrider/754bb3a9267d3f3045cf706c5b17b395 to your computer and use it in GitHub Desktop.
Save StreetStrider/754bb3a9267d3f3045cf706c5b17b395 to your computer and use it in GitHub Desktop.
compress-decompress
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