Created
March 30, 2017 15:38
-
-
Save danvk/6845175246c9568621010d51588690ca to your computer and use it in GitHub Desktop.
Full sample code for "A Typed Chain" post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { chain } from 'chain'; | |
// Open this file in vscode and mouse over the symbols to see their types. | |
// Wrapped scalar. | |
const v = chain('hello chain!') | |
.value(); | |
// Calling methods on wrapped arrays. | |
const v2 = chain([1, 2, 3]) | |
.filter(x => x % 2 === 0) | |
.map(x => '' + x) | |
.value(); // string[] | |
// Mapping over an object produces an array. | |
const v3 = chain({a: 1, b: 2}) | |
.map((val, key) => val) // key's type is "a" | "b" | |
.value(); // number[] | |
// pluck / specialized map for arrays of objects. | |
const v4 = chain([1, 2, 3, 4]) | |
.map(val => ({val, sqr: val * val, str: '' + val})) | |
.map('str') | |
.value(); // string[] | |
// Use all the variables. | |
console.log(v, v2, v3, v4); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare module 'chain' { | |
interface WrappedValue<T> { | |
value(): T; | |
} | |
interface WrappedArray<T> extends WrappedValue<T[]> { | |
map<U extends object>(fn: (x: T, i: number) => U): WrappedArrayOfObjects<U>; | |
map<U>(fn: (x: T, i: number) => U): WrappedArray<U>; | |
filter(fn: (x: T, i: number) => boolean): WrappedArray<T>; | |
reduce<U>(fn: (acc: U, v: T) => U, base: U): WrappedValue<U>; | |
reduce<U extends object>(fn: (acc: U, v: T) => U, base: U): WrappedObject<U>; | |
} | |
interface WrappedObject<T> extends WrappedValue<T> { | |
mapValues<K extends keyof T, U>(fn: (v: T[K], k: K) => U): WrappedObject<{[k in keyof T]: U}>; | |
map<K extends keyof T, U>(fn: (x: T[K], k: K) => U): WrappedArray<U>; | |
filter<K extends keyof T>(fn: (x: T[K], k: K) => boolean): WrappedArray<T[K]>; | |
} | |
interface WrappedArrayOfObjects<U> extends WrappedArray<U> { | |
map<K extends keyof U>(fn: K): WrappedArray<U[K]>; // specialized map aka pluck | |
filter(fn: (x: U, i: number) => boolean): WrappedArrayOfObjects<U>; | |
} | |
function chain<T extends object>(obj: T[]): WrappedArrayOfObjects<T>; | |
function chain<T>(obj: T[]): WrappedArray<T>; | |
function chain<T extends object>(obj: T): WrappedObject<T>; | |
function chain<T>(obj: T): WrappedValue<T>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment