[Javascript] Refactoring: Polymorphic Functions
JavaScript Functions
2023-09-14 09:00:54 时间
if-statements can add serious complexity and beg for refactoring. You can use polymorphic functions to simplify your ifs and dynamically call the appropriate method.
For example you have the code like:
function charge(){ if(this.moive.type==="regular"){ // ...some logic if(this.daysRented > 2){ // ...some logic } }else if(this.moive.type==="new release"){ // ...some logic }else if(this.moive.type==="childrens"){ // ...some logic if(this.daysRented > 3){ // ...some logic } } return amount; }
We can refactor to:
require("activesupport") this.charge = () => { return this.[this.type.titleize().split(" ").join('').camelize() + "Charge"](daysRented); } this.regularCharge = ()=>{ if(daysRented > 2){ } } this.newRelseaseCharge = () => { } this.childrenCharge = () => { if(daysRented > 3){ } }
So based on the type we will call different function.
相关文章
- javascript中通过元素id和name直接取得元素
- javascript获取表单值的7种方式
- 基于JavaScript 声明全局变量的三种方式详解
- [Javascript] Write a Generator Function to Generate the Alphabet / Numbers
- [Javascript Crocks] Flatten Nested Maybes with `chain`
- [Javascript] String Padding in Javascript using padStart and padEnd functions
- [Javascript] Identify the most important words in a document using tf-idf in Natural
- 理解Javascript_02_理解undefined和null [转]
- [Javascript] Prototype Pattern
- [Javascript Crocks] Make your own functions safer by lifting them into a Maybe context
- [Javascript] Promise-based functions should not throw exceptions
- [Javascript] Advanced Reduce: Composing Functions with Reduce
- 从零开始学_JavaScript_系列(21)——dojo(8)(手把手教你封装一个widget)
- 【 华为OD机试 2023】 递增字符串(C++ Java JavaScript Python)
- javaScript在私有的属性和方法
- 如何写出优美的 JavaScript 代码?