Angular2 TypSscript 函数,用于按多个字段对对象数组进行排序



我正在尝试将此函数转换为Angular2/TypeScript,以便按多个字段对对象数组进行排序。

我是打字稿的新手,如何检查它是否干净?

我在打电话

prodataTemp.sort(this.UtilsService.sort_by('brand', 'name', 'model'));

在utils-service.ts中:

sort_by(...args: any[]) { //multiple sort https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields
        var fields = [],
            n_fields = args.length,
            field, name, reverse, cmp;
        var default_cmp = function(a, b) {
            if (a == b) return 0;
            return a < b ? -1 : 1;
        };
        var getCmpFunc = function(primer, reverse) {
            var dfc = default_cmp, // closer in scope
                cmp = default_cmp;
            if (primer) {
                cmp = function(a, b) {
                    return dfc(primer(a), primer(b));
                };
            }
            if (reverse) {
                return function(a, b) {
                    return -1 * cmp(a, b);
                };
            }
            return cmp;
        };
        // preprocess sorting options
        for (var i = 0; i < n_fields; i++) {
            field = args[i];
            if (typeof field === 'string') {
                name = field;
                cmp = default_cmp;
            }
            else {
                name = field.name;
                cmp = getCmpFunc(field.primer, field.reverse);
            }
            fields.push({
                name: name,
                cmp: cmp
            });
        }
        // final comparison function
        return function(A, B) {
            var a, b, name, result;
            for (var i = 0; i < n_fields; i++) {
                result = 0;
                field = fields[i];
                name = field.name;
                result = field.cmp(A[name], B[name]);
                if (result !== 0) break;
            }
            return result;
        }
    };
function sortByMutipleFields(...args: string[]) {
  // takes a list of arguments representing sort fields
  // if preceded by a ! then reverse order (!lastName for example)
  // returns a function that works in Array.sort()
  return (a: any, b: any): number => {
    for (var index = 0; index < args.length; index++) {
      let fieldLeft: string;
      let fieldRight: string;
      if (args[index].startsWith('!')) {
        fieldLeft = b[args[index].slice(1)];
        fieldRight = a[args[index].slice(1)];
      } else {
        fieldLeft = a[args[index]];
        fieldRight = b[args[index]];
      }
      if (fieldLeft > fieldRight) { return 1 };
      if (fieldLeft < fieldRight) { return -1 };
    };
    return 0;
  }
}

这样做呢?

相关内容

  • 没有找到相关文章

最新更新