Repeating the previous one in the cycle

Is there a good idiomatic way to iterate through an array in Coffeescript, but access the current and next element inside the loop? For example, in Python, you can:

[f(current, next) for current, next in zip(a, a[1:])]

      

+3


source to share


2 answers


How about something like this?



array = ['a', 'b', 'c', 'd']

for value, index in array
 current = value
 next = if array[index+1] then array[index+1] else null
 alert "#{current} at #{index} #{next}"

      

+1


source


I went with this:

(f(a[i], a[i-1]) for i in [1..segment.length-1])

      



I couldn't think of anything better.

0


source







All Articles