2 ms·
If you have a function that works on numbers: const add3 = val => val + 3; and need to make it work on optional<number>, all you need is map const op
by bern4444 6y ago
If you have a function that works on numbers:
const add3 = val => val + 3;
and need to make it work on optional<number>, all you need is map
const optionally6 = Some(3).map(add3);
where Optional.map works just like array.map. Its the same idea when you map over an array:
const add3 = val => val + 3;
[1, 2, 3].map(add3);
Though an even nicer approach is to use static versions of these functions:
const add3 = val => val + 3;
const add3ToArrayVals = Array.map(add3);
const add3ToOptionals = Optional.map(add3);
const someSix = add3ToOptionals(Some(3)); // Some(6);
const some456 = add3ToArrayVals([1, 2, 3]);// [4, 5, 6];
This is just a static version of Array.map (doesn't officially exist in JS but is trivial to write) or Optional.map
const staticArrayMap = (fn) => (array) => array.map(fn);
Edit to add, from your example
func(some(3))
would just become
some(3).map(func);
and then you can do
some(3)
.map(func)
.map(otherFunc)
.map(yetAnotherFunc);