preface

We’re often asked a few handwritten code questions in an interview. Hand write an array to repeat, hand write a deep copy, hand write an array to beat equal, etc. This article summarizes an outline of how to deal with handwritten code. The basics are in front of it, but I also hope it will help you, so I will review it again.

Koala is dedicated to sharing the complete Node.js technology stack, from JavaScript to Node.js, to back-end database. Wish you become an excellent senior Node.js engineer. [Programmer growth refers to north] Author, Github blog open source project github.com/koala-codin…

1. Name and specific function considerations

The name

When writing out functions, I hesitate for a few seconds each time I name an argument or function. The interviewer thought I didn’t know how to write!

  • Code specification compliance
  • Function names are named in English (here you must know what the function you are writing can do).
  • As for the parameters passed, as well as the internal declaration of some arrays, variables, etc., do not think too much, can be used directlyarrArr + Function nameShorthand.

In fact, you can directly use ARR1, ARR2 to replace, can distinguish between good, don’t hesitate this kind of thing waste time.

2. New variables and return values

After reading a written interview question, you can first look at whether new variables need to be declared, the results to be returned and the type of results.

  • Array flatting must return an array, you can consider declaring an array in the initial way, you can also consider using map, filter and other functions to return directly.
  • Object deep copies must return copied objects one by one, declaring an empty object at the beginning and returning the processed object at the end.
  • There are a lot of cases where you can declare new variables or not declare new variables, and that’s fine, but you have to take into account the time complexity and the space complexity, and just use one implementation first. The interviewer will continue to ask if you have any other plans.

3. Consider using cycles? Recursion?

cycle

The for loop

  1. Declare a loop variable. ② Judge the circulation condition; ③ Update loop variables;

Between three expressions, use; Split, for loop three expressions can be omitted, but the two “;” Both are indispensable. 2. The for loop execution features: judgment first, then to perform, and while the same 3. The for loop, three expressions can have multiple parts with the second part of multiple judgment conditions && | | connection, daiichi comma separated;

for (var num =1; num<=10; num++) {
    document.write(num+" <br />"); //1 2 3 4 5 6 7 9 10
}
Copy the code

The for loop in

For (keys in object){} keys represent the keys of each pair of obj objects. In all loops, you need to use obj[keys] to fetch each value!!

A for-in loop can not only read the member properties of the object itself, but also iterate through the prototype properties of the object through the prototype chain. Therefore, hasOwnProperty can be used to determine whether a property is a property of the object itself

Obj. HasOwnProperty (keys)==true indicates that this property is a member property of the object, not its original property.

Declare a Peson class
function Person(){
    this.name = "kaola";
    this.age = 24;
    this.func1 = function(){}}// instantiate this class
var bei = new Person();
// Use for-in to traverse the object
for(keys in bei){
    console.log(bei[keys])
}
Copy the code

The for of circulation

ES6 uses C++, Java, C#, and Python to introduce for… The of loop, as a unified way to traverse all data structures.

A data structure that deploys the Symbol. Iterator attribute is considered to have an iterator interface. The of loop iterates through its members. That is to say, for… Inside the of loop is the symbol. iterator method of the data structure.

for… The scope of the of loop includes arrays, Set and Map structures, some array-like objects (such as Arguments objects, DOM NodeList objects), Generator objects, and strings.

recursive

See my article for more details on recursion, and the common recursive handwritten code in this article is written,

4. Consider boundaries

4.1 Type Judgment

How do I determine the data type? How do you determine whether a value is an array type or an object?

Three ways, typeof, instanceof respectively, and the Object. The prototype. ToString. Call ()

typeof

The Typeof operator is used to determine which base type a value belongs to.

typeof 'seymoe'    // 'string'
typeof true        // 'boolean'
typeof 10          // 'number'
typeof Symbol(a)// 'symbol'
typeof null        // 'object' is not null
typeof undefined   // 'undefined'

