-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctional.js
87 lines (71 loc) · 2.25 KB
/
functional.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict'
let animals = [
{ name: 'Luna', species: 'cat'},
{ name: 'Fifi', species: 'dog'},
{ name: 'Bob', species: 'fish'},
{ name: 'Pidgey', species: 'bird'},
{ name: 'Munk', species: 'chipmunk'},
{ name: 'Lulu', species: 'cat'},
]
let isCat = animal => (animal.species === 'cat')
let cats = animals.filter(animal => animal.species === 'cat') //smaller array
let add_animals = animals.map((animal) => animal.name) //a mutated array
let total_cats = animals.reduce((cat_count, animal) => cat_count += (isCat(animal) ? 1 : 0), 0) //an object
// console.log(cats);
// console.log(add_animals);
// console.log(total_cats);
//currying example
let curry_recipe = base => protein => sauce => ('This is a ' + sauce + ' curry with ' + protein + ' on ' + base)
//console.log(curry_recipe('rice')('tofu')('masala'));
let tree = [
{id: 'animal', 'parent' : null},
{id: 'mammal', 'parent' : 'animal'},
{id: 'cat', 'parent' : 'mammal'},
{id: 'dog', 'parent' : 'mammal'},
{id: 'fish', 'parent' : 'animal'},
{id: 'husky', 'parent' : 'dog'},
{id: 'lion', 'parent' : 'cat'},
{id: 'leopard', 'parent' : 'cat'},
{id: 'clown fish', 'parent' : 'fish'},
{id: 'nemo', 'parent' : 'clown fish'},
{id: 'fluffy', 'parent' : 'husky'},
]
let makeTree = (categories, parent) => {
let node = {}
categories
.filter(c => c.parent === parent)
.forEach(c => node[c.id] = makeTree(categories, c.id))
return node
}
console.log(JSON.stringify(makeTree(tree, null), null, 2));
// Promises
function loadImage(url) {
return new Promise((resolve, reject) => {
let image = new Image()
image.onload = function() {
resolve(image)
}
image.onerror = function() {
let message =
'Could not load image at ' + url
reject(new Error(msg))
}
image.src = url
})
}
let addImg = (src) => {
let imgElement =
document.createElement("img")
imgElement.src = src
document.body.appendChild(imgElement)
}
Promise.all([
loadImage('https://unsplash.it/200/300/?random'),
loadImage('https://unsplash.it/200/300/?random'),
loadImage('https://unsplash.it/200/300/?random'),
loadImage('https://unsplash.it/200/300/?random')
]).then((images) => {
images.forEach(img => addImg(img.src))
}).catch((error) => {
// handle error later
})