A carefully written question is a good indicator of code, while a fun question is a good indicator of code desire.

preface

I have participated in online programming questions of Netease, Meituan, Toutiao, Didi and other companies. It is simply considered that the topic has the following three types:

  1. Carefully writtenThe questions will prompt the answerer to goSerious answer
  2. Interesting topicWill provokeAnswer the questions of interestSo that it can inspire some “inspiration”.
  3. Meaningless questions are not worth answeringIt’s a two-way street

Pen test questions in many cases is really a “pit”, can avoid avoid, because after all, like condition 2 is a minority. But a good question is a good test of programming ability, so don’t miss it.

Spring recruitment in 2018 Ctrip front-end pen test is a good example, the following programming questions to do some analysis.


Q&A

List the questions you may be asked:

  • Is the code 100% AC confirmed?

Absolutely 100% AC. It also means getting the details right. (It’s also fun to deal with a lot of detail and complexity in actual front-end development.)

  • Why not write it in ES6?

Avoid writing platforms that don’t support ES6, you know

  • Why don’tnew Set()Come and go?

Ditto for array de-duplication by the way. If you write a new Set in an interview, it will be diss, don’t ask me why I know: >

  • Why isn’t your code mixed together, instead of being pulled out into multiple functions?

A taste for programming.

Programming style

The programming style used for the code in this paper:

  1. useES5In order to avoid some online programming platforms do not supportES6So it is of no use herenew Set())
  2. Airbnb code specification, do not use singlevarmodel
  3. Variable definition (var), function body (body),returnValues are separated by blank lines, logically distinct
  4. Meaningful variable names
  5. Proper function extraction, a function does only one thing

There is also the use of appropriate type judgment for different situations:

  • Array.isArrayJudge the array,
  • Object.prototype.toString.callTo judge pure objects
  • typeofDetermine the base type andfunction
  • instanceofTo determine a custom object

String interception

The title

describe

Given a string less than 50 characters in length and containing letters and digits, extract the digits and letters in sequence. The digits must be rearranged before the letters.

The input

Strings to intercept (including numbers and letters)

The output

Strings rearranged as required

The sample input

Ctrip C2t0r1i8p2020
Copy the code

Sample output:

'2018Ctrip'
Copy the code

answer

There must be some students who say the first question is not worth analyzing. But HERE’s what I want to do:

  1. String to array:str.split('')(Then use the various manipulation methods of arrays, such asarr.forEach)
  2. judgeWhether the string value is a number:/\d/.test(element)orNumber.isNaN(Number(element)
  3. judgeWhether the string value is a letter:/[a-zA-Z]/.test(element)
  4. digitalString deduplication(Using arrays to remove weights)
  5. Output digits and letters

Hence this version of the code:

Conditions 1 to 3

function handleStr(str) {
  var arr = str.split(' ');
  var nums = ' ';
  var words = ' ';
    
  arr.forEach(function (element) {
    if (/\d/.test(element))) {
      nums += element;
    } else if (/[a-zA-Z]/.test(element) ) { words += element; }});return uniqueStr(nums) + words;
}
Copy the code

duplicate removal

As a front-end development uHF interview question, I believe that we have long on the array to heavy twist in the heart:

Basic type deweighting:

function unique(arr) {
  return arr.filter(function (element, index) {
    return arr.indexOf(element) === index;
  });
}
Copy the code

Basic + complex type de-duplication:

function unique(arr) {
  var hash = {};

  return arr.filter(function (element) {
    if (hash.hasOwnProperty(element)) {
      return false;
    }
    hash[element] = true;

    return true;
  });
}
Copy the code

Since numeric de-duplication (STR, primitive type) is based on array de-duplication, we need to redo the original array a bit:

function uniqueStr(str) {
  var arr = str.split(' ');

  return arr.filter(function (element, index) {
    return arr.indexOf(element) === index;
  }).join(' ');
}
Copy the code

String.split () and array.join() help us move freely between strings and arrays.

Final Solution 1

function handleStr(str) {
  var arr = str.split(' ');
  var nums = ' ';
  var words = ' ';
    
  arr.forEach(function (element) {
    if (/\d/.test(element)) {
      nums += element;
    } else if (/[a-zA-Z]/.test(element) ) { words += element; }});return uniqueStr(nums) + words;
}

function uniqueStr(str) {
  var arr = str.split(' ');

  return arr.filter(function (element, index) {
    return arr.indexOf(element) === index;
  }).join(' ');
}

/ / test
console.log(handleStr(Ctrip C2t0r1i8p2020));
// 2018Ctrip
Copy the code

Final Solution 2

Thank you @while for your valuable advice. The blogger didn’t think of str.match(regex) when writing the written test. To achieve a more concise, logical display better, in this fill:

function handleStr(str) {
  var nums = str.match(/\d/g).join(' ');
  var words = str.match(/[a-zA-Z]/g).join(' ');

  return uniqueStr(nums) + words;
}

function uniqueStr(str) {
  var arr = str.split(' ');

  return arr.filter(function (element, index) {
    return arr.indexOf(element) === index;
  }).join(' ');
}

/ / test
console.log(handleStr(Ctrip C2t0r1i8p2020));
// 2018Ctrip
Copy the code

Two. Array dimension

The title

describe

For one-dimensional arrays, group them into two-dimensional arrays according to type type

The input

  • The input parameter may be an empty array[], empty objectnull.undefined, numbers, strings and other outliers;
  • Or it could be structurally zero[{ type, content}]Effective value of;
  • even[null, null, (type, content)]Data such as valid and invalid values.

The output

  • Output an empty array when the input data is invalid[]
  • When the input data is valid (filter out the exception elements in the array first), then it will be the sametypeThe elements of the value are merged to form a new element{"type": "A", "contents": [content1, content2]}, among them,contentsIs an array of elements with the same values for all typescontentValue.
  • Notice that the output is a standardJSONformat

The sample input

var input = [null.2."test".undefined, {
  "type": "product"."content": "product1"
}, {
  "type": "product"."content": "product2"
}, {
  "type": "tag"."content": "tag1"
}, {
  "type": "product"."content": "product3"
}, {
  "type": "tag"."content": "tag2"
}];
Copy the code

Sample output

[{"type":"product"."contents": ["product1"."product2"."product3"] {},"type":"tag"."contents": ["tag1"."tag2"]}]
Copy the code

answer

At first glance, it looks like a lot of requirements. Let’s break it down a little bit:

Condition 1

Output empty array when input data is invalid []

What data is illegal? The input value is not in JSON format (array type).

What else? The input value is in JSON format (array type), but the length is 0.

Write the first sentence:

function groupList(list) {
  if (!Array.isArray(list) || list.length === 0) { return[]; }}Copy the code

Condition 2

When the input data is valid (filter the exception elements in the array first)

Filter out [], null object null, undefined, number, string and other exception elements:

function groupList(list) {
  if (!Array.isArray(list) || list.length === 0) { return []; }
  
  var validItems = getValidItems(list);
}

function getValidItems(json) {
  return json.filter(function (element) {
    return isPureObject(element)
  });
}

function isPureObject(item) {
  return Object.prototype.toString.call(item).slice(8, -1) = = ='Object';
}
Copy the code

Condition 3 (Hidden condition)

{“type”: “xx”, “content”: “yy”} To do this, add a sentence to getValidItems:

function getValidItems(json) {
  return json.filter(function (element) {
    return isPureObject(element) && element.type && element.content;
  });
}
Copy the code

Some students may ask, why not use typeof to determine object, but so bother to remove an isPureObject?

Typeof is used to check basic types and functions. For example:

var demo = [1.2];

demo.type = 'I'm actually an array';
demo.content = 'But I also have type and content, so I can't tell.';
Copy the code

If it is

function getValidItems(json) {
  return json.filter(function (element) {
    return typeof element === 'object' && element.type && element.content;
  });
}
Copy the code

You can’t filter a demo, let alone a regex or any other non-function object.

So please think carefully about the edge case for online programming questions.

Condition 4

After the filtering is complete, the elements with the same type value are combined to form a new element

function groupList(list) {
  if (!Array.isArray(list) || list.length === 0) { return []; }
  
  var validItems = getValidItems(list);
  var result = {};

  validItems.forEach(function (item) {
    if (result.hasOwnProperty(item.type)) {
      result[item.type].push(item.content);
    } else{ result[item.type] = []; result[item.type].push(item.content); }});return result;
}
Copy the code

Conditions for 5

It looks like we’re done merging the same type values, but:

[{type1: contentsArr1}, {type1: contentsArr2}] {type1: contentsArr1}, {type1: contentsArr2}] {type1: contentsArr1}, {type1: contentsArr2}}

Not hard, add another step:

function adjustFormat(obj) {
  var result = [];

  Object.keys(obj).forEach(function (type) {
    result.push({ type: type, contents: obj[type] });
  });

  return result;
}
Copy the code

Create a new array from an array. Isn’t array.map more useful? (Thanks again @while Daishubi for the proposal)

More pure functional programming, more intuitive logic display:

function adjustFormat(obj) {
  return Object.keys(obj).map(function (type) {
    return { type: type, contents: obj[type] };
  });
}
Copy the code

Finally answer

Complete code:

function groupList(list) {
  if (!Array.isArray(list) || list.length === 0) { return []; }
  
  var validItems = getValidItems(list);
  var result = {};

  validItems.forEach(function (item) {
    if (result.hasOwnProperty(item.type)) {
      result[item.type].push(item.content);
    } else{ result[item.type] = []; result[item.type].push(item.content); }});return adjustFormat(result);
}

function getValidItems(json) {
  return json.filter(function (element) {
    return isPureObject(element) && element.type && element.content;
  });
}

function isPureObject(item) {
  return Object.prototype.toString.call(item).slice(8, -1) = = ='Object';
}

function adjustFormat(obj) {
  return Object.keys(obj).map(function (type) {
    return { type: type, contents: obj[type] };
  });
}

// test
var input = [null.2."test".undefined, {
    "type": "product"."content": "product1"
},  {
    "type": "product"."content": "product2"
},  {
    "type": "tag"."content": "tag1"
}, {
    "type": "product"."content": "product3"
}, {
    "type": "tag"."content": "tag2"
}];

console.log(JSON.stringify(groupList(input)));
// [{"type":"product","contents":["product1","product2","product3"]},{"type":"tag","contents":["tag1","tag2"]}]
Copy the code

conclusion

Coming back to the topic itself, what counts as an interesting front-end test?

  • Not a set pieceOf, do not test “recitation ability”
  • canShow JS abilityThe,The research sites are extensive and comprehensivethe
  • It has to do with the front end.It has to do with actual developmentthe
  • Pay attention toDetail complexityAnd theIt’s not pure algorithmic complexity.(Front-end development only, blogger opinion only)

If it’s a hand-written programming question for an on-site interview, I think it should be added:

  • canDemonstrate programming literacy, pay attention to verticalexpandthe

If any company has programming problems like this, please take me with you 🙂


For more information, check: RayJune.me /about


Some students ask why there is no solution to the third question, because I spent a lot of time in the details of the second question (staring at the complexity of Array. IsArray (input)) – = (I believe many students also do the same), there is no time to solve the third question…