Last active
November 16, 2017 16:22
-
-
Save Woodsphreaker/1208b1a72529308cb7daa43894f04a18 to your computer and use it in GitHub Desktop.
prev next element array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment