-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (80 loc) · 2.22 KB
/
index.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
88
89
90
91
92
93
94
95
96
const partial = (fn, ...args) => (...moreArgs) => fn.apply(null, args.concat(moreArgs))
const compose = (...functions) => (data) => functions.reduceRight((acc, fn) => fn(acc), data)
const inc = x => x + 1
const identity = x => x
const map = f => x => Array.prototype.map.call(x, f)
const filter = f => x => Array.prototype.filter.call(x, f)
const sort = f => x => Array.prototype.sort.call(x, f)
const join = seperator => list => Array.prototype.join.call(list, seperator)
const set = prop => obj => value => (obj[prop] = value, obj)
const setR = prop => value => obj => (obj[prop] = value, obj)
const pick = key => obj => obj[key];
function throttle(f, ms) {
let isThrottled = false;
let savedArgs;
let savedThis;
return function wrapper() {
if(isThrottled) {
savedThis = this;
savedArgs = arguments;
return;
}
f.apply(this, arguments);
isThrottled = true;
setTimeout(function() {
isThrottled = false;
if(savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms)
}
}
function debounce(f, ms) {
let isCoolDown = false;
return function() {
if(isCoolDown) return;
f.apply(this, arguments)
isCoolDown = true;
setTimeout(() => isCoolDown = false, ms)
}
}
// promisify(f, true) to get array of results
function promisify(f, manyArgs = false) {
return function (...args) {
return new Promise((resolve, reject) => {
function callback(err, ...results) { // our custom callback for f
if (err) {
return reject(err);
} else {
// resolve with all callback results if manyArgs is specified
resolve(manyArgs ? results : results[0]);
}
}
args.push(callback);
f.call(this, ...args);
});
};
};
const sortingFns = {
'string': (a, b) => a.localeCompare(b),
'number': (a, b) => a - b,
'boolean': (a, b) => a === b ? 0 : a ? -1 : 1
}
module.exports = {
partial,
compose,
inc,
identity,
map,
filter,
sort,
join,
set,
setR,
pick,
throttle,
debounce,
promisify,
sortingFuns
}