Skip to content

Instantly share code, notes, and snippets.

@kcjpop
Created November 19, 2018 12:02
Show Gist options
  • Save kcjpop/475ab7d42e9b3cc25e595cb2bd8b9e49 to your computer and use it in GitHub Desktop.
Save kcjpop/475ab7d42e9b3cc25e595cb2bd8b9e49 to your computer and use it in GitHub Desktop.
Count consecutive chunks of a number array
const assert = require('assert')
function f(n) {
const [result, counter, num] = (n + '').split('').map(Number)
.reduce(([result, count, num], n) => {
if (num == null) return [result, 1, n]
if (n !== num) return [
[...result, [count, num]],
1,
n
]
return [result, count + 1, num]
}, [
[], // acc
0, // counter
null, // current num
])
return [...result, [counter, num]]
}
assert.deepStrictEqual(f(11), [[2, 1]]);
assert.deepStrictEqual(f(21), [[1, 2], [1, 1]]);
assert.deepStrictEqual(f(9000), [[1, 9], [3, 0]]);
assert.deepStrictEqual(f(222222222222), [[12, 2]]);
assert.deepStrictEqual(f(2331), [[1, 2], [2, 3], [1, 1]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment