Many technology-conscious Internet companies require candidates to write code on paper as part of their engineering recruitment process. What are some of the things that interviewers are trying to test? What should candidates pay attention to? This article is based on the United States of America a few years ago commonly used to distinguish a relatively high degree of interview questions to do a detailed explanation, this question I am still using, met a lot of people, but the paper code link can answer to the full mark of the few.

It has 3,655 words and takes seven minutes to read. This is the third article in a series on cracking front-end interviews. The first two are linked here: closures and DOM.

Why code on paper?

Writing code on paper (or perhaps on a whiteboard) may seem impersonal at first, but if you’re the Leader of a team, what kind of person fits in better? If you were the boss, what kind of employees would you pay for? The basic purpose of the code on paper is to see if the candidate has the ability to perform, and to see if the candidate is flexible and knowledgeable.

How does the code link on paper test the ability to live? The first is the speed of work, people without basic coding skills have a very low probability of fast work, 100% rely on Baidu or IDE automatic completion to complete the basic tasks of engineers are not qualified engineers; Secondly, the quality of the work, through the coding process can understand the candidate through learning and training accumulated coding style, thinking methods, etc.; In addition, the paper code also shows the candidate’s initiative in accepting and completing tasks and willingness to accept any task that the team needs to complete.

In some ways, the coding process on paper is a microcosm of what’s to come, so wouldn’t it be nice to rehearse during the interview?

What do YOU do with code on paper?

In general, code on paper doesn’t ask particularly complex questions. It’s likely to fulfill very general requirements, solve real business problems, or implement an algorithm in a language. Before asking code questions for actual business problems, the interviewer will use some of the pre-questions to understand the candidate’s knowledge of business problem solving, and provide supplementary knowledge if necessary.

For example, write a function in JS to parse all parameters from the following URL string without using a third-party library:

http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&d&enabledCopy the code

The expected return result format is as follows:

