Last active
February 16, 2021 13:28
-
-
Save agrrd/8f5784e34119d7a279db2df565c6cb14 to your computer and use it in GitHub Desktop.
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
// problem in https://twitter.com/Al_Grigor/status/1357028887209902088 | |
const funcReducer = (state, currentChar) => { | |
const isNewGroup = currentChar != state.lastChar ? true : false | |
switch (isNewGroup) { | |
case true: | |
state.out = [...state.out, { | |
[currentChar]: 1 | |
}] | |
break | |
case false: | |
const lastItemIdx = state.out.length - 1 | |
const count = state.out[lastItemIdx][currentChar] + 1 | |
state.out[lastItemIdx] = { | |
[currentChar]: count | |
} | |
break | |
} | |
state.lastChar = currentChar | |
return state | |
} | |
// entry point | |
const input = "aaaabbbcca".split("") | |
const result = input.reduce(funcReducer, { | |
lastChar: false, | |
out: [] | |
}) | |
console.log(result.out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment