Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // common functions
- const plus = (a, b) => a + b
- const minus = (a, b) => a - b
- const len = array => array.length
- const condNext = (start, end, list) => plus(start, end) <= len(list) - 1 ? plus(start, end) : len(list) - 1
- const condPrev = (start, end) => minus(start, end) >= 0 ? minus(start, end) : 0
- // closure main function
- const get = list => {
- return {
- next: (start = 0, end = 1) =>
- list[condNext(start, end, list)],
- prev: (start = 0, end = 1) =>
- list[condPrev(start, end)]
- }
- }
- // Elements
- const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
- const arrObj = [
- {
- 'field': '123'
- },
- {
- 'field': '456'
- },
- {
- 'field': '789'
- },
- {
- 'field': '000'
- }
- ]
- /* Usage
- get(arr).next(0) returns the next array element, starting at position 0 -- return element at position 1
- 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)
- get(arr).prev(1) return the previous array element, starting at position 1 -- return element at position 0
- 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)
- */
- // Tests
- console.log(get(arr).prev(4, 3))
- console.log(get(arr).next(5))
- console.log(get(arrObj).prev(2, 2))
- console.log(get(arrObj).next(1))
- console.log(arr.map((el, i, _arr) => get(_arr).next(i, 1)))
- console.log(arr.map((el, i, _arr) => get(_arr).prev(i, 1)))
Add Comment
Please, Sign In to add comment