js代码的优化之路

1.命名时,尽量使用容易区分 容易懂的命名,不要总是用 a1,a2,str,data这样的通用命名
2.命名时,有几个单词时,不要用缩写,这样的单词念不出来,别人也不懂是什么意思
3.我们的代码应该是易找的 所以善于定义变量或者常量 比如计时器的时间参数设定
4. 使用for in 时,可以直接用内部属性作为变量 这样读者就可以直接了解该对象中的具体参数
5.命名时 不要用一个字母 代表一个单词 或者一层意思。 明晰才是王道
6.不要增加不必要的命名内容 eg:

Bad:

type Car = {
  carMake: string;
  carModel: string;
  carColor: string;
}

function print(car: Car): void {
  console.log(`${car.carMake} ${car.carModel} (${car.carColor})`);
}
Good:

type Car = {
  make: string;
  model: string;
  color: string;
}

function print(car: Car): void {
  console.log(`${car.make} ${car.model} (${car.color})`);
}

7.使用默认参数

Bad:

function loadPages(count?: number) {
  const loadCount = count !== undefined ? count : 10;
  // ...
}
Good:

function loadPages(count: number = 10) {
  // ...
}

8.正常情况下,函数的参数不要超过三个,函数过多时,可以通过一个对象解决。
9.代码尽量简写 比如参数中的 写太多抽离为一个变量。之类的
10.尽量做到,一个函数只做一件事,这样方便重构
11.函数名应该有多详细就多详细
12.当您有多个抽象级别时,您的函数通常做得太多。拆分函数会导致可重用性和更容易的测试。
13.重复代码不要写,这样在你将来修改的时候,意味着修改多个地方
14.善于使用Objest.assign()这样可以避免在新增属性时,不停的点来点去
15.在函数中,一个函数只做一件事,如果存在判断 则将他们分开
16.函数的执行 尽量不要去改变全局的变量 多使用return返回值
17.在项目中我们可能会给数组一些新的方法,这些方法在项目中很常用,所以我们一般在js中选择在数组的原型中添加 Array.prototype中添加。但是这样会造成命名冲突或者其他问题。在ts中我们就可以 创建一个类去实现

Bad:

declare global {
  interface Array<T> {
    diff(other: T[]): Array<T>;
  }
}

if (!Array.prototype.diff) {
  Array.prototype.diff = function <T>(other: T[]): T[] {
    const hash = new Set(other);
    return this.filter(elem => !hash.has(elem));
  };
}
Good:

class MyArray<T> extends Array<T> {
  diff(other: T[]): T[] {
    const hash = new Set(other);
    return this.filter(elem => !hash.has(elem));
  };
}

18.善于使用函数式编程而不是命令式编程

Bad:

const contributions = [
  {
    name: 'Uncle Bobby',
    linesOfCode: 500
  }, {
    name: 'Suzie Q',
    linesOfCode: 1500
  }, {
    name: 'Jimmy Gosling',
    linesOfCode: 150
  }, {
    name: 'Gracie Hopper',
    linesOfCode: 1000
  }
];

let totalOutput = 0;

for (let i = 0; i < contributions.length; i++) {
  totalOutput += contributions[i].linesOfCode;
}
Good:

const contributions = [
  {
    name: 'Uncle Bobby',
    linesOfCode: 500
  }, {
    name: 'Suzie Q',
    linesOfCode: 1500
  }, {
    name: 'Jimmy Gosling',
    linesOfCode: 150
  }, {
    name: 'Gracie Hopper',
    linesOfCode: 1000
  }
];

const totalOutput = contributions
  .reduce((totalLines, output) => totalLines + output.linesOfCode, 0);

19.尽量将条件语句封装起来
20.尽量使用正向判断,不要使用逆向判断,eg:

Bad:

function isEmailNotUsed(email: string): boolean {
  // ...
}

if (isEmailNotUsed(email)) {
  // ...
}
Good:

function isEmailUsed(email): boolean {
  // ...
}

if (!isEmailUsed(node)) {
  // ...
}

21.在js中有时会使用switch去做很多判断,这时可以使用多态性来实现相同的任务。

Bad:

class Airplane {
  private type: string;
  // ...

  getCruisingAltitude() {
    switch (this.type) {
      case '777':
        return this.getMaxAltitude() - this.getPassengerCount();
      case 'Air Force One':
        return this.getMaxAltitude();
      case 'Cessna':
        return this.getMaxAltitude() - this.getFuelExpenditure();
      default:
        throw new Error('Unknown airplane type.');
    }
  }

  private getMaxAltitude(): number {
    // ...
  }
}
Good:

abstract class Airplane {
  protected getMaxAltitude(): number {
    // shared logic with subclasses ...
  }

  // ...
}

class Boeing777 extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getPassengerCount();
  }
}

class AirForceOne extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude();
  }
}

class Cessna extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getFuelExpenditure();
  }
}

22.将注释掉的代码,重复的代码,遗弃的代码 直接删除 没必要一直留着,就算之后需要他也一直在你的版本库中。
23.善于使用类中的get和set方法
24.如果一个类中的的参数不参与 赋值,只参与运算的话,可以使用 private 和 readonly将他保护起来
25.当可能需要联合或交叉时,请使用类型。在需要扩展或实现时使用接口
26.一个class应该很小,一般不会出现一个类里有很多的内容
27.始终注意高内聚低耦合,如果内容可拆分就拆分,牢记一个函数只做一件事,不怕函数多,就怕函数不纯
28.在使用类的时候 组合的用法多于继承
29.链式写法很常见也很重要:

Bad:

class QueryBuilder {
  private collection: string;
  private pageNumber: number = 1;
  private itemsPerPage: number = 100;
  private orderByFields: string[] = [];

  from(collection: string): void {
    this.collection = collection;
  }

  page(number: number, itemsPerPage: number = 100): void {
    this.pageNumber = number;
    this.itemsPerPage = itemsPerPage;
  }

  orderBy(...fields: string[]): void {
    this.orderByFields = fields;
  }

  build(): Query {
    // ...
  }
}

// ...

const queryBuilder = new QueryBuilder();
queryBuilder.from('users');
queryBuilder.page(1, 100);
queryBuilder.orderBy('firstName', 'lastName');

const query = queryBuilder.build();
Good:

class QueryBuilder {
  private collection: string;
  private pageNumber: number = 1;
  private itemsPerPage: number = 100;
  private orderByFields: string[] = [];

  from(collection: string): this {
    this.collection = collection;
    return this;
  }

  page(number: number, itemsPerPage: number = 100): this {
    this.pageNumber = number;
    this.itemsPerPage = itemsPerPage;
    return this;
  }

  orderBy(...fields: string[]): this {
    this.orderByFields = fields;
    return this;
  }

  build(): Query {
    // ...
  }
}

// ...

const query = new QueryBuilder()
  .from('users')
  .page(1, 100)
  .orderBy('firstName', 'lastName')
  .build();

30.始终保持一个类中不要有过多的功能,这样会使内聚性降低
31.类模块函数应该分开进行扩展
32.在类中,不能强迫他们不适用他们不使用的接口
32. Dependency Inversion Principle (DIP)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lar_slw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值