Skip to content

Array ranges act differently with plain numbers and variables #349

Description

@Daiz

Consider I have the following code:

arr = [1,2,3,4,5]
arr[-1 to 1]

The second line will compile to [arr[-1], arr[0], arr[1]], giving us [null,1,2].

However, if we change the code to this:

arr = [1,2,3,4,5]
i = 0
arr[i-1 to i+1]

It will compile to essentially arr.slice(i-1, i+1+1), which gives us [], because given negative numbers [].slice will start looking from the end of the array, so this basically equals arr.slice(4,2).

It would be nice if array range behavior could be unified somehow, whether it's being used with plain numbers or variables.

One way (which would solve the problem where I ran into this) would be to simply do bound checking for the (first) slice argument, eg. something like arr.slice((i-1 < 0 ? 0 : i-1), i+1+1) - this would make the end result just [1,2], which is not identical to the first one but better than an empty array at least.

EDIT: Alternatively, you could do the same thing that plain ranges do with variables and use a for loop, something close to this:

var arr, i, i$, to$;
arr = [1,2,3,4,5];
i = 0;
for(i$ = i - 1, to$ = i + 1; i$ < to$; ++i$) {
  arr[i$];
}

This way you'd get the exact same result as with arr[-1 to 1].

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions