一些常见函数


1.快速排序

标准版本:

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
function quickSort(list, start, end) {
if (end <= start) {
return;
}
let left = start;
let right = end;
while (left < right) {
while (list[right] > list[start]) {
right--;
}
while (list[left] <= list[start]) {
left++;
}
if (left < right) {
let temp = list[left];
list[left] = list[right];
list[right] = temp;
}
}
let temp = list[right];
list[right] = list[start];
list[start] = temp;
quickSort(list, start, right - 1);
quickSort(list, right + 1, end);
}

另一种实现方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function quickSort(list) {
if (list.length <= 1) {
return list;
}
let left = [];
let right = [];
for (let i = 1; i < list.length; ++i) {
if (list[i] <= list[0]) {
left.push(list[i]);
} else {
right.push(list[i]);
}
}
return quickSort(left).concat(list[0], quickSort(right));
}
// 也可以用ES6数组的filter方法缩写上述代码
function quickSort(list) {
if (list.length <= 1) {
return list;
}
let left = list.filter((x, i) => x <= list[0] && i != 0);
let right = list.filter((x) => x > list[0]);
return quickSort(left).concat(list[0], quickSort(right));
}

2.防抖

在规定时间后执行函数,如果函数在规定时间内再次被触发,将重新计时。

1
2
3
4
5
6
7
8
9
10
11
function debounce(func, gapTime = 1500) {
let timer = null;
return function() {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, arguments);
}, gapTime)
}
}

3.节流

规定时间内只执行一次函数。

1
2
3
4
5
6
7
8
9
10
function throttle(func, gapTime = 1500) {
let lastTime = null
return function() {
let nowTime = Date.now()
if (nowTime - lastTime > gapTime || !lastTime) {
func.apply(this, arguments)
lastTime = nowTime
}
}
}