Here’s a fairly common situation:
- We have a list of values
- We need to use each value along with the next value
Generally, you end up with something like this:
Whether you use a
for(var i=0; i < arr.length; i++) or something like
array.reduce, you end up having to make sure your index is valid and doesn’t reach outside of the array. We intuitively know the code is brittle and unclear because we inevitably end up adding a comment that says something like
start with the second one or
stop at length - 1.
In cljs, there’s a handy-dandy function called
partition that elegantly solves this problem for us.
The most basic version of
partition only takes
n and the collection as arguments, splitting the collection into lists of size
partition provides another arity which takes a
step argument. With
step, we can say:
- Give me a list of
nitems, starting at the first position.
- Move forward
stepitems, then give me the next list of
So, if we want a list of current value and next value:
From there, it’s simple to use the current and next value:
Find this post useful? Share the love! Tweet