Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract x items from array (slice) but continue from beginning if end is reached

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?

like image 384
Hans Avatar asked Jul 25 '13 05:07

Hans


2 Answers

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] 
like image 119
elclanrs Avatar answered Oct 22 '22 00:10

elclanrs


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

like image 38
omma2289 Avatar answered Oct 22 '22 00:10

omma2289