All files sortBy.ts

100% Statements 8/8
75% Branches 3/4
100% Functions 3/3
100% Lines 8/8

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 471x                                                                   1x 2x       2x 2x 10x 10x 10x      
import { purry } from './purry';
 
/**
 * Sorts the list according to the supplied function in ascending order.
 * @param array the array to sort
 * @param fn the mapping function
 * @signature
 *    R.sortBy(array, fn)
 * @example
 *    R.sortBy(
 *      [{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }],
 *      x => x.a
 *    )
 *    // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
 * @data_first
 * @category Array
 */
export function sortBy<T>(array: T[], fn: (item: T) => any): T[];
 
/**
 * Sorts the list according to the supplied function in ascending order.
 * @param fn the mapping function
 * @signature
 *    R.sortBy(fn)(array)
 * @example
 *    R.pipe(
 *      [{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }],
 *      R.sortBy(x => x.a)
 *    ) // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
 * @data_last
 * @category Array
 */
export function sortBy<T>(fn: (item: T) => any): (array: T[]) => T[];
 
export function sortBy() {
  return purry(_sortBy, arguments);
}
 
function _sortBy<T>(array: T[], fn: (item: T) => any): T[] {
  const copied = [...array];
  return copied.sort((a, b) => {
    const aa = fn(a);
    const bb = fn(b);
    return aa < bb ? -1 : aa > bb ? 1 : 0;
  });
}