Skip to content

Commit

Permalink
feat: support accessors in arrange (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
pbeshai authored Sep 23, 2021
1 parent 78c2b35 commit 257fb43
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions packages/tidy/src/arrange.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand Down
11 changes: 9 additions & 2 deletions packages/tidy/src/arrange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends object>(
comparators: SingleOrArray<Key | Comparator<T>>
// note: had to switch to returning `any` instead of using Comparator<T> (returns number)
// for #49 - otherwise typescript failed to do type inference on accessors
comparators: SingleOrArray<Key | ((a: T, b: T) => any)>
): TidyFn<T> {
const _arrange: TidyFn<T> = (items: T[]): T[] => {
// expand strings `key` to `asc(key)`
const comparatorFns = singleOrArray(comparators).map((comp) =>
typeof comp === 'function' ? comp : asc<T>(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<T>)
: asc<T>(comp)
);

return items.slice().sort((a, b) => {
Expand Down

0 comments on commit 257fb43

Please sign in to comment.