使用promise实现sleep
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
sleep(3000).then(() => {
console.log('JavaScript')
})
实现数组chunk功能
Array.prototype.chunk = function(num) {
const rv = []
let temp = []
for (let i = 0; i < this.length; i++) {
const element = this[i]
temp.push(element)
if ((i + 1) % num === 0 || i === this.length - 1) {
rv.push(temp)
temp = []
}
}
return rv
}
const arr = [1, 2, 3, 4, 5, 123, 21321]
const res = arr.chunk(3)
console.log(res)
快速排序
function quickSort(arr) {
if (arr.length <= 1) {
return arr
}
const pivotIndex = Math.floor(arr.length / 2)
const pivotValue = arr.splice(pivotIndex, 1)[0]
const left = []
const right = []
for (const item of arr) {
if (item < pivotValue) {
left.push(item)
} else {
right.push(item)
}
}
return quickSort(left).concat([pivotValue], quickSort(right))
}
const res = quickSort([10, 123, 132, 213, -1])
console.log(res)