Skip to content

Instantly share code, notes, and snippets.

@morozovamv
Created October 22, 2018 10:04
Show Gist options
  • Save morozovamv/cf499d2b8f465247c8d006729a5c3dc8 to your computer and use it in GitHub Desktop.
Save morozovamv/cf499d2b8f465247c8d006729a5c3dc8 to your computer and use it in GitHub Desktop.
Road to monad: functor
import { Function1 } from 'fp-ts/lib/function';
import { Option, none, some } from 'fp-ts/lib/Option';
// T -> T
const identity = <T>(v: T): T => v;
// (B -> C, A -> B) -> A -> C
const compose = <A, B, C>(f: (Function1<B, C>), g: Function1<A, B>) => (x: A): C => f(g(x));
const plusFive = (n: number): number => n + 5;
const numberToString = (n: number): string => `${n}`;
const plusFiveToNumber = compose(numberToString, plusFive);
// Array
// (A -> B) -> Array<A> -> Array<B>
const map = <A, B, C extends Array<A>>(f: Function1<A, B>) => (U: C): Array<B> => U.map(f);
const array = [1, 2, 3];
// Identity Law
const identityArray = map(identity)(array); // [1, 2, 3]
// Compose Law
const composeArrays = compose(map(numberToString), map(plusFive))(array); // ['6', '7', '8']
const composeArrays2 = map(plusFiveToNumber)(array); // ['6', '7', '8']
// Option = Some | None
const data = some(100);
// Identity Law
const identityOption = data.map(identity); // some(100)
// Compose Law
const composeOptions = data.map(plusFive).map(numberToString); // some('105')
const composeOptions2 = data.map(value => plusFiveToNumber(value)); // some('105')
// Example
type TPerson = { name: string, avatarUrl: Option<string> };
const person: TPerson = { name: 'Oleg', avatarUrl: none };
const getAvatarBG = (url: string): string => `url(${url})`;
const avatarBG = person.avatarUrl.map(getAvatarBG);
// logs
{
console.group('Array');
console.group('Identity law');
console.log('initial data: ', array);
console.log('after identity: ', identityArray);
console.groupEnd();
console.group('Compose law');
console.log(composeArrays);
console.log(composeArrays2);
console.groupEnd();
console.groupEnd();
console.group('Option');
console.group('Identity law');
console.log('identityOption: ', data);
console.log('after identity: ', identityOption);
console.groupEnd();
console.group('Compose law');
console.log(composeOptions);
console.log(composeOptions2);
console.groupEnd();
console.groupEnd();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment