Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Whenever we are trying to deal with a *datastructure* manipulation
- * we should never *skip, mutate, hide* the intermediary *stages* of the manipulation
- * we should try to *transform* structure from one form to another explicity
- *
- * This way we can be confident on *how*(Declarative) the datastructure has transformed
- *
- * Also, allows us to *re-use* functionality for a slightly varied datastructure
- * Eg: I can reuse the functionality for [{},{}] where sequence would be determined
- * by `id` prop of the object. In this case i would only need to change `isInSeq` implementation
- *
- * Trasnformations:
- *
- * "1,2,3,4,10,11,12,3,6,7"
- * [[1,2,3,4],[10,11,12],[3],[6.7]]
- * ["1-4", "10-12", "3", "6-7"]
- * "1-4,10-12, 3, 6-7"
- *
- * Don't worry about looping thru the array everytime. JS engine is fast
- * if u are worried, use *Structural sharing* libs like `mori, immutable.js`
- * But don't sacrifice a comprehensible code
- *
- */
- var isInSeq = (current, next) => (current + 1 == next);
- var getLastItem = (arr) => arr[arr.length -1];
- var sequenceReducer = (acc=[], item) => {
- let chunk = getLastItem(acc);
- if(chunk && isInSeq(getLastItem(chunk), item)) {
- chunk.push(item)
- }else{
- acc.push([item])
- }
- return acc;
- }
- var compress = (arr=[]) => (arr.length != 1)
- ? [arr[0], getLastItem(arr)].join('-')
- : arr.join();
- function main(input) {
- return input.split(',')
- .map(Number)
- .reduce(sequenceReducer, [])
- .map(compress)
- .join(",")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement