0%

javascript精华代码

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
const mapLimit = (tasks, concurrency, debug, callback) => {
let running = 0;
let completed = 0;
let index = 0;
let next = () => {
while (completed < tasks.length && running < concurrency) {
let task = tasks[index++];
task(() => {
running--;
completed++;
if (completed == tasks.length) {
return callback()
}
next();
})
running++;
}
}
next()
}

const chainAsync = (tasks) => {
let index = 0;
let last = tasks[tasks.length - 1];
const next = () => {
let fn = tasks[index++];
fn === last ? fn() : fn(next);
};
next();
}

EXAMPLES

1
2
3
4
5
6
7
8
9
10
11
12
13
chainAsync([
next => {
console.log('0 seconds');
setTimeout(next, 1000);
},
next => {
console.log('1 second');
setTimeout(next, 1000);
},
() => {
console.log('2 second');
}
]);

滑动到顶部

1
2
3
4
5
6
7
8
const scrollToTop = () => {
let c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 1) {
window.scrollTo(0, c - c / 10);
requestAnimationFrame(scrollToTop)
}
}
scrollToTop()

科里化函数

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
const curry = (fn, arity = fn.length, ...args) => 
arity < args.length ? fn(...args): curry.bind(null,fn,arity,...args)

// debounce
const debounce = (fn, ms = 0) => {
let timeoutId;
return function(...args){
clearTimeout(timeoutId);
timeoutId = setTimeout(()=>{
fn.call(this,...args)
},ms)
}
}

window.onresize = debounce(()=>{
console.log(window.innerHeight)
console.log(window.innerWidth)
},1200)

// throttle
const throttle = (fn, ms = 200) => {
let date = Date.now();
return function(...args){
let d = Date.now();
if (d - date < ms) return
date = d;
fn.apply(this,args)
}
}

const throttle2 = (fn, wait) => {
let inThrottle, lastFn, lastTime;
return function() {
const context = this,
args = arguments;
if (!inThrottle) {
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
}
};
};


## hz 函数执行每秒次数
```javascript
const hz = (fn, iterations = 100) => {
let start = performance.now();
for(let i = 0; i<iterations; i++) fn();
let end = performance.now();
return (1000 * iterations) / (end - before);
}

// memorize
const memorize = (fn) => {
const cache = new Map();
const cached = function(val){
return cache.get(val) ? cache.get(val) : cache.set(val,fn.apply(this,val)) && cache.get(val)
}
cached.cache = cache;
return cached;
}

// once
const once = (fn) => {
let started = false;
return function(...args){
if(started) return;
started = true;
return fn.apply(this,args);
}
}

const runPromisesInSeries = tasks => tasks.reduce((prev,next)=>prev.then(next),Promise.resolve())
const delay = (delay) => new Promise(resolve=>setTimeout(()=>{
resolve();
console.log(`${delay} delayed...`)
},delay))

runPromisesInSeries([()=>delay(1000),()=>delay(200),()=>delay(1200)])
.then(console.log)

数据分组

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
const chunk = (arr,size) => 
Array.from({length:Math.ceil(arr.length / size)},(val,idx)=>
arr.slice(idx*size,idx*size + size)
);

const chunk2 = (arr,size) => {
let ret = [];
let tmp = [];
for(let i = 0; i < arr.length; i++){
tmp.push(arr[i]);
if((i+1)%size == 0){
ret.push(tmp);
tmp = []
}
}
ret.push(tmp);
return ret
}
// chunk2的性能居然比chunk高了3倍左右

const countNum = (arr) => arr.reduce((acc,next)=>{
// acc[next] = acc[next] ? acc[next] : 1
acc[next] = (acc[next] || 0) + 1;
return acc
},{})


const deepFlatten = arr => [].concat(...arr.map(v=>(Array.isArray(v)?deepFlatten(v):v)))

const deepFlatten2 = (arr) => {
let tmp = [];
arr.forEach(a=>{
if(!Array.isArray(a)){
tmp.push(a)
}else{
tmp = [...tmp,...deepFlatten(a)]
}
})
return tmp
}


const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

const filterNonUnique2 = arr => [...new Set(arr)];

const flattenDepth = (arr, depth=1) =>
arr.reduce((prev,next)=>prev.concat(depth>1 && Array.isArray(next)?flattenDepth(next,depth -1):next),[])

const indexOfAll = (arr, val) =>
arr.reduce((prev,next,idx)=>next === val?[...prev,idx]:prev,[])

const countOfAll = (arr, val) =>
arr.reduce((prev,next,idx)=>next === val?prev+1:prev,0)