面经 腾讯 一面手撕题

98 阅读1分钟

腾讯 一面

闭包实现调用plus时返回的值加一(闭包)

function createPlus() {
    let counter = 0
​
    return function(){
        return ++counter
    }
}
​
const plus = createPlus()
​
console.log(plus());//1
console.log(plus());//2
console.log(plus());//3

找出字符串中最长有效单词的长度(正则匹配)

function findLongWorldLength(str){
    // 拆分
    let words = str.split(/\W+/)
    let maxLength = 0
​
    // 识别
    for(let i = 0;i<words.length;i++){
        let word = words[i].match(/[a-zA-Z]/g)
        if(word !== null){
            let length = word.length
            maxLength = Math.max(length,maxLength)
        }
    }
    return maxLength
}
​
// 示例用法
let str = "Hello, world! This is a test string.";
console.log(findLongWorldLength(str));

判断两对象是否相同(递归)

function isObject(value) {
    return typeof value === "object" && value !== null
}
​
function deepEqual(obj1,obj2){
    if(obj1 === obj2){
        return true
    }
​
    if(isObject(obj1)&& isObject(obj2)){
        const keys1 = Object.keys(obj1)
        const keys2 = Object.keys(obj2)
​
        if(keys1.length !== keys2.length){
            return false
        }
​
        for(let key of keys1){
            if(!deepEqual(obj1[key],obj2[key])){
                return false
            }
        }
        return true
    }
    return false
​
}
​
// 示例用法
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const obj3 = { a: 1, b: { c: 3 } };
​
console.log(deepEqual(obj1, obj2)); // 输出:true
console.log(deepEqual(obj1, obj3)); // 输出:false

扁平数组转树形

function buildTree(flatArray) {
     const map = new Map()
     const root = []
​
     for(const item of flatArray){
        map.set(item.id,{...item,children:[]})
        if(!item.parentId){
            root.push(map.get(item.id))
        }
     }
​
     for(const item of flatArray){
        if(item.parentId){
            const parent = map.get(item.parentId)
            if(parent){
                parent.children.push(map.get(item.id))
            }
        }
     }
​
     return root
​
}
​
// Example usage
const flatArray = [    { id: 1, name: "A", parentId: null },    { id: 2, name: "B", parentId: 1 },    { id: 3, name: "C", parentId: 1 },    { id: 4, name: "D", parentId: 2 },    { id: 5, name: "E", parentId: 3 },    { id: 6, name: "F", parentId: 4 },    { id: 7, name: "G", parentId: 5 }];
​
const tree = buildTree(flatArray);
console.log(JSON.stringify(tree, null, 2));
​