coffeescript
coffeescript copied to clipboard
Grammar: Add support for stepping to range notation
Python has a nifty syntactic sugar for performing stepping in a slice ("extended slices"), that I think should be added to coffeescript.
foo[3:-5] # takes a slice between 3 and 5 from the end
foo[3:-5:2] # takes every 2nd element between 3 and 5 from the end
foo[::2] # takes every 2nd element
foo[::
Obviously, we can't use identical syntax, since coffeescript uses .. and ... for slices instead of :. I'd recommend either using the same operator (:) that python uses or an english word (by)
foo[3..-5:2]
# or
foo[3..-5 by 2]
The 2nd example (using by) is a little odd to my eyes, since it mixes word and symbol operators, so perhaps we should either use a symbol operator (:) and/or add an (optional) word operator for (inclusive) slice/ranges, e.g. to
foo[3 to -5 by 2] is foo[3..-5:2]
For consistency, we would want to add this functionality anywhere that uses range notations, not just slices and splices, but also including for x in [...], and anywhere that I've missed.
More examples, including for in
foo[1..] # 2nd element to the end
foo[...-1] # all but the last element
foo[1...-1] # all but the end elements
foo[:2] # every 2nd element
foo[1...-1:2] # every 2nd element within the slice consisting of everything but the end elements
foo[:2] = replacementsForEvenElements # lengths must match
for x in [10..100:10] # every 10 up to 100
and the same, with word operators:
foo[1..] # 2nd element to the end
foo[...-1] # all but the last element
foo[1 to -2] # all but the end elements
foo[by 2] # every 2nd element
foo[1 to -2 by 2] # every 2nd element within the slice consisting of everything but the end elements
foo[by 2] = replacementsForEvenElements # lengths must match
for x in [10 to 100 by 10] # every 10 up to 100
It wouldn't just be for slices ... but would you like to edit this ticket (and change the title) to suggest adding support for stepping in ranges in general?
x..y by z
... for slicing, splicing, range literals, and everywhere else that ranges are used.
Sure, I can do that :+1: