26届秋招滴滴校招前端一面面经(3)

55 阅读2分钟

今天继续写在滴滴业务中台前端一面中遇到的js手写题

交通信号灯顺序控制实现

题干

根据提供的代码片段,实现交通信号灯按顺序依次亮起(红灯 → 绿灯 → 黄灯),每个灯亮 2 秒。

解题思路

利用 async/await 和 setTimeout 结合,定义三个异步函数分别对应红灯、绿灯、黄灯亮起的操作,在主函数中使用 await 等待每个函数执行完成,以实现按顺序亮起且间隔 2 秒的效果。

代码实现

// 定义信号灯函数
function red() {
    console.log("红灯");
}

function green() {
    console.log("绿灯");
}

function yellow() {
    console.log("黄灯");
}

// 使用 async/await 实现顺序控制
async function trafficLight() {
    // 红灯亮2秒
    red();
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 绿灯亮2秒
    green();
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 黄灯亮2秒
    yellow();
    await new Promise(resolve => setTimeout(resolve, 2000));
}

// 执行交通信号灯函数
trafficLight();

函数柯里化面试题目解析

题干描述

题目要求: 实现一个通用的函数柯里化工具函数 curry。给定一个普通函数,通过柯里化处理后,可以支持多种调用方式。 示例函数

const add = (a, b, c) => a + b + c;

期望调用方式

curriedAdd(1)(2)(3);    // 6
curriedAdd(1, 2)(3);    // 6
curriedAdd(1)(2, 3);    // 6
curriedAdd(1, 2, 3);    // 6

参考答案

实现代码

function curry(fn) {
    // 获取原函数的参数个数
    const arity = fn.length;
    
    return function curried(...args) {
        // 如果当前传入的参数数量 >= 原函数参数数量,直接执行
        if (args.length >= arity) {
            return fn.apply(this, args);
        } 
        // 否则返回一个新函数,继续接收剩余参数
        else {
            return function(...nextArgs) {
                return curried.apply(this, args.concat(nextArgs));
            };
        }
    };
}

// 使用示例
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);

// 测试各种调用方式
console.log(curriedAdd(1)(2)(3));     // 6
console.log(curriedAdd(1, 2)(3));     // 6
console.log(curriedAdd(1)(2, 3));     // 6
console.log(curriedAdd(1, 2, 3));     // 6

这个题是一个规定了形参数量的函数柯里化题目