4

Hello, everyone, I’m Shanyue. Recently, many of my account fans are preparing for autumn recruitment interviews. The students who come to consult Shanyue are in an endless stream.

There is often a question: how do I practice programming problems? Shanyue once again summarized a practice route on handwritten codes.

All of the following handwritten code are posted on the my Codepen in, interested students can codepen in my concern.

Ready to work

API

As an old front-end who has worked for more than three years, he will understand one thing: API is more important than the implementation .

What's the solution?

Functions such as compose are commonly used in various middleware designs, such as redux . redux function is extremely simple, even one line can be realized, but it is not easy compose

Therefore, many interview questions in the front-end interview are mainly based on the simulation implementation of ES API and lodash API, so you need to be familiar with the lodash and ES6+

Code specification

In the interview process to examine the code, in addition to examining the candidate’s logical ability, secondly, you can examine the candidate’s code ability, such as

  1. Is there a consistent code specification
  2. Is there a clear and readable variable naming
  3. Is there a more brief code

For the ability to develop elegant code, you can check Clean Code concepts adapted for JavaScript. , which has 50+ K stars on Github.

For example, about naming optimization

// BAD
// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);

// GOOD
// Declare them as capitalized named constants.
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;

setTimeout(blastOff, MILLISECONDS_PER_DAY);

Handwritten code roadmap

The following are the code questions I have summarized in many major manufacturers. I will summarize them into different parts according to the degree of difficulty and module attributes.

Remark:

  1. 's collection of all the big factory face
  2. summarized all the interviews with

Therefore, I divided the questions into the following categories. I can prepare according to the number of stars and the order of all the code questions I listed. I find three questions every day for coding, and stick to it. The coding stage of the interview with the big factory after three months is not There will be problems.

  1. ES API
  2. lodash API
  3. Programming logic problems
  4. Algorithm and data structure (leetcode)

’s warehouse, and most of the code questions can be found on 161075fc16ce85 codepen , find my solution test and execute it directly.

01 ES API

Many interview questions from big companies are fascinated by the analog implementation of the native API. Although most of the time it is not helpful, sometimes it can further deepen the understanding of the API.

For example, when you finish handwriting Promise.all , it will be more convenient to handwrite a Concurrency Control Promises.

bind/call/apply ⭐⭐⭐⭐⭐️️️️

High frequency issues, intermediate frequency realization.

Function.prototype.fakeBind = function(obj, ...args) {
  return (...rest) => this.call(obj, ...args, ...rest)
}

sleep/delay ⭐⭐⭐⭐⭐

sleep function is not only a code question often asked in interviews, but also daily work, especially a tool function commonly used in tests.

const sleep = (seconds) => new Promise(resolve => setTimeout(resolve, seconds))

function delay (func, seconds, ...args) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      Promise.resolve(func(...args)).then(resolve)
    }, seconds)
  })
}

Promise.all ⭐️⭐️⭐️⭐️⭐️

At first glance, it is simple, but not easy to implement.

function pAll (_promises) {
  return new Promise((resolve, reject) => {
    // Iterable => Array
    const promises = Array.from(_promises)
    // 结果用一个数组维护
    const r = []
    const len = promises.length
    let count = 0
    for (let i = 0; i < len; i++) {
      // Promise.resolve 确保把所有数据都转化为 Promise
      Promise.resolve(promises[i]).then(o => { 
        // 因为 promise 是异步的,保持数组一一对应
        r[i] = o;

        // 如果数组中所有 promise 都完成,则返回结果数组
        if (++count === len) {
          resolve(r)
        }
        // 当发生异常时,直接 reject
      }).catch(e => reject(e))
    }
  })
}

Array.isArray ⭐️⭐️⭐️⭐️⭐️

Interviews are often asked, but they are simple enough.

Array.prototype.flat ⭐️⭐️⭐️⭐️⭐️

reduce and concat are a perfect match

function flatten (list, depth = 1) {
  if (depth === 0) return list
  return list.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b, depth - 1) : b), [])
}

Promise ⭐️⭐️⭐️⭐️

Array.prototype.reduce ⭐️⭐️⭐️

The topic seems simple, but there are many boundary issues that need to be paid attention to in practice, such as

  1. What is the first Index in the callback function?
  2. How to deal with the sparse array?

String.prototype.trim ⭐️⭐️⭐️

Generally, the API will be examined when examining the regularity

02 lodash API

throtle/debounce ⭐⭐⭐⭐⭐️️

The necessary means to reduce rendering in performance optimization, the code is easy enough, and it is often mentioned in the interview questions.

cloneDeep ⭐⭐️⭐⭐⭐

Deep copy, whether in performance optimization at work or in interviews, is very popular.

Using JSON serialization and deserialization cannot solve the problem of copying some complex objects. The difficulty lies in processing different data types.

isEqual ⭐⭐⭐⭐⭐

In-depth comparison, also commonly used in performance optimization, is cloneDeep difficult than 061075fc16d91d.

get ⭐️⭐️⭐️⭐️⭐️

In ES6+, using the optional chain operator ?. can further reduce the difficulty of implementation

function get (source, path, defaultValue = undefined) {
  // a[3].b -> a.3.b -> [a, 3, b]
  const paths = path.replace(/\[(\w+)\]/g, '.$1').replace(/\["(\w+)"\]/g, '.$1').replace(/\['(\w+)'\]/g, '.$1').split('.')
  let result = source
  for (const p of paths) {
    result = result?.[p]
  }
  return result === undefined ? defaultValue : result 
}

compose(flowRight) ⭐️⭐️⭐️⭐️⭐️

