Created
May 11, 2017 16:43
-
-
Save joewalker/aee2df2ca3a4381bf1d83a2784a0c0f0 to your computer and use it in GitHub Desktop.
Annoying flow problem
This file contains 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
// @flow | |
type FlatMapMapper<In, Out> = (elem: In, index: number, arr: In[]) => Out | Out[]; | |
function flatMap<In, Out>(arr: In[], mapFunc: FlatMapMapper<In, Out>): Out[] { | |
const result = []; | |
for (const [ index, elem ] of arr.entries()) { | |
const x = mapFunc(elem, index, arr); | |
// We allow mapFunc() to return non-Arrays | |
if (Array.isArray(x)) { | |
result.push(...x); | |
} | |
else { | |
result.push(x); | |
} | |
} | |
return result; | |
} | |
function main() { | |
const input = [ 1, 2, 3 ]; | |
const output: string[] = flatMap(input, i => { return [ 'x' ]; }); | |
output.map(console.log); | |
} | |
main(); |
Author
joewalker
commented
May 11, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment