Brush the front end of the book

1. The following recursive functions are at risk of stack overflow. How to optimize them?

function factorial(n){
    return n*factorial(n-1)
}

Answer:

function factorial(n){
    if(n === 1) { return 1;};
    return n*factorial(n-1)
}

2. Please implement a function to calculate the maximum common divisor:

function greatestCommonDivisor(a,b){
//Write code here
}
greatestCommonDivisor(8, 12) //4
greatestCommonDivisor(8, 16) //8
greatestCommonDivisor(8, 17) //1

Answer:

function greatestCommonDivisor(a,b){
  var num=0;  
      while(b!=0){       
           num=a%b;  
           a=b;  
           b=num;  
      }  
      return a;

}

3. Array de duplication (if there is NaN in the array)

Array.prototype.uniq = function () {
   var resArr = [];
   var flag = true;
      
   for(var i=0;i<this.length;i++){
       if(resArr.indexOf(this[i]) == -1){
           if(this[i] != this[i]){   

               //Exclude NaN
              if(flag){
                   resArr.push(this[i]);
                   flag = false;
              }
           }else{
                resArr.push(this[i]);
           }
       }
   }
    return resArr;
}

4. Using JavaScript to implement Fibonacci sequence function, return the nth Fibonacci number. f(1) = 1, f(2) = 1, etc

function fibonacci(n) {
    if(n ==1 || n == 2){
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

5. Create objects in the specified space according to the package name

Enter a description:

namespace({a: {test: 1, b: 2}}, 'a.b.c.d')

Output Description:

{a: {test: 1, b: {c: {d: {}}}}}

function namespace(oNamespace, sPackage) {
 
    var properties = sPackage.split('.');
    var parent = oNamespace;
 
    for (var i = 0, lng = properties.length; i < lng; ++i) {
 
        var property = properties[i];
 
        if (Object.prototype.toString.call(parent[property])!== '[object Object]') {
            parent[property] = {};
        }
 
        parent = parent[property];
 
    }
 
    return oNamespace;
 
}

6. Encapsulate function f so that this of F points to the specified object

function bindThis(f, oTarget) {
    return function(){
        var parames = Array.prototype.slice.call(arguments);
        return f.apply(oTarget,parames); //Note that the execution result of f needs to be returned here
    }  
}

7.dom node lookup

Finds the closest common parent of two nodes, which can include the node itself

Enter a description:

Ononode1 and ononode2 are in the same document and will not be the same node

function commonParentNode(oNode1, oNode2) {
    if(oNode1.contains(oNode2)){
        return oNode1;
    }else if(oNode2.contains(oNode1)){
        return oNode2;
    }else{
        return commonParentNode(oNode1.parentNode,oNode2);
    }
}

8. Convert relational array to tree structure object

Relational array:

var obj = [
    { id:3, parent:2 },
    { id:1, parent:null },
    { id:2, parent:1 },
]

Expected results:

o = {
  obj: {
    id: 1,
    parent: null,
    child: {
      id: 2,
      parent: 1,
      child: {
          id: ,3,
          parent: 2
      }
    }
  }
}

Implementation source code:

function treeObj(obj) {
  obj.map(item => {
    if (item.parent !== null) {
      obj.map(o => {
        if (item.parent === o.id) {
          if (!o.child) {
            o.child = [];
          }
          o.child.push(item);
          o.child = o.child;
        }
      });
    }
  });
  return obj.filter(item => item.parent === null)[0]
}

Or:

function treeObj(obj) {
  return obj.sort((a, b) => b.parent - a.parent)
      .reduce((acc, cur) => (acc ? { ...cur, child: acc } : cur));
}

9. How JS judges whether a group of numbers are continuous

//Output with '-' when consecutive numbers appear
[1, 2, 3, 4, 6, 8, 9, 10]

Expected results:

["1-4", 6, "8-10"]

Implementation code:

Judge whether it is continuous:

var arrange = function(arr){
    var result = [],temp = [];
    arr.sort(function(source, dest){
        return source - dest;
    }).concat(Infinity).reduce(function(source, dest){
        temp.push(source);
        if(dest-source > 1){
            result.push(temp);
            temp = [];
        }
        return dest;
    });
    return result;
};

Format implementation:

var formatarr = function(arr) {
    var newArr = []
    var arr1 = arrange(arr)
    for (var i in arr1) {
        var str = '';
        if (arr1[i].length > 1) {
            str = arr1[i][0] + '-' + arr1[i][arr1[i].length - 1];
            newArr.push(str)
        } else {
            newArr.push(arr1[i][0]);
        }
   }
   return newArr;
}

10. Create the Child subclass, inherit the method of the parent class People by using the prototype and constructor, and call the say function to say the name and age.

Parent class:

function People(name,age){
     this.name=name;
     this.age=age;
     this.say=function(){
         console.log("My name is:"+this.name+"I am this year"+this.age+"Year old!");
     };
}

Prototype inheritance:

function Child(name, age){
    this.name = name;
    this.age = age;
}
Child.prototype = new People();
var child = new Child('Rainy', 20);
child.say()

Constructor inheritance:

function Child(name, age){
    People.call(this)
    this.name = name;
    this.age = age;
}
var child = new Child('Rainy', 20);
child.say()

Combination inheritance:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = People.prototype;
var child = new Child('Rainy', 20);
child.say()

Combination inheritance Optimization:

function Child(name, age){
    People.call(this);
    this.name = name;
    this.age = age;
}
Child.prototype = Object.create(People.prototype);
Child.prototype.constructor = Child;
var child = new Child('Rainy', 20);
child.say()

Tags: Javascript

Posted on Mon, 02 Dec 2019 01:55:29 -0500 by watson516