温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript代码优化之怎么提炼函数

发布时间:2022-08-16 09:25:21 来源:亿速云 阅读:105 作者:iii 栏目:开发技术

本篇内容主要讲解“JavaScript代码优化之怎么提炼函数”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“JavaScript代码优化之怎么提炼函数”吧!

提炼函数

what

将一段代码提炼到一个独立的函数中,并以这段代码的作用命名。

where

如果需要花时间浏览一段代码才能弄清楚它到底要干什么,那么这时候就应该将其提炼到一个函数中,并根据它所做的事命名。以后再读这段代码时,一眼就能知道这个函数的用途。

how

// ==================重构前==================
function printOwing(invoice) {
    let outstanding = 0;
    console.log("***********************");
    console.log("**** Customer Owes ****");
    console.log("***********************");
}
// ==================重构后==================
function printOwing(invoice) {
    let outstanding = 0;
    printBanner()
}
function printBanner() {
    console.log("***********************");
    console.log("**** Customer Owes ****");
    console.log("***********************");
}

函数参数化

what

以参数的形式传入不同的值,消除重复函数

where

如果发现两个函数逻辑非常相似, 只有一些字面量值不同, 可以将其合并成一个函数, 以参数的形式传入不同的值, 从而消除重复。

how

// ==================重构前==================
// 点击异常项
clickFaultsItem(item){
    this.$u.route({
        url:'xxx',
        params:{
            id: item.id,
            type: '异常'
        }
    })
}
// 点击正常项
clickNormalItem(item){
    this.$u.route({
        url:'xxx',
        params:{
            id: item.id,
            type: '正常'
        }
    })
}
// ==================重构后==================
clickItem(id, type){
     this.$u.route({
        url:'xxx',
        params:{id, type}
    })
}

使用策略模式替换“胖”分支

what

使用策略模式替换“胖胖”的if-else或者switch-case

where

当if-else或者switch-case分支过多时可以使用策略模式将各个分支独立出来

how

// ==================重构前==================
function getPrice(tag, originPrice) {
    // 新人价格
    if(tag === 'newUser') {
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    }
    // 返场价格
    if(tag === 'back') {
         return originPrice > 200 ? originPrice - 50 : originPrice
    }
    // 活动价格
    if(tag === 'activity') {
        return originPrice > 300 ? originPrice - 100 : originPrice
    }
}
// ==================重构后==================
const priceHandler = {
    newUser(originPrice){
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    },
    back(originPrice){
        return originPrice > 200 ? originPrice - 50 : originPrice
    },
    activity(originPrice){
         return originPrice > 300 ? originPrice - 100 : originPrice
    }
}
function getPrice(tag, originPrice){
    return priceHandler[tag](originPrice)
}

提炼变量

what

提炼局部变量替换表达式

where

一个表达式有可能非常复杂且难以阅读。 这种情况下, 可以提炼出一个局部变量帮助我们将表达式分解为比较容易管理的形式 ,这样的变量在调试时也很方便。

how

// ==================重构前==================
function price(order) {
    //价格 = 商品原价 - 数量满减价 + 运费
    return order.quantity * order.price -
    Math.max(0, order.quantity - 500) * order.price * 0.05 +
    Math.min(order.quantity * order.price * 0.1, 100);
}
// ==================重构后==================
function price(order) {
    const basePrice = order.quantity * order.price;
    const quantityDiscount = Math.max(0, order.quantity - 500) * order.price * 0.05;
    const shipping = Math.min(basePrice * 0.1, 100);
    return basePrice - quantityDiscount + shipping;
}

内联变量

what

用变量右侧表达式消除变量,这是提炼变量的逆操作

where

当变量名字并不比表达式本身更具表现力时可以采取该方法

how

// ==================重构前==================
let basePrice = anOrder.basePrice;
return (basePrice > 1000);
// ==================重构后==================
return anOrder.basePrice > 1000

封装变量

what

将变量封装起来,只允许通过函数访问

where

对于所有可变的数据, 只要它的作用域超出单个函数,就可以采用封装变量的方法。数据被使用得越广, 就越是值得花精力给它一个体面的封装。

how

// ==================重构前==================
let defaultOwner = {firstName: "Martin", lastName: "Fowler"};
// 访问
spaceship.owner = defaultOwner;
// 赋值
defaultOwner = {firstName: "Rebecca", lastName: "Parsons"};
// ==================重构后==================
function getDefaultOwner() {return defaultOwner;}
function setDefaultOwner(arg) {defaultOwner = arg;}
// 访问
spaceship.owner = getDefaultOwner();
// 赋值
setDefaultOwner({firstName: "Rebecca", lastName: "Parsons"});

