All files sortBy.ts

79.31% Statements 46/58
68.18% Branches 30/44
88.89% Functions 8/9
78.95% Lines 45/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 15010x 10x 10x 10x 10x                                                                             10x 22x       22x 22x 43x 43x     43x 39x     43x       49x   44x 44x     5x 5x         43x       49x     49x 15x 15x 15x   34x     34x     34x   43x 15x         19x 19x 19x 19x     19x 19x 13x         30x       30x         30x     30x       30x           22x     10x             10x        
import { clone } from './clone';
import { isArray, isObject } from './guards';
import { pipe } from './pipe';
import { purry } from './purry';
import { type } from './type';
 
export type SortValue = boolean | number | string;
export type ComplexSort = {
  order?: 'asc' | 'desc';
  value: SortValue;
  compare?: (a: SortValue, b: SortValue) => number;
};
export type SortByProp = SortValue | ComplexSort | (SortValue | ComplexSort)[];
/**
 * Sorts the list according to the supplied function in ascending order.
 * Sorting is based on a native `sort` function. It's not guaranteed to be stable.
 * @param array - the array to sort
 * @param fn - the mapping function
 * @signature
 *    P.sortBy(array, fn)
 * @signature
 *    P.sortBy(fn)(array)
 * @example
 *    P.sortBy(
 *      [{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }],
 *      x => x.a
 *    )
 *    // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
 *
 *    P.pipe(
 *      [{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }],
 *      P.sortBy(x => x.a)
 *    ) // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
 * @category Array, Pipe
 */
export function sortBy<T>(
  array: readonly T[],
  fn: (item: T) => SortByProp
): T[];
export function sortBy<T>(
  fn: (item: T) => SortByProp
): (array: readonly T[]) => T[];
 
export function sortBy() {
  return purry(_sortBy, arguments);
}
 
function _sortBy<T>(array: T[], fn: (item: T) => SortByProp): T[] {
  const copied = clone(array);
  const sortedArray = copied.sort((a, b) => {
    const aa = fn(a);
    const bb = fn(b);
    type SortFunction = (a: SortValue, b: SortValue) => number;
    /** Default comparison function */
    const defaultCompare = (a: SortValue, b: SortValue) => {
      return a < b ? -1 : a > b ? 1 : 0;
    };
    /** Easy way to swap order */
    const order = (
      order: 'asc' | 'desc',
      sortFn: SortFunction
    ): SortFunction => {
      switch (order) {
        case 'asc':
          return (a: SortValue, b: SortValue) => {
            return sortFn(a, b);
          };
        case 'desc':
          return (a: SortValue, b: SortValue) => {
            return sortFn(b, a);
          };
      }
    };
 
    const sortComplex = (
      aC: Exclude<SortByProp, Array<any>>,
      bC: Exclude<SortByProp, Array<any>>
    ) => {
      Iif (type(aC) !== type(bC)) {
        throw new Error("Can't compare two different types");
      }
      if (isObject(aC) && isObject(bC)) {
        const sortFn = order(aC.order || 'asc', bC.compare || defaultCompare);
        const orderScore = sortFn(aC.value, bC.value);
        return orderScore;
      }
      Iif (isObject(aC)) {
        throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard
      }
      Iif (isObject(bC)) {
        throw new Error('Impossible error'); // Code should never throw this error. Using this only as typescript guard
      }
      return order('asc', defaultCompare)(aC, bC);
    };
    if (isArray(aa) && isArray(bb)) {
      Iif (aa.length !== bb.length) {
        throw new Error(
          'Critical sortBy error. Comparison properties should be static'
        );
      }
      for (const sIndex of new Array(aa.length).fill(0).map((_, i) => i)) {
        const aaV = aa[sIndex];
        const bbV = bb[sIndex];
        Iif (type(aaV) !== type(bbV)) {
          throw new Error("Can't compare two different types");
        }
        const result = sortComplex(aaV, bbV);
        if (result !== 0) {
          return result;
        }
      }
    }
 
    Iif (type(aa) !== type(bb)) {
      throw new Error("Can't compare two different types");
    }
 
    Iif (isObject(aa) && isObject(bb)) {
      const sortFn = order(aa.order || 'asc', aa.compare || defaultCompare);
      const orderScore = sortFn(aa.value, bb.value);
      return orderScore;
    }
    Iif (isObject(aa)) {
      throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard
    }
    Iif (isObject(bb)) {
      throw new Error('Impossible error'); // Code should never throw this error. Using this only as typescript guard
    }
 
    return sortComplex(
      aa as Exclude<SortByProp, Array<any>>,
      bb as Exclude<SortByProp, Array<any>>
    );
  });
 
  return sortedArray;
}
 
const l = [
  {
    a: 4,
    x: 74,
  },
];
 
pipe(
  l,
  sortBy(a => a.a)
);