Below is an excerpt from a Slack work rant from Feburary 4, 2020.
Over the last few weeks I have learned about some of the new additions to both ECMAScript 2019 and 2020 (for reasons!!!!) anyway, the following are relevant to an FP setting: flatMap flattens nested list structure then maps over the elements. Usage:
> let arr1 = ["Australia is", "on", "fire still"];
undefined
> arr1.map(x => x.split(" "));
[ [ 'Australia', 'is' ], [ 'on' ], [ 'fire', 'still' ] ]
> arr1.flatMap(x => x.split(" "));
[ 'Australia', 'is', 'on', 'fire', 'still' ]
flatMap
can also be used as a way to add or remove elements of the Array during a map.
> let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
> numbers.flatMap( n => (n % 3 === 0 && n % 2 === 0) ? ["must be six"] : (n % 4 === 0) ? ["multiple of four", n] : [n]);
[
1,
2,
3,
'multiple of four',
4,
5,
'must be six',
7,
'multiple of four',
8,
9,
10
]
- Nullish coalescing: const result = config ?? "default string" when config is null the value of result will be "default string".
- Optional chaining: allows you to safely access deeply nested attributes without the undefined or null checking boilerplate with predictable semantics:
> const comment = { message: "Buttigieg is an arrogant ass!", author: { nickname: "someuser", name: "Some Name Here", mojo: 4.2 }};
> const comment_author_name = comment.author?.name
... my version of nodejs (0.12) doesn't have this in yet, so it blows up but I have Nix so I could just do:
nix-shell -I nixpkgs=channel:nixos-unstable -p nodejs-14_x
However, TypeScript has this "feature" as a common abstraction already.
In Haskell and Purescript, we have been doing this in a referentially transparent way for years, of course, and generalized these ideas away from List or Option to a parametric polymorphic notion that gets a lot of bad press. It's the M-word! 🙂