Guest User

Untitled

a guest
Nov 18th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. // common functions
  2. const plus = (a, b) => a + b
  3. const minus = (a, b) => a - b
  4. const len = array => array.length
  5. const condNext = (start, end, list) => plus(start, end) <= len(list) - 1 ? plus(start, end) : len(list) - 1
  6. const condPrev = (start, end) => minus(start, end) >= 0 ? minus(start, end) : 0
  7.  
  8. // closure main function
  9. const get = list => {
  10. return {
  11. next: (start = 0, end = 1) =>
  12. list[condNext(start, end, list)],
  13.  
  14. prev: (start = 0, end = 1) =>
  15. list[condPrev(start, end)]
  16. }
  17. }
  18.  
  19. // Elements
  20. const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
  21. const arrObj = [
  22. {
  23. 'field': '123'
  24. },
  25. {
  26. 'field': '456'
  27. },
  28. {
  29. 'field': '789'
  30. },
  31. {
  32. 'field': '000'
  33. }
  34. ]
  35.  
  36. /* Usage
  37. get(arr).next(0) returns the next array element, starting at position 0 -- return element at position 1
  38. get(arr).next(1, 3) returns the next array element, starting at position 1 and ending at position 3 -- return element at position 4 (1 + 3)
  39.  
  40. get(arr).prev(1) return the previous array element, starting at position 1 -- return element at position 0
  41. get(arr).prev(3, 1) return the previous array element, starting at position 3 and ending at position 1 -- return element at position 2 (3 - 1)
  42. */
  43.  
  44. // Tests
  45. console.log(get(arr).prev(4, 3))
  46. console.log(get(arr).next(5))
  47.  
  48. console.log(get(arrObj).prev(2, 2))
  49. console.log(get(arrObj).next(1))
  50.  
  51. console.log(arr.map((el, i, _arr) => get(_arr).next(i, 1)))
  52. console.log(arr.map((el, i, _arr) => get(_arr).prev(i, 1)))
Add Comment
Please, Sign In to add comment