Functional Programming on 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
// Fibonachi with Functional Programming
var fibo = (function () {
var cache = { "0": 0, "1": 1 };

var func = function (n) {
if (typeof cache[n] === "number") {
result = cache[n];
} else {
result = cache[n] = func(n - 1) + func(n - 2);
}

return result;
};
return func;
})();

console.log(fibo(10));

// Another way, defining cacher first
// and then put factorial or fibonacci
var cacher = function (cache, func) {
var calculate = function (n) {
if (typeof cache[n] === "number") {
result = cache[n];
} else {
result = cache[n] = func(calculate, n);
}
return result;
};
return calculate;
};

var fact = cacher({ "0": 1 }, function (func, n) {
return n * func(n - 1);
});

var fibo = cacher({ "0": 0, "1": 1 }, function (func, n) {
return func(n - 1) + func(n - 2);
});

console.log(fact(10));
console.log(fibo(10));

// call method
function example() {
console.log(Array.prototype.join.call(arguments));
}

example(1, "string", true); // "1,string,true"

// Currying
function calculate(a, b, c) {
return a * b + c;
}

function curry(func) {
var args = Array.prototype.slice.call(arguments, 1);

return function () {
return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
};
}

var new_func1 = curry(calculate, 1);