Last active
March 11, 2017 09:48
-
-
Save yefremov/b8069e2f4c3f9cc57e1d53d5398c80de to your computer and use it in GitHub Desktop.
If you know map, I will teach you monads
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
// | |
// https://www.youtube.com/watch?v=2jp8N6Ha7tY | |
// | |
// Capitalize the first letter of a string, or all words in a string. | |
function capitalize(str) { | |
return str.charAt(0).toUpperCase() + str.substring(1); | |
} | |
// Arrays | |
var protuguese = [ | |
'galinha', | |
'vaca', | |
'milho' | |
]; | |
protuguese.map(capitalize); | |
// => ["Galinha", "Vaca", "Milho"] | |
// Tree | |
var familyTree = { | |
value: 'mattias', | |
nodes: [ | |
{ | |
value: 'eva', | |
nodes: [ | |
{ value: 'ove' }, | |
{ value: 'sonja' }, | |
] | |
}, | |
{ | |
value: 'maths', | |
nodes: [ | |
{ value: 'anna' }, | |
{ value: 'gustav' }, | |
] | |
} | |
] | |
}; | |
function mapTree(node, mapper) { | |
return { | |
value: mapper(node.value), | |
nodes: node.nodes | |
? node.nodes.map(function (node) { | |
return mapTree(node, mapper); | |
}) | |
: null | |
}; | |
} | |
mapTree(familyTree, capitalize); | |
// => { | |
// value: 'Mattias', | |
// nodes: [ | |
// { | |
// value: 'Eva', | |
// nodes: [ | |
// { value: 'Ove' }, | |
// { value: 'Sonja' }, | |
// ] | |
// }, | |
// { | |
// value: 'Maths', | |
// nodes: [ | |
// { value: 'Anna' }, | |
// { value: 'Gustav' }, | |
// ] | |
// } | |
// ] | |
// }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment