I have a array of n elements. I am at a given position say x and I need to move to position y, I need to find out what is the difference or number of steps if I traverse array by going forward and by going backward.
const foo = Array.from(Array(15).keys());
const length = foo.length;
const currentItem = 2;
const next = 12;
let diff = currentItem - next;
if (diff < 0) {
if (next > currentItem) {
diff = next - currentItem;
console.log((diff));
} else {
diff = length - Math.abs(diff);
console.log(-diff);
}
} else {
if (next < currentItem) {
console.log(-(diff));
} else {
console.log(diff);
}
}
I am trying to fin in above code if I need to move forward or backward. In above example I expect answer as -6 but I get answer 10. I am getting bit confused in the loops. Any better and smarter way to do this?