Skip to content

Instantly share code, notes, and snippets.

@xeptore
Last active April 21, 2020 22:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeptore/a49eca1a3b894030c9687440b9eacf04 to your computer and use it in GitHub Desktop.
Save xeptore/a49eca1a3b894030c9687440b9eacf04 to your computer and use it in GitHub Desktop.
my fp learning tips and quick recaps

FP Tips and Quick Recaps

Currying

const add = (x) => (y) => x + y;
const addTen = add(10);
const incerement = add(1)

console.log(addTen(4)); // 14
console.log(incremenet(5)); // 6

Monoids

a type interface that implements two following methods:

  • .concat(arg) (returns concatenation result)
  • .empty() (returns empty/null new constructed instance)

Functors

interfaces implementing .map(fn) method and following a few laws:

  • chaining .map(fn)methods should have the same result of mapping once on on them with the composition of mapped functions. for example: fx.map(g).map(f) === fx.map(g(f()))
  • assuming function identity = x => x, running fx.map(identity) should have the same result of running identity(fx)

Monads

interfaces following these rules:

  • implementing .of(v) method, lifting v into the Type instance

  • implementing .chain(fn) (also called .flatMap, .bind).

  • Maybe

special kind of Monad s, with two base instances of:

  • Just(v) (in case of truthiness and existence)
  • Nothing (in case of nullability) Nothings are resistant to .map() and similar changes, which means running these kinds of methods on them, will cause returning the same Nothing instance.

these type of Monads are useful when if exists comes into chaining process, and we want to prevent any undefined-related error in not exists case and just want to pass the chain all the way down without any errors.

Maybe s might also have some function to finish the chaining process (sometimes called cata(onJustFn, onNothingFn)), receiving two argument for handling final two different cases. code sample: https://github.com/rametta/pratica/blob/master/src/maybe.js (source)
https://dev.to/rametta/basic-monads-in-javascript-3el3 (implementation)

  • Either

another special kind of Monad s, with Right or Left switches (sub-types) where both of these types extends Either type and like Maybe, one of these sub-types (Left) is resistant to change via .map(fn), .chain(fn), or other methods.
Either s are useful in error handling when chaining methods and it is desired to short-circuit the path in case of the first error, which is also called Railway Oriented Programming
implementation code sample:
https://egghead.io/lessons/javascript-composable-code-branching-with-either

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