The Bookkeeping Pattern
Published ....
Last modified ....
Share this post on BlueskySee discussion on Bluesky
I've found myself lately working with a decent number of Array.prototype.reduce and useReducer uses. With both of these, I've been reaching for what I'm going to call the "bookkeeping pattern"[1]Jump to footnote.
Before diving into the code, I wanted to step back a bit and outline when and where this pattern could be useful.
Let's start with a simple example, imagine you have an array of strings, that can contain some duplicates, and we want to narrow it down to only an array of unique strings. Sure, I know you could also import {uniq} from 'lodash' and be done with it (or use [...new Set([...array])]), but let's say that we wanted to implement this logic via Array.prototype.reduce for a minute!
In order to remove the duplicates, we need some way to know if we've "seen" a value before, while we could use some external value for that, we could also stash that value within the result of our reducer. Essentially we manage our own bookkeeping within the reduce call!
Let's look at some code: