Current and Next Values of a List
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 n
:
partition
provides another arity which takes a step
argument. With n
and step
, we can say:
- Give me a list of
n
items, starting at the first position. - Move forward
step
items, then give me the next list ofn
items. - Repeat.
So, if we want a list of current value and next value:
From there, it’s simple to use the current and next value:
Additional Notes
When working with partition
, it’s worth knowing about partition-by
and partition-all
as well. They’re similar but handle slightly different cases.