tc39 / proposal-slice-notation

http://tc39.es/proposal-slice-notation/
MIT License
523 stars 19 forks source link

Inclusivity vs Exclusivity #15

Open atticoos opened 6 years ago

atticoos commented 6 years ago

Should the syntax be inclusive of the upper bound of the range, or exclusive?

With the collection

a = [1, 2, 3, 4]

And the expression

a[1..3]

Shall it produce a range inclusive of the value at position 3, or exclusive?

// inclusive
[2, 3, 4]
// exclusive
[2, 3]

This issue provides a formal place for discussion and reference point for the underlying behavior of the syntax's inclusive or exclusive behavior

atticoos commented 6 years ago

It should be exclusive

This allows the syntax to remain consistent with the underlying functionality of slice. As per the spec (or in user-friendly terms):

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

ljharb commented 6 years ago

Certainly it should map to slice; is there something in the readme that suggests it would be otherwise?

atticoos commented 6 years ago

Motivation and examples sections of the readme all point to mapping behavior to slice.

However, in the CoffeeScript example there is reference to both inclusive and exclusive usages. There is also mention of the potential usage of two different operators in the first question of the FAQ to achieve either inclusivity or exclusivity.

scf4 commented 6 years ago

Exclusivity seems counterintuitive to me, but so does the behavior of slice. Maybe don’t make it map to slice?

const letters = ["a", "b", "c", "d"];
letters[1:3]; // ["b", "c", "d"];

I would vote for the Ruby-style syntax (1..3 and 1...3) as it’s much more intuitive. I don’t see the step feature as important enough to require its own special syntax.

vojty commented 3 years ago

Rust has nice syntax for exclusive and inclusive ranges as well https://doc.rust-lang.org/std/ops/struct.Range.html#examples

a = [1, 2, 3, 4]
a[0..2] = [1, 2]
a[0..=2] = [1, 2, 3]