const compose = (...fns) =>
  // 注意 f、g 的位置,如果实现从左到右计算,则置换顺序
  fns.reduce((f, g) => (...args) => f(g(...args)))

shuffle ⭐️⭐️⭐️⭐️⭐️

It may be extremely simple to implement a simple shuffle

const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5)

In many scenarios in production practice, shuffle will be used, such as randomly generate a unique six-digit mobile phone verification code

sample ⭐️⭐️⭐️⭐️⭐️

The Math.random() function returns a floating point, the pseudo-random number ranges from 0 to less than 1, which is represented by mathematics as [0, 1), which can be used to implement the sample function

Array.prototype.sample = function () { return this[Math.floor(Math.random() * this.length)] }

sampleSize ⭐️⭐️⭐️⭐️⭐️

maxBy ⭐⭐⭐⭐⭐

keyBy ⭐⭐⭐⭐

groupeBy ⭐⭐⭐⭐

chunk ⭐️⭐️⭐️⭐️

function chunk (list, size) {
  const l = []
  for (let i = 0; i < list.length; i++ ) {
    const index = Math.floor(i / size)
    l[index] ??= [];
    l[index].push(list[i])
  }
  return l
}

chunk ⭐️⭐️⭐️⭐️

const f = x => x

const onceF = once(f)

//=> 3
onceF(3)

//=> 3
onceF(4)

template ⭐⭐⭐⭐️️️️️

Slightly more difficult programming questions.

const template = '{{ user["name"] }},今天你又学习了吗 - 用户ID: {{ user.id }}';

const data = {
  user: {
    id: 10086,
    name: '山月',
  }
};

//=> "山月,今天你又学习了吗 - 用户ID: 10086"
render(template, data); 

Notice:

  1. Pay attention to deeply nested data
  2. Note the user['name'] attribute

pickBy/omitBy ⭐⭐⭐⭐

camelCase ⭐️⭐⭐⭐

difference ⭐️⭐️⭐️

03 Programming logic problems

Regarding programming logic problems, it refers to some data processing often encountered in work

FizzBuzz, can it be divisible by 3 or 5 ⭐️⭐️⭐️⭐️⭐️

Input an integer, if it is divisible by 3, output Fizz

If it is divisible by 5, output Buzz

If it can be both integers of 3 and divisible by 5, then output FizzBuzz

//=> 'fizz'
fizzbuzz(3)

//=> 'buzz'
fizzbuzz(5)

//=> 'fizzbuzz'
fizzbuzz(15)

//=> 7
fizzbuzz(7)

Although this question is very simple, most people still can’t get it right in the interview

Implement Promise.map to control the number of concurrency ⭐️⭐️⭐️⭐️⭐️

With Promise concurrency control, there are often questions in interviews and often involved in work. Before getting started with this problem, understanding the implementation of [Promise.all]() will help a lot to achieve concurrency control.

In addition, the most popular Promise library bluebird Promise.map used extensively in the project.

Asynchronous sum/add ⭐️⭐️⭐️⭐️⭐️

The master of , from the front line of the headline, promise serial, parallel, dichotomy, concurrency control, layer by layer.

How to use JS to implement a publish-subscribe model ⭐️⭐️⭐️⭐️⭐️

How to implement the infinite cumulative sum function ⭐️⭐️⭐️⭐️⭐️

Implement a sum function as follows:

sum(1, 2, 3).valueOf() //6
sum(2, 3)(2).valueOf() //7
sum(1)(2)(3)(4).valueOf() //10
sum(2)(4, 1)(2).valueOf() //9
sum(1)(2)(3)(4)(5)(6).valueOf() // 21

Count the largest number/second largest number in the array ⭐️⭐️⭐️⭐️⭐️

Count the most frequent characters in a string ⭐️⭐️⭐️⭐️⭐️

Encode and compress the following numbers ⭐️⭐️⭐️⭐️⭐️

LRU Cache ⭐️⭐️⭐️⭐️⭐️

Implement a function to encode and decode URL querystring ⭐️⭐️⭐️⭐️⭐️

What is the principle of JSONP and how to implement it ⭐️⭐️⭐️⭐️

How to generate a random string using JS ⭐️⭐️⭐️⭐️⭐️

const random = (n) => Math.random().toString(36).slice(2, 2 + n)

Add thousands to the number ⭐️⭐️⭐️

Thousands place replacement can be matched by regular /(\d)(?=(\d\d\d)+(?!\d))/

function numberThousands (number, thousandsSeperator = ',') {
  return String(number).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousandsSeperator)
}

04 Algorithm and data structure (leetcode)

Leetcode 50/100 simple and intermediate difficulty questions, mainly simple questions.

In my question bank, I have also collected many algorithmic questions summarized in many large factories, and they are summarized as follows

Output Fibonacci sequence within 100

TopK problem

Typical Binary Heap Problem

  1. Take the first k numbers in the array to make a small top pile, and pile it up
  2. The other numbers in the array are compared with the top element one by one. If it is greater than the top element, the number is inserted

Time complexity O(nlg(k))

Find two numbers whose sum is N in an array of positive integers growing in positive order

Find the sum of N numbers in a given array as sum all possible sets

Find the sum of N numbers in a given array as all possible sets of sum, please add the following code

function fn(arr, n, sum) {}

How to judge whether two linked lists intersect

Classic problem

finally

Code programming questions appear frequently in the interview process, and can greatly examine the candidate's coding ability and coding style.


shanyue
4.7k 声望707 粉丝

暮从碧山下,山月(shanyue)随人归。