Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. /**
  2. * Whenever we are trying to deal with a *datastructure* manipulation
  3. * we should never *skip, mutate, hide* the intermediary *stages* of the manipulation
  4. * we should try to *transform* structure from one form to another explicity
  5. *
  6. * This way we can be confident on *how*(Declarative) the datastructure has transformed
  7. *
  8. * Also, allows us to *re-use* functionality for a slightly varied datastructure
  9. * Eg: I can reuse the functionality for [{},{}] where sequence would be determined
  10. * by `id` prop of the object. In this case i would only need to change `isInSeq` implementation
  11. *
  12. * Trasnformations:
  13. *
  14. * "1,2,3,4,10,11,12,3,6,7"
  15. * [[1,2,3,4],[10,11,12],[3],[6.7]]
  16. * ["1-4", "10-12", "3", "6-7"]
  17. * "1-4,10-12, 3, 6-7"
  18. *
  19. * Don't worry about looping thru the array everytime. JS engine is fast
  20. * if u are worried, use *Structural sharing* libs like `mori, immutable.js`
  21. * But don't sacrifice a comprehensible code
  22. *
  23. */
  24.  
  25. var isInSeq = (current, next) => (current + 1 == next);
  26. var getLastItem = (arr) => arr[arr.length -1];
  27.  
  28. var sequenceReducer = (acc=[], item) => {
  29. let chunk = getLastItem(acc);
  30. if(chunk && isInSeq(getLastItem(chunk), item)) {
  31. chunk.push(item)
  32. }else{
  33. acc.push([item])
  34. }
  35.  
  36. return acc;
  37.  
  38. }
  39.  
  40. var compress = (arr=[]) => (arr.length != 1)
  41. ? [arr[0], getLastItem(arr)].join('-')
  42. : arr.join();
  43.  
  44.  
  45.  
  46. function main(input) {
  47. return input.split(',')
  48. .map(Number)
  49. .reduce(sequenceReducer, [])
  50. .map(compress)
  51. .join(",")
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement