Project/code optimization iterative refactoring

  1. Realization, correctness
  2. Concise and easy to understand, readable, annotated, clear structure, remove redundant code
  3. Unified style, code specification, design pattern, scalability, packaging, modularity
  4. Architecture optimization, performance optimization

Case1: What is the left-pad event?

To be sorted and supplemented

Case2: The traffic light status changes

Code).

Don’t pass the exam. Js

const traffic = document.getElementById('traffic'); (function reset()){ traffic.className = 's1'; setTimeout(function() { traffic.className = 's2'; setTimeout(function(){ traffic.className = 's3'; setTimeout(function(){ traffic.className = 's4'; setTimeout(function(){ traffic.className = 's5'; setTimeout(reset, 1000) }, 1000) }, 1000) }, 1000) }, 1000); }) ();Copy the code

Version 1.1

Data encapsulation – Data abstraction version1.js

const traffic = document.getElementById('traffic');

const stateList = [
    {state: 'wait', last:1000},
    {state: 'stop', last:3000},
    {state: 'pass', last:3000},
];
function start(traffic, stateList) {
    function applyState(StateIdx) {
        const {state, last} = stateList[stateIdx];
        traffic.className = state;
        setTimeout(() => {
            applyState((stateIdx + 1) % stateList.length);
        }, last)
    }
    applyState(0);
}

start(traffic, stateList);

Copy the code

Version 1.2

version2.js

const traffic = document.getElementById('traffic'); function polll(... fnList) { let stateIndex = 0; return function(... args){ let fn = fnList[stateIndex++ % fnList.length]; return fn.apply(this, args); } } function setState(state){ traffic.className = state; } let trafficStatePoll = poil(SetState.bind(null, 'wait), SetState.bind(null, 'stop), SetState.bind(null, 'pass)); setInterval(trafficStatePoll, 2000);Copy the code

Version 1.3

const traffic = document.getElementById('traffic');

function wait(time){
    return new Promise(resolve => setTimeout(resolve, time));
}

function setState(state){
    traffic.className = status;
}

async function start(){
    //noprotect
    while(1){
        setState('wait');
        await wait(1000);
        setState('stop');
        await wait(3000);
        setState('pass');
        await wait(3000);
    }
}

start();

Copy the code

Release and summary

There are more complicated methods.

This course is a strong code teaching, in the actual development of the project experience and learn to master the program optimization. However, according to my own learning habit, a program has been reconstructed for 4 iterations, and each time the evolution is wonderful, but the time is prolonged and too long time distrudes attention. If the time is controlled within 3 times or the number of iteration versions is predicted, the experience may be better. The advantage is that you have time to review what you haven’t learned, and the opportunity to allocate your energy with relative freedom.

Case3: Check if it is a power of 4

Version 1

function isPowerOfFour(num){
    num = parseInt(num);
    
    while(num > 1){
        if(num % 4) return false;
        num /=4;
    }
    return true;
}
    
Copy the code

Version 1.1

function isPowerOfFour(num){
    num = parseInt(num);
    
    return num > 0 && (num & (num - 1)) === 0 && (num & 0xAAAAAAAA) === 0;
}    

Copy the code

Version 1.2 Regular expressions

function isPowerOfFour(num){ num = parseInt(num).toString(2); return /^(? :00)*$/.test(num); }Copy the code

Release and summary

Have you thought of a better way? I love the open-ended encouragement.

However, I feel that the two cases need to calm down and digest, but the lecturer has immediately entered the analysis of the next case. Up to here, the course is a little bit difficult, my class state into the second stage, a little low mood. Now comes the challenge of my concentration.

Case4: Shuffle algorithm: correctness

Version 1

const cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; Function shuffle(cards) {return [...cards].sort(() => math.random () > 0.5? 1:1); } const result = Array(10).fill(0); for(let i = 0; i < 10000; i++) { const c = shuffle(cards); for(let j = 0; j < 10; j++) { result[j] += c[j]; } } console.log(result);Copy the code

Version 1.2 OK

Mathematical induction

const cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; function shuffle(cards) { const c = [...cards]; for(let i = c; i > 0; i--) { const pIdx = Math.floor(Math.random()*i); [c[pIdx], c[i-1] = [c[i-1], c[pIdx]]; } return c; } const result = Array(10),fill(0); for(let i=0; i<10000;  i++) { const c= shuffle(cards); for(let j=0; j<10; j++) { result[j] += c[j]; } } console.log(shuffle(cards));  console.log(result)Copy the code

Version 1.3 Generator version

1000

const cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function draw(cards) {
    const c = [...cards];
    for(let i = c.length; i > 0; i--) {
        const pIdx = Math.floor(Math.random()*i);
        [c[pIdx], c[i-1] = [c[i-1], c[pIdx]];
        yield c[i-1];
    }
}

const result = draw(cards);
console.log([...result])
Copy the code

Project summary

Powerless. I’m used to implementing code as an exercise and a test of my mastery. Although the lecturer prepared the code carefully and systematically detailed the knowledge points, I still could not run and debug the demo code in time at my speed, which resulted in a low sense of achievement and frustrated motivation. Hope to have simplified case, 5 minutes in class case realization, in order to enhance enthusiasm and sense of participation.

Red envelope generator

Version 1 PPT version (even red envelope amount)

.js picks out the largest piece for segmentation

function generate(amout, count){ let ret = [amount]; while(count > 1){ let cake = Math.max(... ret), idx = ret.indexOf(cake), part = 1 + Math.floor((cake / 2)* Math.random(1)), rest = cake - part; ret.splice(idx, 1, part, rest); count--; } return ret; } const amountEl = document.getElementById('amount'); const countEl = document.getElemnetById('count') const generateBtn = document.getElemnetById('generateBtn') const resultEl = document.getElemnetById('result')Copy the code

Error: No result is displayed after clicking the random generate button .html

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <h2> </h2> <div id="setting"> <div><label> <input ID ="amount" value=100.00></input></label></div> <div><label> <input ID ="amount" value=100.00></input></label></div> <div><button ID ="generateBtn"> Randomly generated </button></div> </div> < URL id="result"></ul> </body> </html>Copy the code

Version 1.2 Randomly generate N cutting positions (amount is random)

const cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; function draw(cards) { const c = [...cards]; for(let i = c.length; i > 0; i--) { const pIdx = Math.floor(Math.random()*i); [c[pIdx], c[i-1] = [c[i-1], c[pIdx]]; yield c[i-1]; } } function generate(amout, count){ if(count <= 1) return [amount];  const cards = Array(amount - 1).fill(0).map((_, i) => i + 1); const pick = draw(cards); const result = [];  for(let i = 0; i< count; i++) { result.push(pick.next().value); } result.sort((a, b) => a- b); for(let i = count - 1;  i > 0; i--) { result[i] = result[i] - result[i-1]; } return result; }Copy the code