Skip to content

Instantly share code, notes, and snippets.

@yefremov
Last active March 11, 2017 09:48
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 yefremov/b8069e2f4c3f9cc57e1d53d5398c80de to your computer and use it in GitHub Desktop.
Save yefremov/b8069e2f4c3f9cc57e1d53d5398c80de to your computer and use it in GitHub Desktop.
If you know map, I will teach you monads
//
// 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