博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[代码笔记]JS保持函数单一职责,灵活组合
阅读量:4562 次
发布时间:2019-06-08

本文共 6001 字,大约阅读时间需要 20 分钟。

比如下面的代码,从服务端请求回来的订单数据如下,需要进行以下处理

1.根据 status 进行对应值得显示(0-进行中,1-已完成,2-订单异常)
2.把 startTime 由时间戳显示成 yyyy-mm-dd
3.如果字段值为空字符串 ,设置字段值为 ‘--’

let orderList=[    {        id:1,        status:0,        startTime:1538323200000,    },    {        id:2,        status:2,        startTime:1538523200000,    },    {        id:3,        status:1,        startTime:1538723200000,    },    {        id:4,        status:'',        startTime:'',    },];let userList=[    {        id:1,        name:'守候',        type:0    },    {        id:2,        name:'浪迹天涯',        type:1    },    {        id:3,        name:'曾经',        type:2    }]

下面就使用单一职责的原则设置 status,startTime,type,-- 。这里拆分成四个函数。

let handleFn={    setStatus(list){        let _status={            0:'进行中',            1:'已完成',            2:'订单异常'        }        list.forEach(item=>{            item.status=item.status.toString()?_status[item.status]:'';        })        return list    },    setStartTime(list){        list.forEach(item=>{            item.startTime=item.startTime.toString()?new Date(item.startTime).toLocaleDateString().replace(/\//g,'-'):'';        })        return list;    },    setInfo(list){        list.forEach(item=>{            for(let key in item){                if(item[key]===''){                    item[key]='--';                }            }        })        return list;    },    setType(list){        let _type={            0:'普通用户',            1:'vip',            2:'超级vip'        }        list.forEach(item=>{            item.type=item.type.toString()?_type[item.type]:'';        })        return list;    }}

下面直接调用函数就好:

//处理订单数据orderList=handleFn.setStatus(orderList);orderList=handleFn.setStartTime(orderList);orderList=handleFn.setInfo(orderList);console.log(orderList);//处理用户数据userList=handleFn.setType(userList);userList=handleFn.setInfo(userList);console.log(userList);

得到的结果:

如果嫌弃连续赋值麻烦,可以借用 jQuery 的那个思想,进行链式调用。

let ec=(function () {    let handle=function (obj) {        //深拷贝对象        this.obj=JSON.parse(JSON.stringify(obj));    };    handle.prototype={        /**         * @description 设置保密信息         */        setInfo(){            this.obj.map(item=>{                for(let key in item){                    if(item[key]===''){                        item[key]='--';                    }                }            });            return this;        },        /**         * @description 设置状态         */           setStatus(){               let _status={                   0:'进行中',                   1:'已完成',                   2:'订单异常'               }               this.obj.forEach(item=>{                item.status=item.status.toString()?_status[item.status]:''            });            return this;           },           /**         * @description 设置时间         */           setStartTime(){               this.obj.forEach(item=>{                item.startTime=item.startTime.toString()?new Date(item.startTime).toLocaleDateString().replace(/\//g,'-'):'';            });            return this;           },           /**         * @description 设置type         */           setType(){            let _type={                0:'普通用户',                1:'vip',                2:'超级vip'            }            this.obj.forEach(item=>{                item.type=item.type.toString()?_type[item.type]:'';            })            return this;        },        /**         * @description 返回处理结果         * @return {Array|*}         */        end(){            return this.obj;        }    }    //暴露构造函数接口    return function (obj) {        return new handle(obj);    }})();

这样就可以链式调用了

//处理订单数据orderList=ec(orderList).setStatus().setStartTime().setInfo().end();console.log(orderList);//处理用户数据userList=ec(userList).setType().end();console.log(userList);

上面有个问题,就是每次调用一个方法就会执行遍历一遍,处理的方式就是在每一个函数里面,只记录要处理什么,但是不进行处理,等到执行到 end 的时候再统一处理,以及返回。

let ec=(function () {    let handle=function (obj) {        //深拷贝对象        this.obj=JSON.parse(JSON.stringify(obj));        //记录要处理的步骤        this.handleFnList=[];    };    handle.prototype={        /**         * @description 设置保密信息         */        handleSetInfo(item){            for(let key in item){                if(item[key]===''){                    item[key]='--';                }            }            return this;        },        setInfo(){            this.handleFnList.push('handleSetInfo');            return this;        },        /**         * @description 设置状态         */           handleSetStatus(item){               let _status={                   0:'进行中',                   1:'已完成',                   2:'订单异常'               }            item.status=item.status.toString()?_status[item.status]:''            return item;           },           setStatus(){            this.handleFnList.push('handleSetStatus');            return this;        },           /**         * @description 设置时间         */           handleSetStartTime(item){            item.startTime=item.startTime.toString()?new Date(item.startTime).toLocaleDateString().replace(/\//g,'-'):'';            return item;           },           setStartTime(){            this.handleFnList.push('handleSetStartTime');            return this;        },           /**         * @description 设置type         */           handleSetType(item){            let _type={                0:'普通用户',                1:'vip',                2:'超级vip'            }            item.type=item.type.toString()?_type[item.type]:'';            return item;        },        setType(){            this.handleFnList.push('handleSetType');            return this;        },        /**         * @description 返回处理结果         * @return {Array|*}         */        end(){            //统一处理操作            this.obj.forEach(item=>{                this.handleFnList.forEach(fn=>{                    item=this[fn](item);                })            })            return this.obj;        }    }    //暴露构造函数接口    return function (obj) {        return new handle(obj);    }})();

参考地址:

转载于:https://www.cnblogs.com/moqiutao/p/9985470.html

你可能感兴趣的文章
软键盘覆盖EditText解决方法
查看>>
Daily Scrumming* 2015.11.1(Day 13)
查看>>
css不定高图文垂直居中的三种方法
查看>>
剑指offer--1.二维数组中的查找
查看>>
第3次作业:团队介绍
查看>>
[html][javascript]父子窗体传值
查看>>
收房细则
查看>>
读《Android深度探索(卷1)HAL与驱动开发》的一些思考10
查看>>
二十三、uevnet机制和U盘自动挂载
查看>>
Kettle 提取mongodb最大编号
查看>>
Vue2.0-token权限处理
查看>>
Caffeine缓存
查看>>
JavaScript 回车键转成Tab键
查看>>
CentOS7配置MySQL5.7主备
查看>>
合并区间(LintCode)
查看>>
mysql索引的创建
查看>>
《 BCG 原创 :系列 三》 添加菜单栏
查看>>
Java中关于CyclicBarrier的使用
查看>>
vsftpd配置教程
查看>>
first ios app
查看>>