[code Notes] JS keeps function single responsibility and flexible combination

Keywords: Javascript JSON JQuery

For example, in the following code, the order data requested from the server is as follows, which needs to be processed as follows
1. Display corresponding value according to status (0-in progress, 1-completed, 2-order exception)
2. Display startTime as yyyy MM DD from time stamp
3. If the field value is an empty string, set the field value to '--'

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:'Waiting',
        type:0
    },
    {
        id:2,
        name:'Rove all over the world',
        type:1
    },
    {
        id:3,
        name:'once',
        type:2
    }
]

Next, use the principle of single responsibility to set status, startTime, type, --. This is divided into four functions.

let handleFn={
    setStatus(list){
        let _status={
            0:'Have in hand',
            1:'Completed',
            2:'Order exception'
        }
        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:'Ordinary users',
            1:'vip',
            2:'super vip'
        }
        list.forEach(item=>{
            item.type=item.type.toString()?_type[item.type]:'';
        })
        return list;
    }
}

Just call the function directly:

//Process order data
orderList=handleFn.setStatus(orderList);
orderList=handleFn.setStartTime(orderList);
orderList=handleFn.setInfo(orderList);
console.log(orderList);
//Processing user data
userList=handleFn.setType(userList);
userList=handleFn.setInfo(userList);
console.log(userList);

Results obtained:

If you dislike the trouble of continuous assignment, you can borrow the idea of jQuery to make chain call.

let ec=(function () {
    let handle=function (obj) {
        //Deep copy object
        this.obj=JSON.parse(JSON.stringify(obj));
    };
    handle.prototype={
        /**
         * @description Set up confidential information
         */
        setInfo(){
            this.obj.map(item=>{
                for(let key in item){
                    if(item[key]===''){
                        item[key]='--';
                    }
                }
            });
            return this;
        },
        /**
         * @description Setup state
         */
           setStatus(){
               let _status={
                   0:'Have in hand',
                   1:'Completed',
                   2:'Order exception'
               }
               this.obj.forEach(item=>{
                item.status=item.status.toString()?_status[item.status]:''
            });
            return this;
           },
           /**
         * @description Setup time
         */
           setStartTime(){
               this.obj.forEach(item=>{
                item.startTime=item.startTime.toString()?new Date(item.startTime).toLocaleDateString().replace(/\//g,'-'):'';
            });
            return this;
           },
           /**
         * @description Set type
         */
           setType(){
            let _type={
                0:'Ordinary users',
                1:'vip',
                2:'super vip'
            }
            this.obj.forEach(item=>{
                item.type=item.type.toString()?_type[item.type]:'';
            })
            return this;
        },
        /**
         * @description Return processing results
         * @return {Array|*}
         */
        end(){
            return this.obj;
        }
    }
    //Expose constructor interface
    return function (obj) {
        return new handle(obj);
    }
})();

In this way, it can be called in chain

//Process order data
orderList=ec(orderList).setStatus().setStartTime().setInfo().end();
console.log(orderList);
//Processing user data
userList=ec(userList).setType().end();
console.log(userList);

There is a problem above, that is, every time a method is called, it will perform traversal once. The way to deal with it is to record only what to deal with in each function, but not to deal with it. When it is executed to the end, it will be handled uniformly and returned.

let ec=(function () {
    let handle=function (obj) {
        //Deep copy object
        this.obj=JSON.parse(JSON.stringify(obj));
        //Record the steps to be processed
        this.handleFnList=[];
    };
    handle.prototype={
        /**
         * @description Set up confidential information
         */
        handleSetInfo(item){
            for(let key in item){
                if(item[key]===''){
                    item[key]='--';
                }
            }
            return this;
        },
        setInfo(){
            this.handleFnList.push('handleSetInfo');
            return this;
        },
        /**
         * @description Setup state
         */
           handleSetStatus(item){
               let _status={
                   0:'Have in hand',
                   1:'Completed',
                   2:'Order exception'
               }
            item.status=item.status.toString()?_status[item.status]:''
            return item;
           },
           setStatus(){
            this.handleFnList.push('handleSetStatus');
            return this;
        },
           /**
         * @description Setup time
         */
           handleSetStartTime(item){
            item.startTime=item.startTime.toString()?new Date(item.startTime).toLocaleDateString().replace(/\//g,'-'):'';
            return item;
           },
           setStartTime(){
            this.handleFnList.push('handleSetStartTime');
            return this;
        },
           /**
         * @description Set type
         */
           handleSetType(item){
            let _type={
                0:'Ordinary users',
                1:'vip',
                2:'super vip'
            }
            item.type=item.type.toString()?_type[item.type]:'';
            return item;
        },
        setType(){
            this.handleFnList.push('handleSetType');
            return this;
        },
        /**
         * @description Return processing results
         * @return {Array|*}
         */
        end(){
            //Unified processing operation
            this.obj.forEach(item=>{
                this.handleFnList.forEach(fn=>{
                    item=this[fn](item);
                })
            })
            return this.obj;
        }
    }
    //Expose constructor interface
    return function (obj) {
        return new handle(obj);
    }
})();

Reference address: [exploration] try to improve the reusability of code in development

Posted by iii on Sat, 07 Dec 2019 14:32:37 -0800