Iterating through a range in both directions

假如想象 提交于 2019-12-11 05:56:39

问题


There is a very common and easy task of looped iteration through some range in both directions:

var currentIndex = 0;
var range = ['a', 'b', 'c', 'd', 'e', 'f'];

function getNextItem(direction) {
    currentIndex += direction;
    if (currentIndex >= range.length) { currentIndex = 0; }
    if (currentIndex < 0) { currentIndex = range.length-1; }

    return range[currentIndex];
}        
// get next "right" item
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));

The code above works perfectly, but I spent about an hour trying to get rid of double if check.

Is there any way to solve if without if? Sort of one-liner maybe?


回答1:


To turn the two ifs into one unconditional statement, you can add the range.length to the currentIndex and then use modulo:

var currentIndex = 0;
var range = ['a','b','c','d','e','f'];

function getNextItem(direction) {
    currentIndex = (currentIndex + direction + range.length) % range.length;
    return range[currentIndex];
}

// get next "right" item
console.log(getNextItem(1));
console.log(getNextItem(1));

// get next "left" item
console.log(getNextItem(-1));
console.log(getNextItem(-1));
console.log(getNextItem(-1));

console.log(getNextItem(4));
console.log(getNextItem(1));
console.log(getNextItem(1));
console.log(getNextItem(1));


来源:https://stackoverflow.com/questions/58142680/iterating-through-a-range-in-both-directions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!