{user: 'anonymous', id: [123, 456], // The duplicate key is assembled into an array, and the number that can be converted into a number is converted into a number type. True, // The key convention is true}Copy the code

Those of you who have used queryString in Node.js or the QS and Uri. js modules in the community will be familiar with this, and those who are not familiar with the way HTTP GET request parameters are carried should not worry. In this case, the interviewer will explain the rules for the construction of URL parameters. As for the degree of knowledge of the network, it is another concern. In practice, I’ve already had a lot of HTTP conversations with the candidates before I even broached the subject.

1. Before you start

Quite a proportion of the candidates to get the problem, will immediately start to begin to write code, this is the most don’t want to see the interviewer, and fills up the topic of school examinations, paper code as comprehensive quality links, the interviewer wants to see full of you, if you work in the same way to get the demand indiscriminate opened, the end result may is often wasted effort.

Plan before you act. Make sure you understand the problem before you act. What does it mean to get it right? Be aware of the characteristics of the input, and if there are any odd types of input (people with this string in their head are usually good, but interviewers will check carefully to see what you can think of); Be aware of other constraints on the solution, such as time complexity, space complexity. The way to find out is to ask the interviewer, for example, in response to the code above:

  • Does a key with an unspecified value appear repeatedly? What should I do if it occurs repeatedly?
  • Numbers only contain integers? Are floating point numbers included? Scientific notation?
  • What are the performance requirements for the code? Candidates may have multiple approaches in mind when they ask this question.

Like when I answer the requirements in practical work, need to know the boundary of the demand, a variety of possible special circumstances, partners for the expectation of scheduling, priority demand in all the major points defined, from the perspective of decision theory, to grasp more sufficient information, can let you have more demand for technical complexity, scheduling and reasonable forecast, Avoid being half done or half done and not meeting the actual requirements.

To clear up problems, believe that your heart has had the basic train of thought, but hands-on time hasn’t arrived, you should introduce ideas to the interviewer, confirm whether yourself whether to ignore some key points, this is also a good chance to communication, know what is the effective communication of students should be able to understand after receiving information to confirm the importance of the source.

It should be noted that students with strong questioning spirit will ask a lot of questions before starting to act, which seems to be a good thing, but if you just stay at the level of questioning and are not willing to act, you will leave the impression of the interviewer that you are a picky person. In my recruitment experience, I once encountered a person who refused to write code because he thought the problem to be solved was meaningless. I had no choice but to politely send him away. People with low tolerance for things they don’t agree with are likely to bring bad taste to the team.

Having identified the boundaries of the problem and how to solve it, you can start coding.

2. During the coding process

There are many ways to solve the QueryString parameter parsing problem, such as string linear traversal, string partition, regular expression method, in the people I have met, string partition method is the most people, the following discussion around this method. Linear traversal can be implemented by referring to the built-in QueryString module of Node.js.

What factors should be considered in the coding process? Here is a concrete example to analyze, such as I often get the result code like this:

function parse(str) { var obj = {}; var ary = str.split('&'); for (var i = 0; i < ary.length; i++) { var tmp = ary[i].split('='); if (! obj[tmp[0]]) { obj[tmp[0]] = tmp[1] || true; } else { var tmp2 = [obj[tmp[0]], tmp[1] || true]; obj[tmp[0]] = tmp2; } } return obj; }Copy the code

This code has problems in surface layer, logical rigor and robustness. What’s more, it does not meet the requirements of numerical parameters. From this code, it can also be inferred that the candidate is probably not a good learner.

The surface problem

Surface issues are code readability, evaluated by: Does it look clean? Can one look at it and understand what it’s doing? What are the specific surface problems with the above results?

  • In terms of readability, if you want to keep track of resolved key-value pairs in the body of the loop, you need to keep the mapping in mindkey = tmp[0].value = tmp[1];
  • Variable naming, such as TMP multiple use, ary array although can also be used, the community is more arR, variable naming more convention will be better;

The reference code for the surface improvement is as follows:

function parse(str) { var paramObj = {}; var paramArr = str.split('&'); for (var i = 0; i < paramArr.length; i++) { var tmp = paramArr[i].split('='); Var key = TMP [0]; var value = tmp[1] || true; if (! paramObj[key]) { paramObj[key] = value; } else { var newValue = [paramObj[key], value]; paramObj[key] = newValue; } } return paramObj; }Copy the code

The logical question

The result of a code with loose logic is unstable under different input conditions, which can be expressed as follows:

  • obj[tmp[0]]You cannot correctly determine whether a key already exists in the result because a value of 0 May occur.
  • The above code does not correctly handle keys that appear more than twice, and some candidates are still wondering why by the end of the interview.
  • According to the specification, various parameters in URL need to be spliced into URL after encode, corresponding parsing needs decode;

The reference code to solve the logic problem is as follows:

function parse(str) { var paramObj = {}; var paramArr = decoeURI(str).split('&'); For (var I = 0; i < paramArr.length; i++) { var tmp = paramArr[i].split('='); var key = tmp[0]; var value = tmp[1] || true; If (typeof paramObj[key] === 'undefined') {// Determine whether key exists paramObj[key] = value; } else { var newValue = Array.isArray(paramObj[key]) ? paramObj[key] : [paramObj[key]]; // Handle the array newvalue.push (value) correctly; paramObj[key] = newValue; } } return paramObj; }Copy the code

Robust problem

The entire code does not do any defensive programming, which makes it very error-prone, where to do defensive programming is worth deciding. Do QueryString parsing functions at least require their arguments to be strings? It would be better to add the following code at the beginning of the function:

/ /... if (typeof str ! == 'string') { return {}; } / /...Copy the code

demand

There’s nothing to do with numbers in the code, and this is a problem that almost every candidate who writes code when they get a problem has, which is how to convert a value that can be converted to a number into a number. Have you figured out what to do? Use parseInt? Or parseFloat?

Here’s a reference code to handle numbers correctly:

function parse(str) { if (typeof str ! == 'string') { return {}; } var paramObj = {}; var paramArr = decodeURI(str).split('&'); for (var i = 0; i < paramArr.length; i++) { var tmp = paramArr[i].split('='); var key = tmp[0]; var value = tmp[1] || true; // Handle numbers: A lot of people ignore the type judgment here, If (typeof value === 'string' && isNaN(Number(value)) === false) {value = Number(value); if (typeof value === 'string' && isNaN(Number(value)) === false) {value = Number(value); } if (typeof paramObj[key] === 'undefined') { paramObj[key] = value; } else { var newValue = Array.isArray(paramObj[key]) ? paramObj[key] : [paramObj[key]]; newValue.push(value); paramObj[key] = newValue; } } return paramObj; }Copy the code

A question that is not a question

The following two points are not a problem, but they are definitely a plus if the candidate can do it.

  • With ES6 as the new language standard, candidates are still using var a lot. There’s nothing wrong with that, but do you have a better way?
  • You can use more semantic JS array methods to organize your code, such as Map and reduce. If you know them, don’t hesitate to use them in interviews.

The reference code written using ES6 is as follows:

function parse(str) { if (typeof str ! == 'string') { return {}; } return decodeURI(str).split('&').map(param => { const tmp = param.split('='); const key = tmp[0]; let value = tmp[1] || true; if (typeof value === 'string' && isNaN(Number(value)) === false) { value = Number(value); } return { key, value }; }).reduce((params, item) => { const { key, value } = item; if (typeof params[key] === 'undefined') { params[key] = value; } else { params[key] = Array.isArray(params[key]) ? params[key] : [params[key]]; params[key].push(value); } return params; }, {}); }Copy the code

In addition, those of you who are paying attention to the advances in front-end technology may have noticed that some modern browsers offer support for URLSearchParams, which can be done with a single line of code.

3. After coding

After the first version of the code is written, don’t rush to show it to the interviewer, just like after the requirements are developed, you should at least go through the requirements document yourself, substitute the input from the original code into your own code for deduction and simple boundary tests, and then explain to the code and the interviewer. Unsurprisingly, you’ll find some problems or obvious improvements, which you can bring up with the interviewer as it’s an opportunity to show off your skills.

conclusion

Thank you for taking the time to read this, I believe that you have understood the process and results of the code on paper can be used to investigate the basic quality of the candidate, the way of work, and the ability to work, and also know the key points to pay attention to in the different links of the code questions: make clear the question before starting; Pay attention to coding style, logic rigor and program robustness; After coding, you should first test and deduce. Of course, if you haven’t noticed this before, you’ll need to practice it on the job. Finally, good luck finding the job you want.

One More Thing

The author of this article is Wang Shijun. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source. If you found this article helpful, please give it a thumbs up! If you have any questions about the content of this article, please leave a comment. Want to know what I’ll write next? Please subscribe to my nuggets column or Zhihu column: Front End Weekly: Keeping you Up to date on the Front End.

Happy Hacking