From 257fb435117398304ad8822135e7a33211c57051 Mon Sep 17 00:00:00 2001 From: Peter Beshai Date: Thu, 23 Sep 2021 16:09:59 -0700 Subject: [PATCH] feat: support accessors in arrange (#50) --- CHANGELOG.md | 3 +++ packages/tidy/src/arrange.test.ts | 22 ++++++++++++++++++++++ packages/tidy/src/arrange.ts | 11 +++++++++-- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0f169f..2cf48ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Tidy follows semver. All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# 2.4.4 (2021-09-23) +* Feat: arrange now works with accessors: `arrange([d => d.foo.bar])` instead of requiring comparators or wrapping with asc or desc + # 2.4.3 (2021-08-17) * Fix: groupBy now works on columns containing objects with valueOf() e.g. Dates #46 diff --git a/packages/tidy/src/arrange.test.ts b/packages/tidy/src/arrange.test.ts index 130a645..359291e 100644 --- a/packages/tidy/src/arrange.test.ts +++ b/packages/tidy/src/arrange.test.ts @@ -321,6 +321,28 @@ describe('arrange', () => { ).toEqual(['C', 'A', 'B']); }); + it('arranges with accessor functions', () => { + expect( + tidy( + [ + { str: 'foo', value: 3 }, + { str: 'foo', value: 1 }, + { str: 'bar', value: 3 }, + { str: 'bar', value: 1 }, + { str: 'bar', value: 7 }, + ], + (d) => d, + arrange((a) => a.str), + arrange([(a) => a.str, (a) => a.value]) + ) + ).toEqual([ + { str: 'bar', value: 1 }, + { str: 'bar', value: 3 }, + { str: 'bar', value: 7 }, + { str: 'foo', value: 1 }, + { str: 'foo', value: 3 }, + ]); + }); it('works with function accessors passed to asc or desc', () => { const results = tidy( [ diff --git a/packages/tidy/src/arrange.ts b/packages/tidy/src/arrange.ts index b7aaea6..09579b1 100644 --- a/packages/tidy/src/arrange.ts +++ b/packages/tidy/src/arrange.ts @@ -7,12 +7,19 @@ import { Comparator, Key, KeyOrFn, TidyFn } from './types'; * @param comparators Given a, b return -1 if a comes before b, 0 if equal, 1 if after */ export function arrange( - comparators: SingleOrArray> + // note: had to switch to returning `any` instead of using Comparator (returns number) + // for #49 - otherwise typescript failed to do type inference on accessors + comparators: SingleOrArray any)> ): TidyFn { const _arrange: TidyFn = (items: T[]): T[] => { // expand strings `key` to `asc(key)` const comparatorFns = singleOrArray(comparators).map((comp) => - typeof comp === 'function' ? comp : asc(comp) + typeof comp === 'function' + ? // length === 1 means it is an accessor (1 argument). convert to comparator via asc + comp.length === 1 + ? asc(comp as (d: T) => unknown) + : (comp as Comparator) + : asc(comp) ); return items.slice().sort((a, b) => {