내가 최근에 취직할 때 물어본 모든 전방 면접 문제.
                                            
                                                
                                                
                                                
                                                
                                                
                                                 120442 단어  reactcareerjavascript
                    
전단 면접 문제 
이 자술은 내가 최근 코로나 구직 과정에서 던진 모든 질문을 집성한 것이다.나는 또 내가 일을 준비하기 위해 참고할 자원 명세서를 동봉했다.
이 문제들은 다음과 같은 몇 부분으로 나뉜다.
The solution are not production ready code and just represents a rough idea of my approach. Try implementing your own approach.
Edits made on 20/08/2020. Click to view changes
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());
솔루션
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)
  })
솔루션
// 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
}
posts 및 comments를 가져옵니다.다음 작업을 수행합니다.
//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();
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
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
}
솔루션
const debounce = function(func, interval) {
  let timerId;
  return function(e){
    clearTimeout(timerId)
    timerId = setTimeout(function(){
      func.apply()
    }, interval)
  }
}
debounce(apiCall, 3000)
솔루션
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)
    }
  }
}
이 문제는 코드가 아니라 해결 방안의 설계 방면이 필요하다.이것은 개방적인 문제다.
솔루션
//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
  }
}
계산법
1) 다음 시리즈를 고려합니다.
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);
}
솔루션
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)
솔루션
let x = [1, 2, 3, 5, 4] //Outputs: 5
if x.length == 1 return x[0]
else 
 let i = 1
 for(;i<x.length-1;i++){
  if x[i-1]<x[i] and x[i] > x[i+1] return x[i]
 }
 if x.length - 1 == i return x[i]
leetcode
솔루션
[
 [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
Solution
6) 하나의 수조를 정하고 수조에서 세 개와 주어진 목표의 구화 요소를 찾는다
솔루션
let x = [1, 2, 3, 4, 5]
let target = 7
let found = []
const twoPointer = (l ,r, current) => {
  while(l<r){
    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<x.length;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
}
link
솔루션
const subStrHasSameCharCount = (str, startIndex, endIndex, totalHop) => {
  let charMap = {}
  for (let k=startIndex;k<endIndex;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<str.length;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))
솔루션
let s1 = 'dadbcbc'
let s2 = 'ccbbdad'
let charMap = {}
const canBeRearranged = (s1, s2) => {
  if(s1.length!==s2.length){
    return false
  }
  for(let i=0;i<s1.length;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)
솔루션
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)
솔루션
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)
솔루션
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);
Solution
13) 직원 데이터 목록을 포함하는 대상 그룹을 지정하여 각 직원이 보고 대상 목록을 가지도록 한다.이 정보를 사용하여 직원의 등급 구조를 구축한다.
솔루션
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 <currentEmp.reportees.length;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'; //max repeating char is a with count 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<arr.length;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
}
솔루션
//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) 다음과 같은 요구사항이 있는 주차장 시스템을 설계한다.
차량의 상세한 정보를 가진 차량 등록, 예를 들어 등록번호, 색깔, 분배된 주차장
좁은 홈.
2) 지정된 URL을 API 호출하는 react 구성 요소
Ping를 생성합니다.API 호출이 상태 코드 200을 반환하면 사용자가 온라인 상태임을 나타냅니다.그러나 API 호출이 수신한 상태 코드가 200이 아니면 사용자가 오프라인 상태임을 의미합니다.Try changing
statusform dev tools network panel
Solution
3)
json에서 입력하여 동적 폼 생성기를 만듭니다.테이블은 id에 따라 그룹화할 수 있습니다.각 그룹은 고유의 네스트된 그룹을 가질 수 있습니다.Solution
4) 순수한javascript로 지원
adding과 removing 줄, 열을 위한 최소 excel 작업표를 만듭니다.이 문제는 40분의 시간 제한이 있다.Solution
5) 사용자 목록에서 검색할 수 있는 검색 입력 상자를 만들어야 한다.
사용자 객체에는 다음과 같은 필드가 있습니다.
   id: a unique id
   name: user’s name
   items: list of items ordered by user
   address: address of the user
   pincode: user address pin code
검색 결과가 사용자 카드 목록으로 표시됩니다.
총결산
검색 입력 상자에 를 입력하면 검색 결과 목록이 열립니다.검색은 문자열이 일치하는 검색일 수도 있습니다.
카드 목록은 키보드 또는 마우스로 탐색 가능
마우스와 키보드를 모두 사용하여 탐색하는 경우 한 번에 하나의 카드만 강조 표시할 수 있습니다.
(마우스를 목록에 놓으면 키보드가 우선이고, 키보드 내비게이션을 사용하지 않으면 마우스가 우선이다).
이런 행위는 유튜브 검색 방식과 유사하다
검색 결과를 찾지 못하면 빈 카드가 표시됩니다
카드 목록을 스크롤할 수 있습니다.
강조 표시된 카드(키보드/마우스를 통해)가 뷰로 스크롤
Solution
기타
1) 프런트엔드 애플리케이션의 설계 방법
1) 지연 로드click
2) 서버측 렌더링이란 무엇입니까?
3)react 응용 프로그램을 생산 환경에 어떻게 배치하는가.
4) 서비스 종사자/인터넷 종사자란 무엇인가.
5) 웹 응용 프로그램을 최적화하고 성능을 향상시키는 방법.
6) 서로 다른 유형의 클라이언트 캐시 정책을 설명합니다.
7) CORS란?
8) 반응 중의 고급 성분은 무엇인가.
9) 연결 함수가 Redux에서 어떻게 작동하는지 확인합니다.
10) 화학반응 중의 순성분은 무엇인가.
리소스
link
Reference
이 문제에 관하여(내가 최근에 취직할 때 물어본 모든 전방 면접 문제.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/devabhijeet/all-front-end-interview-questions-asked-during-my-recent-job-hunt-1kge텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)