Lets say I have:
var array = [0,1,2,3,4,5,6,7,8,9]
I define:
var itemsToExtract = 5
var startindex = 7
var direction = "forward"
I want to be able to do:
array.someMethod(startindex, itemsToExtract, direction)
and get
[7,8,9,0,1]
I also want it to work backwards, if I set direction to "backward" (slicing from right to left).
I wasnt too lazy and tried something already, see here: http://jsfiddle.net/MkNrr/
I am looking for something "tidier" if there is, also is there a name for this method, is it a known problem?
Background: I am trying to build a sequential pre image loader (load one image(src) after the other) for use in an image gallery. Maybe even such a libary already exists?
How about a function that returns the forward and back arrays? That way you don't need a switch. Something like this:
function overslice(arr, idx, items) {
var fwd = arr.filter(function(v,i){ return i >= idx }).slice(0, items),
back = arr.filter(function(v,i){ return i <= idx }).slice(-items);
while (fwd.length < items) {
fwd = fwd.concat(arr).slice(0, items);
}
while (back.length < items) {
back = arr.concat(back).slice(-items);
}
return { fwd: fwd, back: back };
}
Then you can use it like:
var array = [0,1,2,3,4,5,6,7,8,9]
var result = overslice(array, 7, 5);
console.log(result.fwd, result.back); //=> [7, 8, 9, 0, 1] [3, 4, 5, 6, 7]
My approach:
function overslice(array, startindex, count, direction) {
var retarray = [];
var increment = (direction === 'backward') ? -1 : 1;
for(var c=0, i = startindex; c<count; i+=increment, c++){
retarray.push(array[(i + array.length)%array.length]);
}
return retarray;
}
Working fiddle
UPDATE
Another version using the count
variable to dictate the direction using positive/negative values and with a fix to allow use of count
larger than the array length:
function overslice(array, startindex, count) {
var retarray = [];
var increment = (count >= 0) ? 1 : -1;
count = Math.abs(count);
for(var i = startindex, c = 0;c<count;i+=increment, c++){
if(i<0) i= array.length-1;
retarray.push(array[i%array.length]);
}
return retarray;
}
Demo fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With