typeof {}           // 'object'
typeof []           // 'object'
typeof(() = > {})    // 'function'
Copy the code

As you can see from the output of the code above,

  1. nullThere is an error in the judgment of the results obtained

If typeof NULL is used, the result is Object

  1. The operator determines the type of an object and its subtypes, such as functions (callable objects), arrays (ordered indexed objects), and so onobjectResults.

In the case of object subtypes and null, you can see that typeOf has some limitations for determining types.

instanceof

Object types can also be determined by the instanceof operator, which tests whether the constructor’s prototype appears on the prototype chain of the object being tested.

[] instanceof Array            // true
({}) instanceof Object         // true
(() = >{}) instanceof Function   // true
Copy the code

Copy code Note: Instanceof is not a panacea.

Here’s an example:

let arr = []
let obj = {}
arr instanceof Array    // true
arr instanceof Object   // true
obj instanceof Object   // true
obj instanceof Array   // false
Copy the code

In this case, the arR Array is an instance of new Array(), so arr.__proto__ === array. prototype. Array is an Object subtype. Array.prototype.__proto__ === Object.prototype, so the Object constructor is on the prototype chain of arR. So instanceof still can’t elegantly determine whether a value is an array or an ordinary object.

Object.prototype.__proto__ === null arr instanceof null should also be true. This confirms that the typeof NULL result as object is really just a javascript bug.

Object.prototype.toString()(Recommended)

This is the ultimate solution to determining data types in JavaScript, as shown in the following code:

Object.prototype.toString.call({})              // '[object Object]'
Object.prototype.toString.call([])              // '[object Array]'
Object.prototype.toString.call(() = > {})        // '[object Function]'
Object.prototype.toString.call('seymoe')        // '[object String]'
Object.prototype.toString.call(1)               // '[object Number]'
Object.prototype.toString.call(true)            // '[object Boolean]'
Object.prototype.toString.call(Symbol())        // '[object Symbol]'
Object.prototype.toString.call(null)            // '[object Null]'
Object.prototype.toString.call(undefined)       // '[object Undefined]'

Object.prototype.toString.call(new Date())      // '[object Date]'
Object.prototype.toString.call(Math)            // '[object Math]'
Object.prototype.toString.call(new Set())       // '[object Set]'
Object.prototype.toString.call(new WeakSet())   // '[object WeakSet]'
Object.prototype.toString.call(new Map())       // '[object Map]'
Object.prototype.toString.call(new WeakMap())   // '[object WeakMap]'
Copy the code

We can see that this method returns the exact object type for any type of value passed in. The usage is straightforward, but there are a few points to understand:

  • The method is essentially a dependencyObject.prototype.toString() Method to get the internal properties of the object[[Class]]
  • Passing in the primitive type makes it possible to determine the result because the value is wrapped
  • nullundefinedThe ability to output results is handled by the internal implementation

For judging types, we can use the Object. The prototype, the toString () a simple packaging, so we cannot judge type, directly using the type function are ok.

The code is as follows:

var type = function(data) {
      var toString = Object.prototype.toString;
      var dataType = toString
              .call(data)
              .replace(/\[object\s(.+)\]/."$1")
              .toLowerCase()
      return dataType
};
Copy the code

Array.isArray()

Array.isArray also checks whether the passed argument is an Array. IsArray (ES 5.1) does not support IE6~8, so use it with compatibility issues.

  • Incompatible problem resolution occurred
    if (!Array.isArray) {
      Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
      };
    }
    Copy the code

4.2 Null value judgment

The importance of null value judgment

  if([]) {
    console.log('true');
  } else {
    consoel.log('false');
  }
  / / res: true
  
  if({}) {
    console.log('true');
  } else {
    consoel.log('false');
  }
  / / res: true
Copy the code

If the array is null, it will be converted to true. If the array is null, it will be converted to true.

Empty array judgment

If the array is empty, it is the type of the array and its length>0

