Skip to content

Commit 62857a9

Browse files
committed
fp fns
1 parent f4372eb commit 62857a9

File tree

5 files changed

+88
-0
lines changed

5 files changed

+88
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function autoPartial(fn) {
2+
return function (...args) {
3+
const totalArgsNeeded = fn.length;
4+
if (args.length >= totalArgsNeeded) {
5+
return fn(...args);
6+
}
7+
return autoPartial(fn.bind(null, ...args));
8+
}
9+
}
10+
11+
12+
function _multiply(x, y, z) {
13+
return x * y * z;
14+
}
15+
16+
console.log(autoPartial(_multiply)(10)(8)(5));
17+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function measureExecutionTime(fn) {
2+
return function(...args) {
3+
console.time(fn.name);
4+
const res = fn(...args);
5+
console.timeEnd(fn.name);
6+
return res;
7+
};
8+
}
9+
10+
function _fib(n) {
11+
if (n < 2) {
12+
return n;
13+
}
14+
return fib(n-1) + fib(n-2);
15+
}
16+
17+
const fib = measureExecutionTime(_fib);
18+
19+
console.log(fib(30));
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
*
3+
* @param {Function} fn
4+
* @returns
5+
*/
6+
export function printOnInvoke(fn) {
7+
return (...args) => {
8+
console.log(fn.name, args);
9+
return fn(...args);
10+
}
11+
}
12+
13+
function add(a, b) {
14+
return a + b;
15+
}
16+
17+
const updatedAdd = printOnInvoke(add);
18+
19+
console.log(updatedAdd(10, 20));

javascript-specific/functional-programming/pure-functions/readme.md renamed to javascript-specific/functional-programming/readme.md

File renamed without changes.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function urlBuilder(protocol) {
2+
return function (subdomain) {
3+
return function (domain) {
4+
return function (...paths) {
5+
return function (params = {}) {
6+
const queryParams = Object.keys(params).reduce((query, curr, index) => query + `${index === 0 ? '' : '&'}${curr}=${params[curr]}`, '');
7+
let url = `${protocol}://${subdomain}.${domain}`;
8+
if (paths.length) {
9+
url += `/${paths.join('/')}`;
10+
}
11+
if (queryParams) {
12+
url += `?${queryParams}`
13+
}
14+
return url;
15+
}
16+
}
17+
}
18+
}
19+
}
20+
21+
const http = urlBuilder('http');
22+
const https = urlBuilder('https');
23+
24+
const www = https('www');
25+
const google = www('google.com');
26+
27+
const path1 = google('some', 'path');
28+
const finalUrlWithParams = path1({
29+
a: 10,
30+
b: "hello",
31+
})
32+
33+
console.log(finalUrlWithParams);

0 commit comments

Comments
 (0)