拆分阶段

what

把一大段行为拆分成多个顺序执行的阶段

where

当看见一段代码在同时处理两件不同的事, 可以把它拆分成各自独立的模块, 因为这样到了需要修改的时候, 就可以单独处理每个模块。

how

// ==================重构前==================
function priceOrder(product, quantity, shippingMethod) {
    const basePrice = product.basePrice * quantity;
    const discount = Math.max(quantity - product.discountThreshold, 0)
    * product.basePrice * product.discountRate;
    const shippingPerCase = (basePrice > shippingMethod.discountThreshold)
    ? shippingMethod.discountedFee : shippingMethod.feePerCase;
    const shippingCost = quantity * shippingPerCase;
    const price = basePrice - discount + shippingCost;
    return price;
}
/*
该例中前两行代码根据商品信息计算订单中与商品相关的价格, 随后的两行则根据配送信息计算配送成本。
将这两块逻辑相对独立后,后续如果修改价格和配送的计算逻辑则只需修改对应模块即可。
*/
// ==================重构后==================
function priceOrder(product, quantity, shippingMethod) {
    const priceData = calculatePricingData(product, quantity);
    return applyShipping(priceData, shippingMethod);
}
// 计算商品价格
function calculatePricingData(product, quantity) {
    const basePrice = product.basePrice * quantity;
    const discount = Math.max(quantity - product.discountThreshold, 0)
    * product.basePrice * product.discountRate;
    return {basePrice, quantity, discount};
}
// 计算配送价格
function applyShipping(priceData, shippingMethod) {
    const shippingPerCase = (priceData.basePrice > shippingMethod.discountThreshold)
    ? shippingMethod.discountedFee : shippingMethod.feePerCase;
    const shippingCost = priceData.quantity * shippingPerCase;
    return priceData.basePrice - priceData.discount + shippingCost;
}

拆分循环

what

将一个循环拆分成多个循环

where

当遇到一个身兼数职的循环时可以将循环拆解,让一个循环只做一件事情, 那就能确保每次修改时你只需要理解要修改的那块代码的行为就可以了。该行为可能会被质疑,因为它会迫使你执行两次甚至多次循环,实际情况是,即使处理的列表数据更多一些,循环本身也很少成为性能瓶颈,更何况拆分出循环来通常还使一些更强大的优化手段变得可能。

how

// ==================重构前==================
const people = [
    { age: 20, salary: 10000 },
    { age: 21, salary: 15000 },
    { age: 22, salary: 18000 }
]
let youngest = people[0] ? people[0].age : Infinity;
let totalSalary = 0;
for (const p of people) {
    // 查找最年轻的人员
    if (p.age < youngest) youngest = p.age;
    // 计算总薪水
    totalSalary += p.salary;
}
console.log(`youngestAge: ${youngest}, totalSalary: ${totalSalary}`);
// ==================重构后==================
const people = [
    { age: 20, salary: 10000 },
    { age: 21, salary: 15000 },
    { age: 22, salary: 18000 }
]
let totalSalary = 0;
for (const p of people) {
    // 只计算总薪资
    totalSalary += p.salary;
}
let youngest = people[0] ? people[0].age : Infinity;
for (const p of people) {
    // 只查找最年轻的人员
    if (p.age < youngest) youngest = p.age;
} 
console.log(`youngestAge: ${youngest}, totalSalary: ${totalSalary}`);
// ==================提炼函数==================
const people = [
    { age: 20, salary: 10000 },
    { age: 21, salary: 15000 },
    { age: 22, salary: 18000 }
]
console.log(`youngestAge: ${youngestAge()}, totalSalary: ${totalSalary()}`);
function totalSalary() {
    let totalSalary = 0;
    for (const p of people) {
        totalSalary += p.salary;
    }
    return totalSalary;
} 
function youngestAge() {
    let youngest = people[0] ? people[0].age : Infinity;
    for (const p of people) {
        if (p.age < youngest) youngest = p.age;
    }
    return youngest;
}
// ==================使用工具类进一步优化==================
const people = [
    { age: 20, salary: 10000 },
    { age: 21, salary: 15000 },
    { age: 22, salary: 18000 }
]
console.log(`youngestAge: ${youngestAge()}, totalSalary: ${totalSalary()}`);
function totalSalary() {
    return people.reduce((total,p) => total + p.salary, 0);
}
function youngestAge() {
    return Math.min(...people.map(p => p.age));
}

