A Pen by Michael Russell on CodePen.
Created
April 22, 2016 14:25
-
-
Save subhaze/733586836a4c3ec00c97661abf301962 to your computer and use it in GitHub Desktop.
flatMap [Array#reduce]
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
<pre style="padding: 20px"><code class="hljs js"> | |
let stuff = ['a', 'b', 'c', ['e', 'f', 'g']]; | |
function flatMap(list, projection){ | |
return list.reduce( (acc, curr) => | |
Array.isArray(curr) | |
? acc.concat(curr.map(projection)) | |
: acc.concat(projection(curr)) | |
, []); | |
} | |
console.log(flatMap(stuff, (x)=>x+'1')); | |
// ["a1", "b1", "c1", "e1", "f1", "g1"] | |
</code></pre> |
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
let stuff = ['a', 'b', 'c', ['e', 'f', 'g']]; | |
function flatMap(list, projection){ | |
return list.reduce( (acc, curr) => | |
Array.isArray(curr) | |
? acc.concat(curr.map(projection)) | |
: acc.concat(projection(curr)) | |
, []); | |
} | |
console.log(flatMap(stuff, (x)=>x+'1')); | |
// ["a1", "b1", "c1", "e1", "f1", "g1"] | |
hljs.initHighlightingOnLoad(); |
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
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> |
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
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/tomorrow-night-eighties.min.css" rel="stylesheet" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment