All front end Interview questions asked during my recent job hunt


All front end Interview questions asked during my recent job hunt.

All front end Interview questions asked during my recent job hunt

Front end interview (1 Part Series)

Interview questions for front end


This readme is a compilation of all the question asked during my recent COVID-19 job hunt. I’ve also attached(附上) a list of resources that I’d referred for the preparations.

在今天的文章中,我想跟大家聊聊自己最近在 COVID-19 疫情下的求职经历中遇到的问题。另外,我还把自己的准备工作整理成一份资源清单供大家参考。
The questions are divided into following sections.

  • JS
  • Coding
  • Assignments
  • Miscellaneous

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. Given a multidimensional array with depth of n, flatten it. Once flattened make it available as a method on array instance
  1. 给定一个深度为 n 的多维数组,将其展平。展平后,将其作为 array 实例上的可用方法。
Answer
/**
 * [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());

Array.prototype.flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

  1. Create a promise from scratch
  1. 从零开始创建一项 promise.
Answer
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);
  });

  1. Filter movie list by average rating, name. Sort filtered list by any field inside movie object
  1. 按 平均评分 及 名称 对电影列表进行过滤。按电影对象内的任意字段对过滤后的列表进行排序。
Answer
// 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;
}

  1. Given an end point URL to fetch all the posts and comments. Do the following.
  1. 给定一个用于获取所有 posts 与 comments 的端点 URL. 解决以下问题:
  • Map all the comments to the posts it belongs to. The resultant data after mapping should be of below structure.

将所有评论 (comments) 映射至其所归属的帖子 (posts), 映射后的结果数据应具有以下结构。

Answer

Answer

//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();

  1. Implement a method getHashCode on string instance. The method should be available on all strings.

❓5. 在字符串实例上实现方法 getHashCode. 此方法应适用于所有字符串类型。

Answer
let s1 = 'sample';

if (!String.prototype.getHashCode) {
  String.prototype.getHashCode = function () {
    console.log('String instance ', this);
    return this;
  };
}

  1. What does the below expressions evaluate to
  1. 以下表达式的计算结果是什么?
1 + true;
true + true;
'1' + true;
'2' > '3';
'two' > 'three';
Answer
2
1true
false
true

  1. Implement bind and reduce.
  1. 实现 bind 与 reduce.
Answer
//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;
};

  1. Implement debounce function
  1. 实现防抖函数 防抖就是指触发事件特定时间间隔内后才执行函数,如果在特定时间间隔内又触发了事件,则会重新计算函数执行时间。节流就是指连续触发事件但是在特定时间间隔内内只执行一次函数
    发送请求 输入验证 浏览器窗口 resize
Answer
const debounce = function (func, interval) {
  let timerId;
  return function (e) {
    clearInterval(timerId);
    timer = setTimeout(function () {
      func.apply();
    }, interval);
  };
};
debounce(apiCall, 3000);

Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() and use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds has elapsed.
Use Function.prototype.apply() to apply the this context to the function and provide the necessary arguments.
Omit the second argument, ms, to set the timeout at a default of 0 ms.

const debounce = (fn, ms = 0) => {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), ms);
  };
};

Examples

window.addEventListener(
  'resize',
  debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250),
); // Will log the window dimensions at most every 250ms

  1. Implement throttle function
  1. 实现 节流函数。 节流就是指连续触发事件但是在特定时间间隔内内只执行一次函数
Answer
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);
    }
  };
};

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

Use setTimeout() and clearTimeout() to throttle the given method, fn.
Use Function.prototype.apply() to apply the this context to the function and provide the necessary arguments.
Use Date.now() to keep track of the last time the throttled function was invoked.
Use a variable, inThrottle, to prevent a race condition between the first execution of fn and the next loop.
Omit the second argument, wait, to set the timeout at a default of 0 ms.

const throttle = (fn, wait) => {
  let inThrottle, lastFn, lastTime;
  return function () {
    const context = this,
      args = arguments;
    if (!inThrottle) {
      fn.apply(context, args);
      lastTime = Date.now();
      inThrottle = true;
    } else {
      clearTimeout(lastFn);
      lastFn = setTimeout(function () {
        if (Date.now() - lastTime >= wait) {
          fn.apply(context, args);
          lastTime = Date.now();
        }
      }, Math.max(wait - (Date.now() - lastTime), 0));
    }
  };
};

Examples

window.addEventListener(
  'resize',
  throttle(function (evt) {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250),
); // Will log the window dimensions at most every 250ms

函数防抖:将几次操作合并为一此操作进行。原理是维护一个计时器,规定在 delay 时间后触发函数,但是在 delay 时间内再次触发的话,就会取消之前的计时器而重新设置。这样一来,只有最后一次操作能被触发。

函数节流:使得一定时间内只触发一次函数。原理是通过判断是否到达一定时间来触发函数。

区别: 函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。 比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。

  1. Design API polling mechanism. The API is called after a fixed interval. The API is a stock API that fetches the latest price of stock. Upon fetching the results, render the UI.
  1. 设计一套 API 轮询机制,以固定时间间隔调用该 API. 此 API 属于股票 API, 可获取最新股票价格。在提取完毕后,将结果呈现在 UI 当中。

The question demands the design aspect of the solution and not the code. It was open ended question.

这个问题的解主要偏重设计而非代码,属于典型的开放式问题。

Answer
//With setInterval, throttling and flags
setInterval=>Endpoint=>Render

//with the inversion of control
Endpoint=>Render=>setTimeout=>Endpoint=>Render=>SetTimeout...

  1. Convert class based inheritance code given below to ES5 code.
  1. 将以下给出的、基于类的继承代码转换为 ES5 代码。
class Parent {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }
}

class Children extends Parent {
  constructor(props) {
    super(props);
  }
}
Answer
function Parent(name) {
  this.name = name;
}

Parent.prototype.getName = function () {
  return this.name;
};

function Children(name) {
  Parent.call(this, name);
}

Children.prototype = new Parent();

  1. What does following code evaluates to?
  1. 以下代码的计算结果是什么?
//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;

//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);
Answer
//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 }

  1. Given an array of numbers implement the following
  1. 给定一个数字数组,请执行以下操作:
const list = [1, 2, 3, 4, 5, 6, 7, 8];
const filteredArray = list.filter(between(3, 6)); // [4,5]
Answer
function between(start, end) {
  return function (value, index) {
    return value > start && value < end;
  };
}

Algorithms

  1. Consider the following series:
  1. 考虑以下级数:
A := 1
B := A*2 + 2
C := B*2 + 3 and so on...

Write a program that:

outputs the number corresponding to a given letter

given a string of letters like ‘GREP’, computes the sum of the numbers corresponding to all the letters in the string (i.e., G + R + E + P), as given by the above series and

given a large number (that would fit into a standard 32-bit integer), finds the shortest string of letters corresponding to it.

You may use a greedy approach for the last part. Compute the values of the numbers corresponding to letters as and when required and DO NOT pre-compute beforehand and store them in a data structure.

请编写一款程序,以:

给出与给定字母相对应的数字;

给定一个类似”GREP”的字母字符串,请结合以上级数,计算与该字符串中所有字母相对应的数字之和(即 G+R+E+P);

给定一个较大数(可大至标准 32 位整数), 请找到与之对应的最短字母字符串。

您可能会在最后一题中使用贪心算法。请根据实际情况,在必要时计算与字母相对应的数字值,请勿事先进行预计算并将结果存储在数据结构当中。

Answer
//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);
}

  1. Given an array find a pair such that it sums to a given number
  1. 给定一个数组,请找到另一结对数组,保证两个数组的加和为特定数。
Answer
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);

  1. Find the local maxima in a given array. A local maxima is a element that is greater than it’s left and right neighbours. I provided a O(n) solution which was quite straight forward before going for optimisation.
  1. 在给定数组中找到局部最大值。所谓局部最大值,是指大于其左右相邻数的元素。这里我给出一个 O(n) 解,无需优化即可简单解决这个问题。
Answer
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]

  1. Rotate a matrix clockwise by 90 degree. The solution should be in place.
  1. 对某一数组顺时针旋转 90 度,旋转后的数组即为解。
    leetcode
Answer
[
  [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
const a = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]; // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

/**
 * 48. Rotate Image
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function (matrix) {
  let stack = [];
  for (i = 0; i < matrix.length; i++)
    for (j = 0; j < matrix[0].length; j++) stack.push(matrix[i][j]);
  for (j = matrix[0].length - 1; j >= 0; j--)
    for (i = 0; i < matrix.length; i++) matrix[i][j] = stack.shift();
};

rotate(a);
console.log(a);
// [ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]

// [
//   [7, 4, 1],
//   [8, 5, 2],
//   [9, 6, 3]
// ]

48. Rotate Image

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function (matrix) {
  var n = matrix.length;
  var n2 = Math.floor(n / 2);
  // 1 2 3     7 8 9
  // 4 5 6  => 4 5 6
  // 7 8 9     1 2 3
  for (var i = 0; i < n2; i++) {
    for (var j = 0; j < n; j++) {
      swap(matrix, i, j, n - 1 - i, j);
    }
  }
  // 7 8 9     7 4 1
  // 4 5 6  => 8 5 2
  // 1 2 3     9 6 3
  for (var i = 0; i < n; i++) {
    for (var j = i + 1; j < n; j++) {
      swap(matrix, i, j, j, i);
    }
  }
};

var swap = function (matrix, x1, y1, x2, y2) {
  var tmp = matrix[x1][y1];
  matrix[x1][y1] = matrix[x2][y2];
  matrix[x2][y2] = tmp;
};

Explain:

见注释

顺时针 90°: 先上下倒置,再对角倒置

逆时针 90°: 先左右倒置,再对角倒置

Complexity:

  • Time complexity : O(n^2).
  • Space complexity : O(1).

  1. Maximum subarray sum modulo m
Answer

Answer


  1. Given an array find three element in array that sum to a given target
  1. 对于给定数组,请找到数组中加和等于给定目标的三个元素。
Answer
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;
};

  1. Given a string and an integer k, find number of substrings in which all the different characters occurs exactly k times.
  1. 给定一个字符串与一个整数 k, 找到所有不同字符恰好出现 k 次的子字符串数。
    link
Answer
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));

  1. Given two input strings, s1 and s2, containing characters from a-z in different orders, find if rearranging string in s1 results in a string that is equal to s2.
  1. 给定两个输入字符串 s1 与 s2, 其中包含来自 a 到 z 且以不同顺序排列的字符,请证明能否在 s1 中通过字符重新排列获得等于 s2 的字符串。
Answer
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);

  1. Given an array or variable input size, write a function to shuffle the array.
  1. 给定一个数组或可变输入大小,编写一项函数以实现数组洗牌。
Answer
const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr = shuffle(arr);

  1. Calculate the sum of all elements in a multidimensional array of infinite depth.
  1. 计算无限尝试的多维数组中,所有元素的加和。
Answer
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);

  1. Flatten a nested object of varying debt.
  1. 展平一个表示变化债务的嵌套对象。
Answer
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);

  1. Given a json input, where each entry represents a directory such that each directory in turn can have a nested entry of it’s own. Create the resulting directory structure.
  1. 给定一项 json 输入,其中每个条目代表一个目录,而各个目录又可以拥有自己的嵌套条目。请据此创建一套目录结构。
Answer

Answer


  1. Given an array of object containing list of employee data such that each employee has list of reportee. Use this information to construct a hierarachy of employees.
  1. 给定一个对象数组,其中包含员工数据列表,以保证每位员工都拥有对应的报告对象列表。使用此信息以构建员工层级结构。
Answer
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]);

  1. Print a given matrix in spiral form
  1. 以螺旋形式输出给定的数组。
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];
Answer
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));

  1. Find maximum consecutive repeating char in a give string.
  1. 在给定字符串中找到最大的连续重复字符。
let str = 'bbbaaaaccadd'; //max repeating char is a with count 4
Answer
//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

  1. Given a input array of varying length, segregate all the 2’s at the end of the array.
  1. 给定一个长度可变的输入数组,将所有 2 分隔在数组末尾。
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]
Answer
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++;
  }
}

  1. Reverse a linked list
  1. 反转一个链接列表。
//Input = 1 -> 2 -> 3 -> 4 -> 5 -> 6
//Output = 1 <- 2 <- 3 <- 4 <- 5 <- 6
Answer
//sudo code
let current = head;
let prev = null;
let next = null;

while (current) {
  next = current.next;
  current.next = prev;
  prev = current;
  current = next;
}

Assignments

  1. Design a parking lot system with following requirements:
  • It can hold up to N vehicles. Handle availability of parking lot.
  • Entry and exit log of vehicles.
  • Automated ticketing system for every vehicle entering/exiting the parking lot will have vehicle registration with vehicle details like: Registration No., Color, allocated parking slot.

I should be able to query:

  • Registration No. of all vehicles of a particular color.
  • Parking slot of a vehicle given registration no.
  • Parking slots for vehicles given a color.
  • List of available slots in the parking lot.

Requirements:

  • Can use anything to structure the code: Classes/Structs.
  • Your solution should be extendable for future use cases.

Few code design principles:

  • Modularity of code.
  • Naming conventions.
  • SOLID principles.
  1. 设计一套停车场系统,要求满足以下需求:
  • 最多可容纳 N 辆车。实现对泊车位的可用性管理。

  • 保留车辆的出入记录。

  • 自动工单系统会自动对每辆出入汽车进行登记,包括以下详细信息:注册号、颜色、已分配的停车位。

这套系统应支持查询以下结果:

  • 查询所有特定颜色汽车的注册号。

  • 使用特定注册号查询该车辆的停车位。

  • 查询特定颜色汽车的停车位。

  • 列出当前停车场内所有可用空位的列表。

要求:

  • 可以使用任何代码结构:Classes/Structs.

  • 您的解法应具备可扩展性,用以支持未来更多用例。

代码设计原则:

  • 代码模块化。

  • 命名约定。

  • SOLID 原则。

Answer

Answer


  1. Create a react component Ping that makes an API call to a given URL. If the API calls returns status code 200 that means the user is online. However, if the API call receives status code other than 200 it means, the user is offline.
  1. 创建一款 react 组件 Ping, 用于对特定 URL 执行 API 调用。如果 API 调用返回的状态代码为 200, 则表示用户在线。如果 API 调用返回的状态代码不是 200, 则表示用户处于脱机状态。
    Try changing status form dev tools network panel

尝试更改开发工具网络页面中的 status 表单。

Answer

Answer


  1. Create a dynamic form builder from a json input. The form can be grouped based on id. Each group can have a nested group of it’s own.
  1. 使用 json 输入创建一款动态表单构建器。表单可以根据 ID 进行分组,且每个组中可以包含一个嵌套组。
Answer

Answer


  1. Create a minimal excel sheet in pure javascript that supports adding and removing rows, columns. There was time limit on this question of 40 minutes.
  1. 以纯 JavaScript 代码创建一份精简 excel 表格,该表格应支持对行与列的添加及删除功能。需要在 40 分钟内完成。
Answer

Answer


  1. You have to make a search input box which will search over a list of users.
  1. 请制作一个搜索输入框,以供在用户列表中执行搜索。
    The user object has the following fields
  • 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

You have to implement search on all of the fields.

The search results will show up as a list of User Cards.

To Summarize
On typing in the search input box, the search results list opens up. The search could be just a string matching search.

The list of cards can be navigated through keyboard or mouse
only one card should highlight at a time if both mouse and keyboard are used for navigation

(keyboard will take preference if mouse is kept hovered on the list, similarly mouse will take preference if keyboard navigation is not used).

This behaviour is similar to how youtube search works

When no search results are found, an empty card is displayed
The card list would be scrollable.

The highlighted card (via keyboard/mouse) will scroll into view

用户对象中包含以下字段:

  • id: 一条唯一 id
  • name: 用户名
  • items: 用户订购商品清单
  • address: 用户地址
  • pincode: 用户地址邮政编码

您的搜索方案必须涵盖所有字段。

搜索结果以用户卡列表的形式显示。

总结

在搜索输入框内键入内容后,其会打开搜索结果列表。您的解法可以仅实现字符串匹配搜索。

用户卡列表可以通过键盘或鼠标进行导航。如果同时使用鼠标与键盘进行导航,则每次只突出显示一张用户卡(如果鼠标悬念在列表上,则键盘优先;如果未使用键盘操作,则鼠标优先).

其行为类似于 YouTube 网站的搜索方式。

当未找到搜索结果时,显示空白卡。

卡列表应支持滚动。

突出显示的卡片(通过键盘 / 鼠标)将自动滚动至视图区域内。

Answer

Answer

Miscellaneous

  1. How would you architect a front end application click
  2. Implement Lazy loading click
  3. What is Server Side Rendering.
  4. How to deploy a react app to production.
  5. What are service worker/web worker.
  6. How to optimise a web app and make it more performant.
  7. Explain different type of client side cache strategies.
  8. What is CORS.
  9. What are higher order component in react.
  10. How does connect function work in redux.
  11. What are pure components in React.
  12. Difference between proto and prototype
  13. Difference between inline vs inline block vs block
  14. Difference between flex and grid layout
  15. Different positioning system in CSS
  16. Specificity and selectors priority in CSS
  17. Difference between display none vs visibility hidden vs opacity
  1. 您如何设计前端应用程序的架构?

  2. 实现懒加载

  3. 服务器端渲染是什么?

  4. 如何在生产环境中部署一款 React app.

  5. 服务工作节点 /Web 工作节点是什么。

  6. 如何优化 Web 应用程序并提高其性能表现。

  7. 请尝试解释不同类型的客户端缓存策略。

  8. CORS 是什么.

  9. React 中有哪些高阶组件。

  10. Redux 中的连接功能如何起效。

  11. React 中的纯组件是什么。

Resources

link

Front end interview (2 Part Series)

Hello there, if you have come to this post that means you are currently getting interviewed or are looking forward to get interviewed in the near future.

Keeping that in mind I’ve compiled a list of resources one can refer to get an upper hand during the interview process.

Q&A format

  1. 123 essential javascript questions

    Tricky questions on hoisting, inheritance, closures, null vs undefined, NaN…

  2. 70 javascript interview questions

    Dive deep into hoisting, inheritance, closures, promises, events…

  3. javascript mcq

    Practical code snippets in Q&A format.


Concepts

  1. alexander zlatkov’s how javascript works medium posts

    Internal working of JS includes event loop, v8 engine, classes and inheritance, storage engines, shadow dom, webRTC, garbage collection, service workers, web workers, web socket, HTTP/HTTP2, network layer, browser engine, rendering engine…

  2. akshay saini’s youtube channel

    Learn about event delegation, event propagation, debouncing, throttling, call, apply, bind, polyfills, curring.

  3. design pattern soumyajit pathak’s medium posts

    Brief overview of different design pattern

  4. addy osmani

    Dive deep into design pattern such as singleton, mediator, revealing module, pub sub…

  5. javascript concepts visualised

    not so easy concepts made easy with awesome visualiser.

  6. how to architect a front end application

    Learn different layer of front end application and their roles in the overall architecture.


HTML, CSS

  1. boxmodel

    Learn about the box model

  2. flex

    Layout using flexbox

  3. grid

    Layout using grid

  4. specificity

    Learn about CSS specificity and selector priorities

  5. position

    Learn different positioning system used in CSS

  6. inline vs inline-block

    Learn difference between inline vs inline block vs block


React

  1. react vs angular change detection

    Learn how angular and react differ from each other in the context of change detection mechanism

  2. fiber architecture traversal

    Learn internal of React’s fiber tree traversal process

  3. fiber architecture reconciliation

    Learn internal of React’s fiber tree reconciliation process

  4. internal working of props and life cycle hooks

    Learn internal of props and state updation along with life cycle hooks

Alogorithms

  1. tech dose

    Get to know the why of the solutions and how to develop intuition for algorithmic problems.

  2. tushar roy’s

    Learn concepts of tree, graphs, dynamic programming. Different traversal strategies and problems.

  3. my code school

    Learn the math and run time analysis of algorithms

All front end interview question

link


文章作者: 庄引
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 庄引 !
  目录