Null object judgment

  1. Object.getOwnPropertyNames()

    Use Object. GetOwnPropertyNames (). The return value is an explicitly named array of properties in the object

    var obj = {}
    Object.getOwnPropertyNames(obj).length === 0; // true
    Copy the code
  2. Json objects are converted to strings

    Convert a JSON object to a string, and then compare the string to “{}”

    var obj = {};
    var a = JSON.stringify(obj);
    a === "{}"; // true
    // a === {}; // false
    Copy the code
  3. for… in… Cycle judgment

    var obj = {};
    
    function judgeObj(obj) {
      for(let key in obj) {
        return false
      }
      return true
    };
    
    judgeObj(obj); // true
    Copy the code
  4. Object.keys()

    The use of the Object. The keys (). ES6’s new method returns an array of property names as well

    var obj = {}
    Object.keys(obj).length === 0; // true
    Copy the code
  5. I’m going to use the object properties directly if I’m going to make sure that if OBj is not null, I’m going to include the name property

    var obj = {};
    
    obj && obj.name ? 'Not empty' : 'empty'; // 
    Copy the code

4.3 Use of equal sign

Comparison process:

  • Double equals == :

(1) If the two values are of the same type, compare the three equal signs (===)

(2) If two values have different types, they may also be equal. Type conversion should be performed according to the following rules for comparison:

1) If one is null and one is undefined, then equal

2) If one is a string and one is a number, convert the string to a number and then compare

  

  • 3 = = = = :

(1) If the types are different, they must not be equal

(2) If both values are the same, then they are equal; If at least one of them is a NaN, it is not equal. (To determine if a value is a NaN, use isNaN() only.)

(3) If both are strings, the characters in each position are the same, then equal, otherwise not equal.

(4) If both values are true or false, then they are equal

(5) If both values refer to the same object or function, they are equal; otherwise, they are not

(6) If both values are null, or undefined, then they are equal

5. Master the common functions of array string objects

5.1 Common functions of array

Splice function (to change the original array)

  • There is the ability to add elements to a specified position in an array

Array.splice(begin, deleteCount, addItem1, addItem2...)

// initial value of a: [1,2,3,4,5]

var b = arr.splice(1.2)
/ / a:].enlighened
/ / b: [2, 3]

var c = arr.splice(1.2.777.888)
/ / a: / 1777888, four, five
/ / b: [2, 3]
Copy the code

Slice function (create a new array without changing the original array)

The slice() method shallow-copies a portion of the array into a new array object and returns the array object.

Arr. Slice ([start[, end]])

The start argument specifies the index at which the replication starts, and end, if any, indicates the index at which the replication ends (excluding this location).

If the value of start is negative, if the array length is length, it means that the copy starts from the position of length+start. If end has a value, it must be a negative value greater than start. Otherwise, empty array is returned.

When the slice method argument is null, as with the concat method, shallow copy generates a new array.

var array = ["one"."two"."three"."four"."five"];
console.log(array.slice()); // ["one", "two", "three","four", "five"]
console.log(array.slice(2.3)); // ["three"]
Copy the code

Shallow copy refers to copying only the reference to the object when the object is copied, but it still refers to the same object. Here’s why slice is a shallow copy.

var array = [{color:"yellow"}, 2.3];
var array2 = array.slice(0.1);
console.log(array2); // [{color:"yellow"}]
array[0] ["color"] = "blue";
console.log(array2); // [{color:"bule"}]
Copy the code

Since slice is a shallow copy, the copied object is just a reference. If you change the value of array, array2 also changes.

In addition, we can easily retrieve the last element of the array by using the slice method with the first argument being negative, as follows:

The console. The log ([1, 2, 3]. Slice (1)); / / [3]

The join function

The join() method joins all the elements in the array into a single string.

Grammar arr. The join () 'XXX'

