并发请求
出现情况:xhs一面
-
实现一个批量请求函数 multiRequest(urls, maxNum),要求如下:
- 要求最大并发数 maxNum
- 每当有一个请求返回,就留下一个空位,可以增加新的请求
- 所有请求完成后,结果按照 urls 里面的顺序一次打印
async function multiRequest(urls, maxNum) {
const results = [];
let count = 0;
while (count < urls.length) {
const promises = [];
for (let i = count; i < Math.min(count + maxNum, urls.length); i++) {
promises.push(fetch(urls[i]).then(res => res.text()));
}
const responses = await Promise.allSettled(promises);
for (let response of responses) {
if (response.status === 'fulfilled') {
results.push(response.value);
count++;
} else {
console.error(response.reason);
}
}
}
console.log(results);
}
multiRequest(
[
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3',
'https://jsonplaceholder.typicode.com/posts/4',
'https://jsonplaceholder.typicode.com/posts/5',
'https://jsonplaceholder.typicode.com/posts/6',
'https://jsonplaceholder.typicode.com/posts/7',
'https://jsonplaceholder.typicode.com/posts/8',
'https://jsonplaceholder.typicode.com/posts/9',
'https://jsonplaceholder.typicode.com/posts/10',
],
3
);
实现lodash的get方法
字节二面
function get(object, path, defaultValue = 'undefined')
{ //构造数组,将'['和']'替换成'.'
let newPath = [];
newPath = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
return newPath.reduce((a, b) => { return (a || {})[b] }, object) || defaultValue
}
红绿灯
dd二面
const generate =
({ color, delay }) =>
() =>
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(color);
}, delay);
});
const lightConf = [
{ color: "red", delay: 3000 },
{ color: "green", delay: 2000 },
{ color: "yellow", delay: 1000 },
];
const promises = lightConf.map(generate);
const light = async () => {
while(true){
for(const promise of promises){
const color = await promise()
console.log(color);
}
}
}
light()
flat函数
字节一面
const flat = (arr: any[], deep = Infinity) => {
if(deep === 0) return arr
return arr.reduce(
(total, next) =>
total.concat(Array.isArray(next) ? flat(next, deep - 1) : next),
[]
);
};
promisify
字节一面
const promisify = (fn)=>function (...args) {
return new Promise((resolve,reject)=>{
args.push(function(err,data){
if(err) reject(err)
resolve(data)
})
fn(...args)
})
}
子数组最大和
function maxSubArray(nums: number[]): number {
let max = nums[0];
let prev = nums[0];
for (let i = 1;i<nums.length;i++){
prev = Math.max(nums[i],prev+nums[i])
max = Math.max(prev,max)
}
return max
};
深拷贝
const deepClone = <T extends object >(obj: T, map = new WeakMap()): T => {
if (obj === null || obj === undefined || typeof obj !== "object") return obj;
if (map.has(obj)) return map.get(obj);
const clonedObj = Array.isArray(obj)
? []
: Object.create(Object.getPrototypeOf(obj));
const keys = Reflect.ownKeys(obj);
for (const key of keys) {
if (obj[key] !== null && typeof obj[key] === "object") {
clonedObj[key] = deepClone(obj[key], map);
} else {
clonedObj[key] = obj[key];
}
}
return clonedObj;
};
科里化
const curryIt = (fn:Function):Function=>{
const paramList:any[] = []
function foo(...args){
paramList.push(...args)
if(paramList.length === fn.length){
return fn(...paramList)
}else {
return foo
}
}
return foo
}
快速排序
const quickSort = (arr,l,r)=>{
if(l === r) return
let i = l-1,j=r+1
const mid = arr[l+r >> 1]
while(i<j){
while(arr[++i]<mid) continue;
while(arr[--j]>mid) continue;
if(i<j) [arr[i],arr[j]] = [arr[j],arr[i]]
}
quickSort(arr,l,j)
quickSort(arr,j+1,r)
}
const arr = [1,25,2,5,6,2,1]
quickSort(arr,0,arr.length-1)