Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for selecting a range of number in javascript

Tags:

javascript

I would like your code suggestion for this algo.

Imagine you have an array of number 0 to 9.

In console you need to print always a set of 4 number, starting from 0.

so for example first set would be

0 - 1 - 2 - 3

when an event occurs occurs you need to print the next number and remove one from the pile

1 - 2 - 3 - 4

when an event occurs occurs you need do the same

2 - 3 - 4 - 5

and so on till you display the last number like

6 - 7 - 8 - 9

what is most elegant and faster way to implement this in JavaScript?

Without affecting the original array.

Solutions

var range = [0,1,2,3,4,5,6,7,8,9];
var start = -1;

function get4()
{
    start++;
    if(start < 7 ) {

        return range.slice(start,start+4);
    }

}


console.log(get4());
console.log(get4());
console.log(get4());
console.log(get4());
console.log(get4()); 
console.log(get4());  
console.log(get4());   
like image 558
GibboK Avatar asked Nov 29 '25 17:11

GibboK


1 Answers

Use Array.prototype.slice:

var start = 0;
var newArr = arr.slice(start, start + 4);
like image 185
ComFreek Avatar answered Dec 01 '25 07:12

ComFreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!