拆分变量

what

将一个变量拆分成两个或多个变量

where

如果变量承担多个责任, 它就应该被替换为多个变量, 每个变量只承担一个责任。

how

// ==================重构前==================
let temp = 2 * (height + width);
console.log(temp);
temp = height * width;
console.log(temp);
// ==================重构后==================
const perimeter = 2 * (height + width);
console.log(perimeter);
const area = height * width;
console.log(area);

分解条件表达式

what

将条件表达式提炼成函数

where

在带有复杂条件逻辑的函数中,往往可以将原函数中对应的代码改为调用新函数。

对于条件逻辑, 将每个分支条件分解成新函数可以带来的好处:

  • 提高可读性

  • 可以突出条件逻辑, 更清楚地表明每个分支的作用

  • 突出每个分支的原因

how

// ==================重构前==================
// 计算一件商品的总价,该商品在冬季和夏季的单价是不同的
if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd))
charge = quantity * plan.summerRate;
else
charge = quantity * plan.regularRate + plan.regularServiceCharge;
// ==================重构后==================
if (summer())
    charge = summerCharge();
else
    charge = regularCharge();
function summer() {
    return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
}
function summerCharge() {
    return quantity * plan.summerRate;
}
function regularCharge() {
    return quantity * plan.regularRate + plan.regularServiceCharge;
}
// 进一步优化(使用三元运算符)
charge = summer() ? summerCharge() : regularCharge();
function summer() {
    return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
}
function summerCharge() {
    return quantity * plan.summerRate;
}
function regularCharge() {
    return quantity * plan.regularRate + plan.regularServiceCharge;
}

合并条件表达式

what

将多个条件表达式合并

where

当发现这样一串条件检查: 检查条件各不相同, 最终行为却一致。 如果发现这种情况,就应该使用“逻辑或”和“逻辑与”将它们合并为一个条件表达式。

how

// ==================重构前==================
if (anEmployee.seniority < 2) return 0;
if (anEmployee.monthsDisabled > 12) return 0;
if (anEmployee.isPartTime) return 0;
// ==================重构后==================
if (isNotEligableForDisability()) return 0;
function isNotEligableForDisability() {
    return ((anEmployee.seniority < 2)
            || (anEmployee.monthsDisabled > 12)
            || (anEmployee.isPartTime));
}

以卫语句取代嵌套条件表达式

what

如果某个条件极其罕见,就应该单独检查该条件,并在该条件为真时立刻从函数中返回。 这样的单独检查常常被称为“卫语句”(guard clauses)。

where

如果使用if-else结构,你对if分支和else分支的重视是同等的。这样的代码结构传递给阅读者的消息就是:各个分支有同样的重要性。卫语句就不同了,它告诉阅读者: “这种情况不是本函数的核心逻辑所关心的, 如果它真发生了,请做一些必要的整理工作,然后退出。” 为了传递这种信息可以使用卫语句替换嵌套结构。

how

// ==================重构前==================
function payAmount(employee) {
    let result;
    if(employee.isSeparated) {
        result = {amount: 0, reasonCode:"SEP"};
    }
    else {
        if (employee.isRetired) {
            result = {amount: 0, reasonCode: "RET"};
        }
        else {
            result = someFinalComputation();
        }
    }
    return result;
}
// ==================重构后==================
function payAmount(employee) {
    if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
    if (employee.isRetired) return {amount: 0, reasonCode: "RET"};
    return someFinalComputation();
}

将查询函数和修改函数分离

what

将查询动作从修改动作中分离出来的方式

where

如果遇到一个“既有返回值又有副作用”的函数,此时可以将查询动作从修改动作中分离出来。

how

// ==================重构前==================
function alertForMiscreant (people) {
    for (const p of people) {
        if (p === "Don") {
            setOffAlarms();
            return "Don";
        }
        if (p === "John") {
            setOffAlarms();
            return "John";}
    }
    return "";
}
// 调用方
const found = alertForMiscreant(people);
// ==================重构后==================
function findMiscreant (people) {
    for (const p of people) {
        if (p === "Don") {
            return "Don";
        }
        if (p === "John") {
            return "John";
        }
    }
    return "";
}
function alertForMiscreant (people) {
    if (findMiscreant(people) !== "") setOffAlarms();
}
// 调用方
const found = findMiscreant(people);
alertForMiscreant(people);

到此,相信大家对“JavaScript代码优化之怎么提炼函数”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI