Just to add - although it's not totally official since tests haven't been fully 100% written/vetted yet - Sodium should be Fantasy-Land compatible, which means you can already use Sanctuary with it.
You can use lift and chain (a.k.a. "bind") operations on Cells
(these just leverage the built-in functions in Sodium)
Sanctuary comes with Maybe which matches what @the-real-blackh suggests with Optional
I couldn't figure out how to solve this cleanly with just pipe/compose
and chain
/bind
, and in this example it's really not doing anything you couldn't inherently do by just checking the value... but still, maybe it's incentive for stronger solutions - so here's a little fiddle showing it in action. @M-Pixel it doesn't perfectly match your sequence - read the next response to explain why. But for starters:
https://jsfiddle.net/dakom/mau512kg/
Once you ensure that you're sending Maybes into the Streams, the key lines are simply:
const nothingToZero = x => S.alt(x, S.Just(0))
const addCells =
S.lift2(a => b =>
a.isNothing && b.isNothing
? S.Nothing
: S.lift2(S.add, nothingToZero(a), nothingToZero(b)));
const combinedCell = addCells (cell1) (cell2);
Now I just need to go back in time and teach myself this stuff before I got into the habit of doing runtime checks on null/undefined