0

I need make a range from 1 to 15 and some kind of reverse. Currently i using next script:

$scope.range = (min, max) ->
  input = []
  i = min
  while i < max
    input.push i
    i += 1
  input

so if put range(1,15) it will be 1 2 3 4 5 6 7 8 9 10 11 ... 15

What i need is in case when range(10, 3) it should put 10 11 12 13 14 15 1 2 3

2 Answers 2

1
range = (min, max) ->
    input = []
    i = max
    while i > min
      input.push i
      i -= 1
    input

console.log(range( 10, 50 ));

Thats really simple try to set i = max an then count i down with the condition that i must be greater than min. That's it. Try the code above.

Sign up to request clarification or add additional context in comments.

1 Comment

I have fixed your script indentation. There is still a problem with the range boundaries: you are missing the inclusive lower bound. Could be fixed by looping with a while i >= min. And you are giving the boundaries in reverse order.
0

Solution is based on understanding that must go to 15 and order must be as shown:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

function range(min, max) {
    var startArr = arr.slice(arr.indexOf(min)),
        endArr = max < arr.length ? arr.slice(0, arr.indexOf(max) + 1) : [];
    return startArr.concat(endArr);
}


range(10, 3);
//[10,11,12,13,14,15,1,2,3]

DEMO

3 Comments

Thanks but why in case if may arr = [{id:1, name: 'John'}, {id:2, name: 'Mark'}, {id:3, name: 'Jim'},{id:4, name: 'Bob'} ... ]; it not works?
Because this is working from array of integers exactly as you showed in question. If you want it to work on array of objects need to clarify criteria
Thanks, i'll already handle it. Probably i'll should delete my comment, before you answered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.