Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Last active May 27, 2020 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbbx6spp/61f9aa904003019aa8a77c3276e40d74 to your computer and use it in GitHub Desktop.
Save mbbx6spp/61f9aa904003019aa8a77c3276e40d74 to your computer and use it in GitHub Desktop.
An M-word work rant of work Slack February 2020 edition.

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! 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment