基于ES6的代码重构要点

接见原文地点

Why

  • 对底本代码逻辑举行提炼,进步代码的浏览性。

  • 加强代码的Object Oriented和Functional Programming特征。

  • 再逻辑还不算太庞杂的时刻,早点订正一些Coding范例。

重构要点

  1. Construct HTML using template strings.

  2. Eliminate if/else blocks with hash maps.

  3. Collapse multiple arguments with a config object.

  4. Pre-bind arguments to make point-free functions.

  5. Break complex conditionals with intention revealing .variables.

  6. Inline IIFE for complex initialization.

  7. Use hoisting/composed-method to focus on important code.

1.运用ES6的template string来替代不好用的html文本

var html = '<div class="my-car-class-contain">' +
            '<div class="my-car-class-title">' + title + '</div>' + 
            '<img src="' + url + '">' +
            '</div>';

//运用template直接就能够像些angular的模板一样在js代码中插进去html
let tmp_html = `<div class="my-car-class-contain">
                <div class="my-car-class-title">${title}</div>
                <img src="${url}" alt="">
                </div>`;

2.用hash-map来替代庞杂的if/else推断前提

function getSomething(type) {
    if (type === 'boy') {
        return '/img/bog.jpg'
    } else if (type === 'man') {
        return '/img/man.jpg'
    } else if (type === 'girl') {
        return '/img/girl.jpg'
    } else (type === 'woman') {
        return '/img/woman.jpg'
    }
}

//hash-map
function getSomething(type) {
    var typeMap = {
        boy: '/img/bog.jpg',
        man: '/img/man.jpg',
        girl: '/img/girl.jpg',
        woman: '/img/woman.jpg',
    }
    
    return typeMap[type] || '/img/default.jpg';
}

//当condition或许type前提很庞杂的时刻,能够把他们提取出来,以便保护
import typeMap from './conditions';

3.削减函数入参,用Object来替代。

function formatNumber(value, decimals, asPercent, prefix, suffix) {
    var formattedNumber = value;
    
    //do something
    
    return formattedNumber;
}
formatNumber(10,2,false,'','%');

//应用ES6默认值特征,以及对象定义参数
function formatNumber({value=0, decimals=0, asPercent=false, prefix=‘’, suffix=‘’}){}
var num = 20;
formatNumber({value: num, suffix:'%'});

4.运用bind要领,将一个函数星散成多个更好明白的函数

function doOperation(name='default', args=[]) {
    // 这是一个经由历程name来决议操作要领的函数
}
function findSome() {
    return Promise.resolve('LS460h');
}
function getCarList() {
    return Promise.resolve({size:4800, seats:5, output:6.0});
}
findSome().then(args => {
    doOperation('searchCar', args);
});
getCarList().then(args => {
    doOperation('buyLexus', args);
});

//修正历程
//先经由历程bind函数,将操作要领从参数导入的体式格局星散成2个函数
var play = doOperation.bind(null, 'searchCar');
var buy = doOperation.bind(null, 'buyLexus');

findSome().then(play);
getCarList().then(buy);

5.运用array的some要领来重构前提推断语句

import _ from 'lodash';
var age,
    gamer = [],
    adNetworks = [],
    specialAchievements = [];

function showGame() {
    /* do something */
}

if((age > 0 && age <0) || 
    gamer.isFirstTime ||
    _.some(adNetworks, function(n) {
        return gamer.network === n;
    }) ||
    _.some(specialAchievements, function(ach) {
        return gamer.specialAchievement = ach;
    })) {
    showGame();    
}

把conditions提炼成Array,并运用箭头函数

var conditions = [
    () => {
        return age > 0 && age <0;
    },
    () => gamer.isFirstTime,
    () => {
        return _.some(adNetworks, n => gamer.network === n);
    },
    () => {
        return _.some(specialAchievements, ach => gamer.specialAchievement === ach);
    },
    //到场新的前提,就变得很轻松
    () => specialAchievements.length > 0
];

let matches = _.some(conditions, c=>c());
if(matches) {
    showGame();    
}

6.运用IIFE(Immediately-Invoked Function Expression)做庞杂初始化

var settings = readSettings();
var apiUrl = `https://${settings.apiDomain}:${settings.apiPort}/api`;

var defaultConfig = {
    apiUrl:apiUrl,
    timezone: settings.timezone,
    account: settings.account,
    theme: settings.theme
}

// IIFE 
var defaultConfig = (() => {
    var settings = readSettings();
    var apiUrl = `https://${settings.apiDomain}:${settings.apiPort}/api`;

    var defaultConfig = {
        apiUrl:apiUrl,
        timezone: settings.timezone,
        account: settings.account,
        theme: settings.theme
    }
})();

7.把回调的逻辑抽取成函数,隐蔽逻辑,让代码语义更清楚。

_fetchData(url)
    .then(data => {
        //do something
    })
    .then(transactions => {
        //do something
    })

//after
import {processData, renderHtml} from './doSomething'
_fetchData(url)
    .then(processData)
    .then(renderHtml);
    原文作者:sutaking
    原文地址: https://segmentfault.com/a/1190000007461531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