JSFiddle - React, Tailwind, and code Playground

by Aleksey Karagodnikov

JavaScript

function arraySearch(value, db) {
    for (var i = 0; i < db.length; ++i) {
        if (db[i] === value) {
            return i;
        }
    }
    return -1;
}

function nextElem(needle, haystack, cycle) {
    cycle = typeof (cycle) === 'undefined' ? false : !! cycle;
    var key = arraySearch(needle, haystack, true);
    if (key > -1) {
        if (++key > (haystack.length - 1)) {
            return (cycle && haystack[0]);
        } else {
            return haystack[key];
        }
    }
    return false;
}

function prevElem(needle, haystack, cycle) {
    cycle = typeof (cycle) === 'undefined' ? false : !! cycle;
    var key = arraySearch(needle, haystack, true);
    if (key > -1) {
        if (--key < 0) {
            return (cycle && haystack[haystack.length - 1]);
        } else {
            return haystack[key];
        }
    }
    return false;
}
var arr = [1, 4, 5];
console.log(nextElem(0, arr));          // false
console.log(nextElem(4, arr));          // 5
console.log(nextElem(5, arr));          // false
console.log(nextElem(5, arr, 'cycle')); // 1
console.log(prevElem(0, arr));          // false
console.log(prevElem(4, arr));          // 1
console.log(prevElem(1, arr));          // false
console.log(prevElem(1, arr, 'cycle')); // 5