Created
May 8, 2014 22:27
-
-
Save jdrury/e282918b435b6461f938 to your computer and use it in GitHub Desktop.
compress string
This file contains hidden or 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 compress = function(str){ | |
var compressed = ""; | |
var previous = ""; | |
var count = 1; | |
var last = str.length - 1; | |
sorted = str.split('').sort(); | |
sorted.forEach(function(letter,i) { | |
if (i === 0){ | |
previous = letter; | |
} else if (previous === letter && i !== last) { | |
console.log('next',letter) | |
count += 1; | |
} else if (i === last){ | |
if (letter !== previous){ | |
compressed += previous + count; | |
compressed += letter + 1; | |
} else { | |
count += 1; | |
compressed += letter + count | |
} | |
} else { | |
compressed += previous + count; | |
count = 1; | |
previous = letter; | |
} | |
}) | |
return compressed.length > str.length ? str : compressed; | |
} | |
var str = "ababc" | |
console.log(compress(str)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment