腾讯 一面
闭包实现调用plus时返回的值加一(闭包)
function createPlus() {
let counter = 0
return function(){
return ++counter
}
}
const plus = createPlus()
console.log(plus());
console.log(plus());
console.log(plus());
找出字符串中最长有效单词的长度(正则匹配)
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));
console.log(deepEqual(obj1, obj3));
扁平数组转树形
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
}
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));