Last active
May 11, 2017 03:51
-
-
Save zacacollier/ce4e5a0b2c875ac2c8ed88f9c10b9d94 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/turutux
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
"use strict"; | |
function lookSay (number) { | |
/* Setup: | |
* Stringify the number, split it, | |
* then coerce each string to an integer | |
*/ | |
let split = `${number}`.split("").map(n => +n); | |
let acc = {}; | |
// '.reduce()' would be nice but it's not as efficient | |
for (let i = 0; i < split.length; i++) { | |
// if the current index is the same as the next index, | |
if (split[i] === split[i + 1]) { | |
// and if the accumulator doesn't have a corresponding property, | |
if (!acc[split[i]]) { | |
// initialize that property, and set it to 1. | |
acc[split[i]] = 1; | |
} | |
else { | |
// otherwise, increment that property. | |
acc[split[i]]++; | |
} | |
} | |
else { | |
/* if the current index is NOT the same as the next index, | |
* then we know that we're about to start indexing a new integer, | |
* and should increment the accumulator's corresponding property | |
*/ | |
acc[split[i]]++; | |
} | |
} | |
// Build the output string | |
let output = ""; | |
for (let j in acc) { | |
output = output.concat(`${acc[j]}`, `${j}`); | |
} | |
/* Return parsed output. | |
* Gain a small performance boost using the unary `+` operator: | |
* https://jsperf.com/number-vs-parseint-vs-plus/19 | |
* (kinda negligible since we only call the operator twice in this function) | |
*/ | |
return +output; | |
} | |
// console.log(lookSay(3333111222222)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment