Skip to content

Instantly share code, notes, and snippets.

@agrrd
Last active February 16, 2021 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agrrd/8f5784e34119d7a279db2df565c6cb14 to your computer and use it in GitHub Desktop.
Save agrrd/8f5784e34119d7a279db2df565c6cb14 to your computer and use it in GitHub Desktop.
// 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