Skip to content

Instantly share code, notes, and snippets.

@sgoguen
Last active September 7, 2021 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgoguen/0bfc2a08de74e6719b2c7e125dc3363d to your computer and use it in GitHub Desktop.
Save sgoguen/0bfc2a08de74e6719b2c7e125dc3363d to your computer and use it in GitHub Desktop.
A Hack Styled Operator
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