我在近期求职中遇到的前端面试问题及其解法
共 13302字,需浏览 27分钟
·
2020-09-18 13:27
在今天的文章中,我想跟大家聊聊自己最近在 COVID-19 疫情下的求职经历中遇到的问题。另外,我还把自己的准备工作整理成一份资源清单供大家参考。
这些问题主要分为以下几个小节。
JS
编码
应用题
杂项
这里提出的解法并不能直接使用,只代表我个人的思维方式与粗略概念。大家不妨尝试用自己的办法解决这些问题。
1) 给定一个深度为 n 的多维数组,将其展平。展平后,将其作为 array 实例上的可用方法。
/**
* [1,2,[3,4]] -> [1,2,3,4]
*/
let arr = [1,2,[3,4, [5,6, [7, [8, 9, 10]]]]]
function flatten(arr) {
return arr.reduce(function(acc, next){
let isArray = Array.isArray(next)
return acc.concat(isArray ? flatten(next) : next)
}, [])
}
if (!Array.prototype.flatten) {
Array.prototype.flatten = function() {
return flatten(this)
}
}
console.log(arr.flatten());
2) 从零开始创建一项 promise。
class CustomPromise {
state = "PENDING"
value = undefined
thenCallbacks = []
errorCallbacks = []
constructor(action) {
action(this.resolver.bind(this), this.reject.bind(this))
}
resolver(value) {
this.state = "RESOLVED"
this.value = value
this.thenCallbacks.forEach((callback) => {
callback(this.value)
})
}
reject(value) {
this.state = "REJECTED"
this.value = value
this.errorCallbacks.forEach((callback) => {
callback(this.value)
})
}
then(callback) {
this.thenCallbacks.push(callback)
return this
}
catch (callback) {
this.errorCallbacks.push(callback)
return this
}
}
let promise = new CustomPromise((resolver, reject) => {
setTimeout(() => {
const rand = Math.ceil(Math.random(1 * 1 + 6) * 6)
if (rand > 2) {
resolver("Success")
} else {
reject("Error")
}
}, 1000)
})
promise
.then(function(response){
console.log(response)
})
.catch(function(error){
console.log(error)
})
3) 按平均评分及名称对电影列表进行过滤。按电影对象内的任意字段对过滤后的列表进行排序。
// O(M)
function getMovies() {
return []; // [{id, name, year}]
}
// O(R)
function getRatings() {
return []; // [{id, movie_id, rating}] 0 <= rating <= 10 // e.g 9.3
}
/**
* minAvgRating ->
* avgRating >= minAvgRating
*
* sort ->
* name -> ascending order movies by name
* -name -> descending
*
* avgRating
*
*
* search ->
* 'ave' -> 'Avengers'
* 'avengers' -> 'Avengers'
* 'AvengersInfinitywar' -> 'Avengers'
*/
const toLower = str => str.toLocaleLowerCase()
const getAvrgRating = (movie, movingWithRatings) => {
let count = 0;
return movingWithRatings.reduce((acc, value, index) => {
const movieMatch = movie.id === value.movie_id
if (movieMatch) {
acc+=value.rating
count++
}
if (index === movingWithRatings.length - 1) {
acc = acc/count
}
return acc
}, 0)
}
const isSubString = (str1, str2) => {
str1 = toLower(str1.split(" ").join(""))
str2 = toLower(str2.split(" ").join(""))
if (str1.length > str2.length) {
return str1.startWith(str2)
} else {
return str2.startWith(str1)
}
}
const moviesList = getMovies()
const movingWithRatings = getRatings();
function queryMovies({ search, sort, minAvgRating }) {
let filteredMovies = movingWithRatings.filter(movie => getAvrgRating(movie, movingWithRatings) >= minAvgRating);
filteredMovies = filteredMovies.map(movie => moviesList.filter(listItem => listItem.id === movie.movie_id).pop())
filteredMovies = filteredMovies.filter(movie => isSubString(toLower(movie.name), toLower(search)))
filteredMovies = filteredMovies.sort((a, b) => {
const isDescending = sort[0] === '-' ? true : false
let sortCopy = isDescending ? sort.slice(1) : sort
const value1 = a[sortCopy]
const value2 = b[sortCopy]
if (isDescending) {
return value1 > value2 ? -1 : 1
}else {
return value1 < value2 ? -1 : 1
}
})
filteredMovies = filteredMovies.map(movie => ({
...movie,
avgRating: movingWithRatings.filter(ratedMovie => ratedMovie.movie_id === movie.id)[0].rating
}))
return filteredMovies
}
4) 给定一个用于获取所有 posts 与 comments 的端点 URL。解决以下问题:
将所有评论(comments)映射至其所归属的帖子(posts),映射后的结果数据应具有以下结构。
//service.js
const POSTS_URL = `https://jsonplaceholder.typicode.com/posts`;
const COMMENTS_URL = `https://jsonplaceholder.typicode.com/comments`;
export const fetchAllPosts = () => {
return fetch(POSTS_URL).then(res => res.json());
};
export const fetchAllComments = () => {
return fetch(COMMENTS_URL).then(res => res.json());
};
import { fetchAllPosts, fetchAllComments } from "./service";
const fetchData = async () => {
const [posts, comments] = await Promise.all([
fetchAllPosts(),
fetchAllComments()
]);
const grabAllCommentsForPost = postId =>
comments.filter(comment => comment.postId === postId);
const mappedPostWithComment = posts.reduce((acc, post) => {
const allComments = grabAllCommentsForPost(post.id);
acc[post.id] = allComments;
return acc;
}, {});
console.log("mappedPostWithComment ", mappedPostWithComment);
};
fetchData();
5) 在字符串实例上实现方法 getHashCode。此方法应适用于所有字符串类型。
let s1 = "sample"
if (!String.prototype.getHashCode) {
String.prototype.getHashCode = function(){
console.log('String instance ', this)
return this
}
}
1+true
true+true
‘1’+true
‘2’ > ’3’
‘two’>’three’
2
2
1true
false
true
7) 实现 bind 与 reduce。
//bind
if (!Function.prototype.bind) {
Function.prototype.bind = function(...arg){
const func = this
const context = arg[0]
const params = arg.slice(1)
return function(...innerParam) {
func.apply(context, [...params, ...innerParam])
}
}
}
//reduce
Array.prototype.reduce = function(func, initState) {
const arr = this
const callback = func
let init = initState
arr.forEach(function(value, index){
init=callback(init, value)
})
return init
}
8) 实现 debounce(防抖)函数。
const debounce = function(func, interval) {
let timerId;
return function(e){
clearTimeout(timerId)
timerId = setTimeout(function(){
func.apply()
}, interval)
}
}
debounce(apiCall, 3000)
9) 实现 throttling(节流)函数。
const throttle = (callback, interval) => {
let timerId;
let allowEvents = true;
return function() {
let context = this;
let args = arguments;
if (allowEvents) {
callback.apply(context, args)
allowEvents = false;
timerId = setTimeOut(function(){
allowEvents = true
}, interval)
}
}
}
10) 设计一套 API 轮询机制,以固定时间间隔调用该 API。此 API 属于股票 API,可获取最新股票价格。在提取完毕后,将结果呈现在 UI 当中。
这个问题的解主要偏重设计而非代码,属于典型的开放式问题。
//With setInterval, throttling and flags
setInterval=>Endpoint=>Render
//with the inversion of control
//Endpoint=>Render=>setTimeout=>Endpoint=>Render=>SetTimeout...
class Parent(name){
constructor(name) {
this.name=name
}
getName(){return this.name}
}
class Children extends Parent {
constructor(props){
super(props)
}
}
function Parent(name) {
this.name = name
}
Parent.prototype.getName = function() {
return this.name
}
function Children(name){
Parent.call(this, name)
}
Children.prototype = new Parent()
//Q.1
var x = 1;
var y = x;
x = 0;
console.log(x, y);
//Q.2
var x = [1];
var y = x;
x = [];
console.log(x,y);
//Q.3
function Abc() { console.log(this); };
Abc()
new Abc();
//Q.4
var x = 1;
var obj = {
x: 2,
getX: function () {
return console.log(this.x);
}
};
obj.getX()
let a = obj.getX
console.log(a)
//Q.5
//How to get the a to log 2 in the above code
//Q.6
console.log("A");
setTimeout(() => console.log("B"), 0);
setTimeout(() => console.log("C"), 0);
console.log("D");
//Q.7
setTimeout(function() {
console.log("A");
}, 0);
Promise.resolve().then(function() {
console.log("B");
}).then(function() {
console.log("C");
});
console.log("D");
//Q.8
let obj1 = {
a:1,
b:2
}
function mutate(obj) {
obj = {a:4, c:6}
}
console.log(obj1)
mutate(obj1)
console.log(obj1)
//A.1
0 1
//A.2
[] [1]
//A.3
window object is logged
//A.4
logs 2 and 1
//A.5
a.call(obj);
//A.6
A, D, B , C
//A.7
D, B, C, A
//A.8
{ a: 1, b: 2 }
{ a: 1, b: 2 }
const list = [1,2,3,4,5,6,7,8]
const filteredArray = list.filter(between(3, 6)) // [4,5]
function between(start, end) {
return function (value,index) {
return value>start && value<end
}
}
A := 1
B := A*2 + 2
C := B*2 + 3 and so on...
请编写一款程序,以:
给出与给定字母相对应的数字;
给定一个类似“GREP”的字母字符串,请结合以上级数,计算与该字符串中所有字母相对应的数字之和(即 G+R+E+P);
给定一个较大数(可大至标准 32 位整数),请找到与之对应的最短字母字符串。
您可能会在最后一题中使用贪心算法。请根据实际情况,在必要时计算与字母相对应的数字值,请勿事先进行预计算并将结果存储在数据结构当中。
//A = 1
//B = A*2 +2
//C = B*2+ 3
//D = C*2+ 3
var genCharArray = function(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
}
var charMap = {};
var charArray = genCharArray('a', 'z');
charArray.forEach(function(char, index){
charMap[char] = Number(index + 1);
});
var charSequence = function(char){
if(typeof char==="string"){
char = charMap[char];
}
if(char==1){
return 1;
}else{
return char + 2 * charSequence(char-1);
}
}
var input = process.argv[2];
if(input.length===1){
console.log(charSequence(charMap[input]));
}else if(input.length>1){
var charTotalSequence = input.split("").reduce(function(acc, curr){
return acc + charSequence(charMap[curr]);
},0);
console.log(charTotalSequence);
}
2) 给定一个数组,请找到另一结对数组,保证两个数组的加和为特定数。
let nums = [2, 7, 10, 1, 11, 15, 9]
let target = 11
let numsMap = new Map()
let pairs = nums.reduce((acc, num) => {
let numToFind = target - num
if (numsMap.get(numToFind)) {
return [...acc, [num, numToFind]]
} else {
numsMap.set(num, true)
return [...acc]
}
}, [])
console.log("Pairs ", pairs)
3) 在给定数组中找到局部最大值。所谓局部最大值,是指大于其左右相邻数的元素。这里我给出一个 O(n) 解,无需优化即可简单解决这个问题。
let x = [1, 2, 3, 5, 4] //Outputs: 5
if x.length == 1 return x[0]
else
let i = 1
for(;i-1;i++){
if x[i-1] x[i+1] return x[i]
}
if x.length - 1 == i return x[i]
4) 对某一数组顺时针旋转 90 度,旋转后的数组即为解。
leetcode:
https://leetcode.com/problems/rotate-image/
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
//The solution is to first take the transpose of the matrix.
//After taking the transpose the resulting matrix is as follows.
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
//After the transpose step, All we have to do is to reverse the array @ each entry.
//The resulting matrix after after reversal is as follows.
[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
//The above matrix is rotated 90 degree
5) 对于给定数组,请找到数组中加和等于给定目标的三个元素。
let x = [1, 2, 3, 4, 5]
let target = 7
let found = []
const twoPointer = (l ,r, current) => {
while(l const totalSum = current + x[l] + x[r]
if (totalSum === target) {
found.push([current, x[l], x[r]])
return
} else if (totalSum > target) {
r--
} else {
l++
}
}
}
const threeSum = (x, target) => {
for (let i=0;i const current = x[i];
let leftPointer = i+1
let rightPointer = x.length - 1
if (current+x[leftPointer]+x[rightPointer] === target) {
found.push([current, x[leftPointer], x[rightPointer]])
} else {
twoPointer(leftPointer, rightPointer, current)
}
}
return found
}
6) G 给定一个字符串与一个整数 k,找到所有不同字符恰好出现 k 次的子字符串数。
https://www.geeksforgeeks.org/number-substrings-count-character-k/
const subStrHasSameCharCount = (str, startIndex, endIndex, totalHop) => {
let charMap = {}
for (let k=startIndex;k let currentChar = str[k]
if (charMap[currentChar]) {
charMap[currentChar]++
} else {
charMap[currentChar] = 1
}
}
let totalCount = Object.values(charMap).length > 0
return totalCount ? Object.values(charMap).every(item => item == totalHop) : false
}
const characterWithCountK = (str, k) => {
if (k == 0) return ''
let count = 0
let initialHop = k
while (initialHop < str.length) {
for (let j=0;j let startIndex = j
let endIndex = j + initialHop
if(endIndex > str.length) continue
count = subStrHasSameCharCount(str, startIndex, endIndex, k)
? count + 1: count
}
initialHop+=k
}
count = subStrHasSameCharCount(str, 0, initialHop, k)
? count + 1: count
return count
}
let str = 'aabbcc'
let k = 2
console.log(characterWithCountK(str, k))
7) 给定两个输入字符串 s1 与 s2,其中包含来自 a 到 z 且以不同顺序排列的字符,请证明能否在 s1 中通过字符重新排列获得等于 s2 的字符串。
let s1 = 'dadbcbc'
let s2 = 'ccbbdad'
let charMap = {}
const canBeRearranged = (s1, s2) => {
if(s1.length!==s2.length){
return false
}
for(let i=0;i const charFromString1 = s1[i]
const charFromString2 = s2[i]
if(charFromString1 in charMap){
charMap[charFromString1]++
} else {
charMap[charFromString1] = 1
}
if(charFromString2 in charMap){
charMap[charFromString2]--
} else {
charMap[charFromString2] = -1
}
}
for(let x in charMap){
if (charMap[x]!==0){
return false
}
}
return true
}
canBeRearranged(s1, s2)
8) 给定一个数组或可变输入大小,编写一项函数以实现数组洗牌。
const swap = (index1, index2, arr) => {
let temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
}
const shuffle = (arr) => {
let totalLength = arr.length
while(totalLength > 0) {
let random = Math.floor(Math.random() * totalLength)
totalLength--
swap(totalLength, random, arr)
}
return arr
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = shuffle(arr)
9) 计算无限尝试的多维数组中,所有元素的加和。
let arr = [4, 5, 7, 8, [5, 7, 9, [3, 5, 7]]]
let sum = 0
const calculateSum = (arr) => {
arr.reduce(function(acc, currentVal) {
const isEntryArray = Array.isArray(currentVal)
if (isEntryArray) {
return acc.concat(calculateSum(currentVal))
} else {
sum+=currentVal
return acc.concat(currentVal)
}
}, [])
}
calculateSum(arr)
console.log(sum)
10) 展平一个表示变化债务的嵌套对象。
const obj = {
level1: {
level2: {
level3: {
more: 'stuff',
other: 'otherz',
level4: {
the: 'end',
},
},
},
level2still: {
last: 'one',
},
am: 'bored',
},
more: 'what',
ipsum: {
lorem: 'latin',
},
};
var removeNesting = function(obj, parent){
for (let key in obj){
if (typeof obj[key] === "object") {
removeNesting(obj[key], parent+"."+key)
} else {
flattenedObj[parent+'.'+key] = obj[key]
}
}
}
let flattenedObj = {}
const sample = removeNesting(obj, "");
console.log(flattenedObj);
11) 给定一项 json 输入,其中每个条目代表一个目录,而各个目录又可以拥有自己的嵌套条目。请据此创建一套目录结构。
解:
https://jsbin.com/gajiweq/1/edit?js,console
12) 给定一个对象数组,其中包含员工数据列表,以保证每位员工都拥有对应的报告对象列表。使用此信息以构建员工层级结构。
const employeesData = [{
id: 2,
name: 'Abhishek (CTO)',
reportees: [6]
}, {
id: 3,
name: 'Abhiram (COO)',
reportees: []
}, {
id: 6,
name: 'Abhimanyu (Engineering Manager)',
reportees: [9]
}, {
id: 9,
name: 'Abhinav (Senior Engineer)',
reportees: []
}, {
id: 10,
name: 'Abhijeet (CEO)',
reportees: [2, 3],
}];
/*
A (CEO)
----B (CTO)
--------D (Engineering Manager)
------------E (Senior Software Engineer)
----C (COO)
*/
const findCeo = (currentEmp) => {
let parentEmployee = employeesData.filter(emp => emp.reportees.indexOf(currentEmp.id) > -1)
if (parentEmployee && parentEmployee.length > 0) {
return findCeo(parentEmployee[0])
} else {
return currentEmp
}
}
const logHierarchy = (currentEmp, indent) => {
console.log("-".repeat(indent) + currentEmp.name)
indent+=4;
for(let i=0;i let employee = employeesData.filter(emp => emp.id === currentEmp.reportees[i])
logHierarchy(employee[0], indent)
}
}
const traverse = (employee) => {
let ceo = findCeo(employee)
logHierarchy(ceo, 0)
}
traverse(employeesData[0])
const inputMatrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11,12,13,14,15],
[16,17,18,19,20],
]
const exprectOutput = [1,2,3,4,5,10,15,20,19,18,17,16,11,6,7,8,9,14,13,12]
function spiralParser(inputMatrix){
const output = [];
let rows = inputMatrix.length;
let cols = rows > 0 ? inputMatrix[0].length : 0;
//singleEmptyRow => Edge case 1 //[]
if (rows === 0) {
return []
}
if (rows === 1) {
//singleElementRowNoCol => Edge case 2 //[[]]
if (cols === 0) {
return []
} else if (cols === 1){
//singleElementRow => Edge case 3 //[[1]]
output.push(inputMatrix[0][0])
return output
}
}
let top = 0;
let bottom = rows - 1;
let left = 0;
let right = cols - 1;
let direction = 0;
//0 => left->right
//1 => top->bottom
//2 => right->left
//3 => bottom->top
while(left <= right && top <= bottom) {
if(direction === 0) {
//left->right
for (let i=left; i<=right;i++) {
output.push(inputMatrix[top][i])
}
top++;
} else if (direction === 1) {
//top->bottom
for (let i=top; i<=bottom;i++) {
output.push(inputMatrix[i][right])
}
right--
} else if (direction === 2) {
//right->left
for (let i=right; i>=left;i--) {
output.push(inputMatrix[bottom][i])
}
bottom--
} else if (direction === 3) {
//bottom->top
for (let i=bottom; i>=top;i--) {
output.push(inputMatrix[i][left])
}
left++
}
direction = (direction + 1) % 4
}
return output;
}
console.log(spiralParser(inputMatrix2))
let str = 'bbbaaaaccadd'; // 最大重复字符数为 4
//sudo code
maxNow = if input string length is 1 or greater than 1 ? 1 : 0
maxOverall = if input string length is 1 or greater than 1 ? 1 : 0
for char in inputString starting from index 1
if char equals prevChar
maxNow++
maxOverall = max(maxOverall, maxNow)
else if char not equals prevChar
maxNow = 1
let inputArr = [2,9,1,5,2,3,1,2,7,4,3,8,29,2,4,6,54,32,2,100]
//ouput => [9,1,5,3,1,7,4,3,8,29,4,6,54,32,100,2,2,2,2,2]
let slowRunner = 0
for (let fastRunner=0;fastRunner if (arr[fastRunner]!==2 && arr[slow] == 2) {
[arr[fastRunner], arr[slow]] = [arr[slow], arr[fastRunner]]
slowRunner++
}
}
//Input = 1 -> 2 -> 3 -> 4 -> 5 -> 6
//Output = 1 <- 2 <- 3 <- 4 <- 5 <- 6
//sudo code
let current = head
let prev = null
let next = null
while(current) {
next = current.next
current.next = prev
prev = current
current = next
}
17) 使用迭代对预排序树进行遍历(无递归)。
//sudo code
const preorder = (root) => {
let stack = []
stack.push(root)
while(there is element in stack) {
let current = stack.pop()
console.log(current.value)
if (current.right) {
stack.push(current.right)
}
if (current.left) {
stack.push(current.left)
}
}
}
1) 设计一套停车场系统,要求满足以下需求:
最多可容纳 N 辆车。实现对泊车位的可用性管理。
保留车辆的出入记录。
自动工单系统会自动对每辆出入汽车进行登记,包括以下详细信息:注册号、颜色、已分配的停车位。
这套系统应支持查询以下结果:
查询所有特定颜色汽车的注册号。
使用特定注册号查询该车辆的停车位。
查询特定颜色汽车的停车位。
列出当前停车场内所有可用空位的列表。
要求:
可以使用任何代码结构:Classes/Structs。
您的解法应具备可扩展性,用以支持未来更多用例。
低代码设计原则:
代码模块化。
命名约定。
SOLID 原则。
解:
https://github.com/devAbhijeet/parking-lot-design-js
2) 创建一款 react 组件 Ping,用于对特定 URL 执行 API 调用。如果 API 调用返回的状态代码为 200,则表示用户在线。如果 API 调用返回的状态代码不是 200,则表示用户处于脱机状态。
尝试更改开发工具网络页面中的 status 表单。
解:
https://codesandbox.io/s/admiring-davinci-xnjef
3) 使用 json 输入创建一款动态表单构建器。表单可以根据 ID 进行分组,且每个组中可以包含一个嵌套组。
解:
https://codesandbox.io/s/great-noyce-75kup
4) 以纯 JavaScript 代码创建一份精简 excel 表格,该表格应支持对行与列的添加及删除功能。需要在 40 分钟内完成。
解:
https://codesandbox.io/s/smoosh-thunder-krv8m
5) 请制作一个搜索输入框,以供在用户列表中执行搜索。
id: 一条唯一 id
name: 用户名
items: 用户订购商品清单
address: 用户地址
pincode: 用户地址邮政编码
您的搜索方案必须涵盖所有字段。
搜索结果以用户卡列表的形式显示。
总结
在搜索输入框内键入内容后,其会打开搜索结果列表。您的解法可以仅实现字符串匹配搜索。
用户卡列表可以通过键盘或鼠标进行导航。如果同时使用鼠标与键盘进行导航,则每次只突出显示一张用户卡(如果鼠标悬念在列表上,则键盘优先;如果未使用键盘操作,则鼠标优先)。
其行为类似于 YouTube 网站的搜索方式。
当未找到搜索结果时,显示空白卡。
卡列表应支持滚动。
突出显示的卡片(通过键盘 / 鼠标)将自动滚动至视图区域内。
解:
https://codesandbox.io/s/silly-moon-31m7u
1) 您如何设计前端应用程序的架构?
2) 实现懒加载
3) 服务器端渲染是什么?
4) 如何在生产环境中部署一款 React app。
5) 服务工作节点 /Web 工作节点是什么。
6) 如何优化 Web 应用程序并提高其性能表现。
7) 请尝试解释不同类型的客户端缓存策略。
8) CORS 是什么。
9) React 中有哪些高阶组件。
10) Redux 中的连接功能如何起效。
11) React 中的纯组件是什么。
https://github.com/devAbhijeet/learning-resources
https://dev.to/devabhijeet/all-front-end-interview-questions-asked-during-my-recent-job-hunt-1kge