-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2629-FunctionComposition.js
More file actions
67 lines (60 loc) · 1.8 KB
/
2629-FunctionComposition.js
File metadata and controls
67 lines (60 loc) · 1.8 KB
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
// 2629. Function Composition
// Given an array of functions [f1, f2, f3, ..., fn],
// return a new function fn that is the function composition of the array of functions.
// The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).
// The function composition of an empty list of functions is the identity function f(x) = x.
// You may assume each function in the array accepts one integer as input and returns one integer as output.
// Example 1:
// Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
// Output: 65
// Explanation:
// Evaluating from right to left ...
// Starting with x = 4.
// 2 * (4) = 8
// (8) * (8) = 64
// (64) + 1 = 65
// Example 2:
// Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1
// Output: 1000
// Explanation:
// Evaluating from right to left ...
// 10 * (1) = 10
// 10 * (10) = 100
// 10 * (100) = 1000
// Example 3:
// Input: functions = [], x = 42
// Output: 42
// Explanation:
// The composition of zero functions is the identity function
// Constraints:
// -1000 <= x <= 1000
// 0 <= functions.length <= 1000
// all functions accept and return a single integer
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function(functions) {
return function(x) {
let res = x
while(functions.length != 0) {
var fn = functions.pop();
res = fn(res)
}
return res
}
};
// best solution
var compose = function(functions) {
return function(x) {
let res = x
for (let item = functions.length-1; item >= 0; item--){
res = functions[item](res)
}
return res
}
};
/**
* const fn = compose([x => x + 1, x => 2 * x])
* fn(4) // 9
*/