Javascript - Order Pattern

I. Giới thiệu

Pattern là một phần quan trọng trong lập trình. Nó sẽ giúp cho việc phát triển các chức năng dễ dàng hơn, dễ mở rộng, tránh việc trùng lặp code.

Việc order một list các object trong javascript có thể được thực hiện dễ dàng thông qua order pattern dưới đây.

II. Sử dụng
1. Function Order Pattern
        
    "use strict";
    Order.version = 'Order-1.1 10-03-2021';
    Order.ASC = 'ASC';
    Order.DESC = 'DESC';
    
    function Order(values){
        this.values = values;
        this.meet = function(propertiesOrder){
            if(!propertiesOrder || propertiesOrder.length == 0) return this.values;
            this.values.sort(function(a, b){
                for(var i = 0; i < propertiesOrder.length; i++){
                    var property = propertiesOrder[i].property;
                    var orderType = propertiesOrder[i].orderType;
                    if(a[property] == b[property]) continue;
                    if(a[property] && b[property]){
                        if(a[property] < b[property]){
                            return Order.ASC == orderType ? -1 : 1;
                        }
                        if(a[property] > b[property]){
                            return Order.ASC == orderType ? 1 : -1;
                        }
                    }
                    if(!a[property]){
                        return Order.ASC == orderType ? 1 : -1;
                    }
                    if(!b[property]){
                        return Order.ASC == orderType ? -1 : 1;
                    }
                }
            });
        }
    }
        
      
2. Test
        
    // object input
    var bondPayments = [
    {
        "bondHolderIdType": "1",
        "bondHolderIdNumber": "181978397",
        "customerRegionType": "3",
        "bondCode": "SGP202101",
        "customerType": "Cá nhân",
        "nationalityCode": "234",
        "totalQuantity": 29450
    },
    {
        "bondHolderIdType": "1",
        "bondHolderIdNumber": "118755784",
        "customerRegionType": "9",
        "bondCode": "SGP202101",
        "customerType": "Cá nhân",
        "nationalityCode": "234",
        "totalQuantity": 10000
    },
    {
        "bondHolderIdType": "1",
        "bondHolderIdNumber": "155114415",
        "customerRegionType": "4",
        "bondCode": "SGP202101",
        "customerType": "Cá nhân",
        "nationalityCode": "234",
        "totalQuantity": 10000,
    }
    ];

    var order = new Order(bondPayments);
    order.meet([
        {property: 'bondCode', orderType: Order.ASC},
        {property: 'customerRegionType', orderType: Order.DESC},
        {property: 'bondHolderIdNumber', orderType: Order.ASC}
    ]);
    console.log('bondPayments', bondPayments);
        
      

Nhận xét

Bài đăng phổ biến từ blog này

IBM BPM - Date

BPM WebSphere - Create Datasource (Connect to DB via JDBC)

IBM BPM - Error: Save error