Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created January 17, 2019 22:54
Show Gist options
  • Save christianscott/58576bcc26ccdf7e42c8ec8af50dfc34 to your computer and use it in GitHub Desktop.
Save christianscott/58576bcc26ccdf7e42c8ec8af50dfc34 to your computer and use it in GitHub Desktop.
Proving a (terrible) point
type UnaryFunction<A, B> = (arg: A) => B
function pipe<T, A, B, C, D, E, F>(op1: UnaryFunction<T, A>, op2: UnaryFunction<A, B>, op3: UnaryFunction<B, C>, op4: UnaryFunction<C, D>, op5: UnaryFunction<D, E>, op6: UnaryFunction<E, F>): UnaryFunction<T, F>;
function pipe<T, R>(...operations: UnaryFunction<any, any>[]): UnaryFunction<T, R> {
return initial => operations.reduce((prev, nextFn) => nextFn(prev), initial)
}
const curry2 = <A, B, C>(fn: (a: A, b: B) => C) => (a: A) => (b: B) => fn(a, b)
const filter = curry2(<T>(fn: UnaryFunction<T, boolean>, arr: T[]) => arr.filter(fn))
const map = curry2(<T>(fn: UnaryFunction<T, boolean>, arr: T[]) => arr.map(fn))
const pick = curry2(<T extends { [key: string]: any }>(key: keyof T, obj: T) => obj[key])
// isInputComponent : Component -> Bool
const isInputComponent = (component: { type: string }) => component.type.endsWith('input')
// getLabel : Component -> String
const getLabel = pick('label')
// doubleUp : a -> (a, a)
const doubleUp = x => [x, x]
const log = fn => (...args) => {
console.log('called with:', args)
return fn(...args)
}
const call = log((fn, arg) => fn(arg))
const zip = (xs, ys) =>
Array
.from({ length: Math.min(xs.length, ys.length) }, (_, i) => i)
.map(i => [xs[i], ys[i]])
const zipMap = curry2((fns, vals) => zip(fns, vals).map(call))
const id = x => x
const unique = arr => [...new Set(arr)]
const uncurry = curry2((fn, args) => fn(...args))
const len = (o: { length: number }) => o.length
const equals = (a, b) => a === b
const isEveryLabelUnique = pipe(
filter(isInputComponent),
map(getLabel),
doubleUp,
zipMap([id, unique]),
zipMap([len, len]),
uncurry(equals),
)
console.log(
isEveryLabelUnique([
{ type: 'text_input', label: 'What is your name?' },
{ type: 'select_input', label: 'What is your name?' },
{ type: 'other' },
])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment