Skip to content

Commit

Permalink
feat(utilities): add objectValues function (#474)
Browse files Browse the repository at this point in the history
* feat(utilities): add `objectValues` function

* test(objectValues): cover readonly types

* fix(objectValues): return type

* chore(utilities): re-order export for `objectValues`

* Update packages/utilities/src/lib/objectValues.ts

Co-authored-by: Jeroen Claassens <jeroen.claassens@live.nl>
  • Loading branch information
RealShadowNova and favna committed Oct 1, 2022
1 parent 8cd1293 commit 90c2409
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utilities/src/index.ts
Expand Up @@ -33,6 +33,7 @@ export * from './lib/mergeDefault';
export * from './lib/mergeObjects';
export * from './lib/noop';
export * from './lib/objectToTuples';
export * from './lib/objectValues';
export * from './lib/parseUrl';
export * from './lib/partition';
export * from './lib/range';
Expand Down
5 changes: 5 additions & 0 deletions packages/utilities/src/lib/objectValues.ts
@@ -0,0 +1,5 @@
import type { NonNullObject } from './utilityTypes';

export function objectValues<T extends NonNullObject>(obj: T): T extends ArrayLike<any> ? T[number][] : T[keyof T][] {
return Object.values(obj) as T extends ArrayLike<infer Values> ? Values[] : T[keyof T][];
}
31 changes: 31 additions & 0 deletions packages/utilities/tests/objectValues.test.ts
@@ -0,0 +1,31 @@
import { objectValues } from '../src';

describe('objectValues', () => {
test('GIVEN basic readonly THEN returns expected', () => {
const source = { a: 'Hello', b: 420 } as const;
const expected = ['Hello', 420];

expect<('Hello' | 420)[]>(objectValues(source)).toEqual(expected);
});

test('GIVEN deep readonly THEN returns expected', () => {
const source = { a: 'Hello', b: 420, deep: { i: [] } } as const;
const expected = ['Hello', 420, { i: [] }];

expect<('Hello' | 420 | { i: readonly [] })[]>(objectValues(source)).toEqual(expected);
});

test('GIVEN basic readonly THEN returns expected', () => {
const source = { a: 'Hello', b: 420 };
const expected = ['Hello', 420];

expect(objectValues(source)).toEqual(expected);
});

test('GIVEN deep THEN returns expected', () => {
const source = { a: 'Hello', b: 420, deep: { i: [] } };
const expected = ['Hello', 420, { i: [] }];

expect(objectValues(source)).toEqual(expected);
});
});

0 comments on commit 90c2409

Please sign in to comment.