网易雷火前端笔试
2023.4.22
1.实现一个本地的 add 方法,用于计算任意数量数字的加法,其中每次加法运算都需要通过调用远程API的 addRemote 方法来实现。addRemote 方法能够计算两个数字的和,实现如下:
js
const addRemote = async(a, b) => new Promise(resolve => {
setTimeout(() => resolve(a + b), 200);
});
请在以下代码框架中实现 add 方法,它的输入是 n 个数字(不定长度参数)。请确保你的实现能够最优地完成参数中的所有数字相加。最后,使用示例验证 add 方法的运行结果。
js
async function add(...args) {
//你的实现
}
//请用示例验证运行结果
add([1, 2])
.then(result => {
console.log(result); //3
});
add([3, 5, 2])
.then(result => {
console.log(result); //10
})
例如:
add(1,2,3) 返回6;
add(1, 1,1,1,1,1,1,1) 返回 8。
实现如下:
js
const addRemote = async (a, b) => {
return new Promise(resolve => {
setTimeout(() => resolve(a + b), 200);
});
};
async function add(...arr) {
const promises = [];
// 遍历参数列表,发起多个异步请求
for (let i = 0; i < arr.length; i += 2) {
const a = arr[i];
const b = arr[i + 1] || 0;
promises.push(addRemote(a, b));
}
// 等待所有异步请求完成后,将结果进行累加
const results = await Promise.all(promises);
return results.reduce((sum, num) => sum + num, 0);
}
// 使用示例
add(1, 2).then(result => {
console.log(result); //3
});
add(3, 5, 2).then(result => {
console.log(result); //10
});
add(1, 2, 3).then(result => {
console.log(result); //6
});
add(1, 1, 1, 1, 1, 1, 1, 1).then(result => {
console.log(result); //8
});
2.网易雷火正在实现一个AI自动化工具,用于用户构建模拟虚拟世界各种元素交互的场景,有一个需求是需要编写一个算法来判断游戏场景中的两段路线(直线)是否相交。路线表示为路线AB和路线CD,路线AB的起点坐标为(X1,Y1),终点坐标为(X2,Y2),路线CD的起点坐标为(A1,B1),终点坐标为(A2,B2)。请您参照这个场景描述,使用JavaScript 编程,在不引入第三方库的情况下实现判断两段路线是否有交点的算法。
示例1:
输入:
[0, 0],[3, 3],[0, 2],[2, 0]
输出:
true
示例2:
输入:
[0, 0],[5, 5],[5, 6],[6, 7]
输出:
false
实现如下:
js
const isIntersect = ([[x1, y1], [x2, y2]], [[x3, y3], [x4, y4]]) => {
// 判断两条直线是否平行
const deltaABx = x2 - x1;
const deltaABy = y2 - y1;
const deltaCDx = x4 - x3;
const deltaCDy = y4 - y3;
const crossProduct = deltaCDy * deltaABx - deltaABy * deltaCDx;
if (crossProduct === 0) {
return false;
}
// 计算交点位置
const k1 = deltaABy / deltaABx;
const b1 = y1 - k1 * x1;
const k2 = deltaCDy / deltaCDx;
const b2 = y3 - k2 * x3;
const x = (b2 - b1) / (k1 - k2);
const y = k1 * x + b1;
// 判断交点是否在两条线段的范围内
return (x >= Math.min(x1, x2) && x <= Math.max(x1, x2) &&
y >= Math.min(y1, y2) && y <= Math.max(y1, y2) &&
x >= Math.min(x3, x4) && x <= Math.max(x3, x4) &&
y >= Math.min(y3, y4) && y <= Math.max(y3, y4));
};
console.log(isIntersect([[0, 0], [3, 3]], [[0, 2], [2, 0]])); // true
console.log(isIntersect([[0, 0], [5, 5]], [[5, 6], [6, 7]])); // false
3.无重复字符的最长子串(力扣)。
snowy