Last active
September 7, 2021 21:26
-
-
Save sgoguen/0bfc2a08de74e6719b2c7e125dc3363d to your computer and use it in GitHub Desktop.
A Hack Styled Operator
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
type Func<A, B> = (input: A) => B; | |
const _$ = undefined; | |
// If f and the input are provided, evalulate and return B[] | |
function map<A, B>(input: A[], f: Func<A, B>): B[]; | |
// If input is not provided, return a function ala partial application | |
function map<A, B>(input: undefined, f: Func<A, B>): Func<A[], B[]>; | |
function map<A, B>(input: A[] | undefined, f: Func<A, B>) { | |
if (input == undefined) { | |
return (input: A[]) => mapImpl(f, input); | |
} | |
return mapImpl(f, input); | |
} | |
function mapImpl<A, B>(f: Func<A, B>, input: A[]) { | |
const result: B[] = []; | |
for (const item of input) { | |
result.push(f(item)); | |
} | |
return result; | |
} | |
// Use the _$ placeholder to return a function instead of an array | |
const doubleArray = map(_$, (x: number) => 2 * x); | |
// Passing an array returns an array | |
const aDoubledArray = map([1, 2, 3, 4], (x: number) => 2 * x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment