Okay, so what you want is a size of array as result (hence 4
) and you have a range array (hence 1 - 7
) . Basically no need to prepare the complete range array as input for processing, you can just have a count and can prepare the only block size resultant array as your requirement.
Array.from(Array(blockSize).keys(), a => ((a + count) % range) + 1)
This will do your job, here blockize
is 4
and range
is 7
, only thing you need to manage is count
throughout your program. It will start from 0
and you need to do +1
or -1
accordingly keeping your range in mind.
I am adding just a sample program to manage the count easily, however you can manage by your own way. and the good part is, you can go to 3-4 next step or previous in one go (as next or prev will go one positive or negative step)
Here is the wrapper of the solution just to manage count.
function buildBlock(range, blockSize) {
let count = 0,
getVal = () => Array.from(Array(blockSize).keys(), a => ((a + count) % range) + 1),
context = {
next: () => {count++; return getVal()},
prev: () => {count = count -1 + range; return getVal()},
current: getVal
};
return context;
}
let block1 = buildBlock(7, 4);
console.log("Current: ", ...block1.current());
console.log("Next: ", ...block1.next());
console.log("Next: ", ...block1.next());
console.log("Next: ", ...block1.next());
console.log("Next: ", ...block1.next());
console.log("Next: ", ...block1.next());
console.log("Previous: ", ...block1.prev());
console.log("Previous: ", ...block1.prev());
console.log("Previous: ", ...block1.prev());
console.log("Previous: ", ...block1.prev());
console.log("Previous: ", ...block1.prev());
console.log("Previous: ", ...block1.prev());
console.log("Next: ", ...block1.next());