var b = arr.join(', '); / / b: '1, 2, 3'
var b = arr.join(The '*'); // b: '1*2*3'
Copy the code

Push function

Adds a value to an array.

Concat function

The concat() method merges the array or element passed in with the original array to form a new array and returns it.

IndexOf function

The indexOf() method finds the indexOf the element when it first appears in the array, or returns -1 if it does not.

Syntax: arr.indexof (Element, fromIndex=0)

Element is the element to be searched.

FromIndex is the starting position, which defaults to 0. If the array length is exceeded, -1 is returned. If the value is negative, and the array length is length, the search starts from the first item of the array length + fromIndex to the end of the array. If length + fromIndex<0, the entire array will be searched.

IndexOf uses strict equality (that is, using === to match elements in an array).

var array = ['abc'.'def'.'ghi'.'123'];
console.log(array.indexOf('def')); / / 1
console.log(array.indexOf('def', -1)); // -1 indicates that the search starts from the last element, so -1 is returned on failure
console.log(array.indexOf('def', -4)); // 1 Since 4 is larger than the array length, the entire array will be searched, so return 1
console.log(array.indexOf(123)); // -1 will not match the string '123' because it is a strict match
Copy the code

Includes function

The includes() method, based on the ECMAScript 2016 (ES7) specification, determines whether the current array contains a specified value and returns true if so, false otherwise.

Syntax: arr.includes(element, fromIndex=0)

Element is the element to be searched.

FromIndex means that element is searched from the index. The default value is 0. FromIndex is forward lookup, that is, from the index to the end of the array.

var array = [-0.1.2];
console.log(array.includes(+0)); // true
console.log(array.includes(1)); // true
console.log(array.includes(2, -4)); // true
Copy the code

Above, includes seems to ignore the difference between -0 and +0, which is not a problem because JavaScript has always been indifferent to -0 and +0.

Arr.indexof (x)>-1 = arr.includes(x). It seems so, almost all the time they are equivalent, the only difference being that Includes can find nans and indexOf can’t.

var array = [NaN];
console.log(array.includes(NaN)); // true
console.log(arra.indexOf(NaN) > -1); // false
Copy the code

(Here you can consider the efficiency of indexOf and includes, and the underlying implementation)

Array function has a lot of, the above only lists the commonly used several, found an article on a full array of functions, is very good, thank the authors share, recommend to everyone: louiszhai. Making. IO / 2017/04/28 /…

5.2 Common String Functions

The split function

  • Strings are divided into arrays
  • Do not change the original string
string.split(separator,limit)
Copy the code

The substr function

The substr() method returns a specified number of characters starting at a specified position in the string.

STR. Substr (start[, length])

Start indicates the start position for intercepting characters. The value can be positive or negative. A positive value indicates the index of the start position, and a negative value indicates the index of the length+start position.

Length indicates the length of the truncated character.

var str = "Yesterday is history. Tomorrow is mystery. But today is a gift.";
console.log(str.substr(47)); // today is a gift.
console.log(str.substr(-16)); // today is a gift.
Copy the code

Array function has a lot of, the above only lists the commonly used several, found an article on a whole string functions, is very good, thank the authors share, recommend to everyone: louiszhai. Making. IO / 2016/01/12 /…

5.3 Common functions of objects

Object.prototype.hasOwnProperty(prop)

This method returns true only if the target property is a property of the object itself, and false if the property is inherited from the stereotype chain or does not exist at all.

var o = {prop:1};
o.hasOwnProperty('prop'); // true
o.hasOwnProperty('toString'); // false
o.hasOwnProperty('formString'); // false
Copy the code

Object.create(obj, descr) (ES5)

This method is mainly used to create a new object and set the stereotype for it, using the property descriptor to define the stereotype properties of the object.

var parent = {hi: 'Hello'};
var o = Object.create(parent, {
    prop: {
        value: 1}}); o.hi;// 'Hello'
// Get the prototype
Object.getPrototypeOf(parent) === Object.prototype; // true indicates that the parent's prototype is object.prototype
Object.getPrototypeOf(o); // the prototype of o is {hi: "Hello"}
o.hasOwnProperty('hi'); // false indicates that hi is prototyped
o.hasOwnProperty('prop'); // true indicates that prop is a property on itself on the prototype.
Copy the code

Now, you can even use it to create a completely blank object, something you can’t do in ES3.

var o = Object.create(null);
typeof o.toString(); // 'undefined'
Copy the code

There are many array functions, the above list only a few commonly used, found a very full object function article, very good, thank the author to share, recommended to everyone: www.lxchuan12.cn/js-object-a…

6. Common special instructions

6.1 Arguments Are similar to array objects

What is an array-like object, for example:

let arrayLike = {
    '0': 'a'.'1': 'b'.'2': 'c'.length: 3
};
Copy the code

Class array conversion in several ways

  • ES6 extends the operator for the conversion

    var arr1 = [...arrayLike]; // ['a','b','c']
    Copy the code
  • ES6 in the Array. The from

    let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
    Copy the code

    Another use of array.from () is to convert a string to an Array and then return the length of the string.

    function countSymbols(string) {
      return Array.from(string).length;
    }
    Copy the code
  • ES5 Array. In the prototype. Slice. The call ()

    function test(a,b,c,d) 
       { 
          var arg = Array.prototype.slice.call(arguments.1); 
          alert(arg); 
       } 
       test("a"."b"."c"."d"); //b,c,d
    Copy the code
    • The first argument is context, which replaces this in the object function
    • The second argument is the argument passed to the object function

    Array. Prototype. Slice. The call (the arguments) will have the length attribute object into an Array, in addition to the IE node set (IE the dom object is implemented in the form of com objects, js object with the com object cannot transform)

6.2 Use of higher-order functions

See this article for more information on higher-order functions. High-order function description and actual combat in the realization of infinite superposition, array pat flat, to heavy can be used in high-order function.

7. Prove to the interviewer that ES6 will do the same

When it comes to writing code by hand, consider the simplicity of using ES6. Here you can take a look at ES6 extension operators… , set set, arrow function and other commonly used ES6 knowledge points, with ES6 ruanyifeng.com

8. Practice

Node.js has a queryString module that can convert the parameters following the urlStr host address into objects.

let urlStr = 'http://www.inode.club?name=koala&study=js&study=node';
Copy the code

The conversion result is as follows:

{ name: 'koala'.study: [ 'js'.'node']}Copy the code

Code implementation

You can implement it yourself and think about the process after reading this article

let urlStr = 'http://www.inode.club?name=koala&study=js&study=node'
// Parameters are converted to objects
function queryString(request){
    let params = request.split('? ') [1];
    let param = params.split('&');
    let obj = {};
    for (let i = 0; i<param.length; i++){let paramsA = param[i].split('=');
        let key = paramsA[0];
        let value = paramsA[1];
        if(obj[key]){
            obj[key] = Array.isArray(obj[key])? obj[key]:[obj[key]]; obj[key].push(value); }else{ obj[key] = value; }}return obj;
}
console.log(queryString(urlStr));
Copy the code

conclusion

This article is an outline to deal with handwritten code, the function is not all listed, according to the outline review, and then to see some often tested handwritten code problems, I feel easy to remember and clear some, I hope to help you.

Pay attention to my

  • Welcome to add my wechat [coder_qi], pull you node.js into the technology group, long-term exchange learning…
  • Welcome to “programmer growth refers to the north”, a heart to help you grow the public number…

Reference documentation

ES6 nguyen half-stretching

JavaScript string all API full decryption

All API parsing of JavaScript objects

Node series original articles

Learn more about processes and threads in Node.js

To learn node. js, it is necessary to know stream first

Exports: module. Exports: module

Understand the Events module thoroughly

Node.js advanced fs file module learning