Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement hasPresentKeys #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ In a nutshell:
- `isDefined`: Removes `undefined` values via a `filter`.
- `isFilled`: Removes `null` values via a `filter`.
- `hasPresentKey`: Removes everything that is not an object with the expected key present via a `filter`.
- `hasPresentKeys`: Removes everything that is not an object with the expected keys present via a `filter`.
- `hasValueAtKey`: The same as `hasPresentKey` but with an additional check for a particular value.

## Short explanation
Expand Down Expand Up @@ -73,7 +74,7 @@ const definedResults: Array<TestData> = results.filter(isPresent);
As you can see, `isPresent` can drop `undefined`, `null` and `void` values from an array (where `void` values are
really just `undefined` in disguise). This makes it broadly applicable.

## Use `hasPresentKey` and `hasValueAtKey` to filter objects
## Use `hasPresentKey`, `hasPresentKeys` and `hasValueAtKey` to filter objects

If you want to find all of the objects in an array that have a particular field present, you can use `hasPresentKey`. For example:

Expand All @@ -82,6 +83,13 @@ const filesWithUrl = files.filter(hasPresentKey("url"));
files[0].url // TS will know that this is present
```

If you want to find all of the objects in an array that have a particular number of fields present, you can use `hasPresentKeys`. For example:

``` typescript
const filesWithUrl = files.filter(hasPresentKey(["url", "name"]));
files[0].url || files[0].name // TS will know that this is present
```

If you want to find all of the objects with a particular field set to a particular value you can use `hasValueAtKey`:

``` typescript
Expand Down
66 changes: 51 additions & 15 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
isFilled,
hasPresentKey,
hasValueAtKey,
hasPresentKeys,
} from '.';

type TestData = {
Expand Down Expand Up @@ -51,9 +52,7 @@ describe('Functions', () => {

describe('isDefined', () => {
it('should return true on defined', () => {
expect(
isDefined<TestData>({ data: 'hello world' })
).toBeTruthy();
expect(isDefined<TestData>({ data: 'hello world' })).toBeTruthy();
});

it('should return false on undefined', () => {
Expand Down Expand Up @@ -97,9 +96,7 @@ describe('Functions', () => {

describe('isFilled', () => {
it('should return true on defined', () => {
expect(
isFilled<TestData>({ data: 'hello world' })
).toBeTruthy();
expect(isFilled<TestData>({ data: 'hello world' })).toBeTruthy();
});

it('should return false on null', () => {
Expand Down Expand Up @@ -160,6 +157,45 @@ describe('Functions', () => {
});
});

describe('hasPresentKeys', () => {
it('returns true only for objects that have a defined non-null single value at the given key', () => {
expect(hasPresentKeys(['data'])({ data: undefined })).toEqual(false);
expect(hasPresentKeys(['data'])({ data: null })).toEqual(false);
expect(hasPresentKeys(['data'])({ data: '' })).toEqual(true);
expect(hasPresentKeys(['data'])({ data: 'hello' })).toEqual(true);

const items: Array<{ data?: string | null | undefined }> = [
{},
{ data: undefined },
{ data: null },
{ data: '' },
{ data: 'hello' },
];
const result = items.filter(hasPresentKeys(['data']));
expect(result).toEqual([{ data: '' }, { data: 'hello' }]);
});


it('returns true only for objects that have a defined non-null multiple value at the given key', () => {
expect(hasPresentKeys(['data', 'fruit'])({ data: undefined, fruit: undefined })).toEqual(false);
expect(hasPresentKeys(['data', 'fruit'])({ data: null, fruit: null })).toEqual(false);
expect(hasPresentKeys(['data', 'fruit'])({ data: '', fruit: '' })).toEqual(true);
expect(hasPresentKeys(['data', 'fruit'])({ data: 'hello', fruit: 'banana' })).toEqual(true);

const items: Array<{ data?: string | null | undefined, fruit?: string | null | undefined }> = [
{},
{ data: undefined, fruit: undefined },
{ data: null, fruit: null },
{ data: '', fruit: '' },
{ data: 'hello', fruit: 'banana' },
{ data: null, fruit: 'banana' },
{ data: 'hello', fruit: null },
];
const result = items.filter(hasPresentKeys(['data', 'fruit']));
expect(result).toEqual([{ data: '', fruit: '' }, { data: 'hello', fruit: 'banana' }]);
});
});

describe('hasValueAtKey', () => {
it('returns true only for objects that have a defined value at the given key', () => {
expect(hasValueAtKey('data', 'a')({ data: undefined })).toEqual(false);
Expand All @@ -180,17 +216,17 @@ describe('Functions', () => {

const fruits: Array<
| {
type: 'apple';
isApple: true;
}
type: 'apple';
isApple: true;
}
| {
type: 'banana';
isBanana: true;
}
type: 'banana';
isBanana: true;
}
> = [
{ type: 'apple', isApple: true },
{ type: 'banana', isBanana: true },
];
{ type: 'apple', isApple: true },
{ type: 'banana', isBanana: true },
];
const fruitsResult: Array<{
type: 'apple';
isApple: true;
Expand Down
29 changes: 29 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,35 @@ export function hasPresentKey<K extends string | number | symbol>(k: K) {
};
}

/**
* Returns a function that can be used to filter down objects
* to the ones that have a defined non-null value under the keys `k`.
*
* @example
* ```ts
* const filesWithUrlAndName = files.filter(file => file.url && file.name);
* files[0].url || files[0].name // In this case, TS might still treat this as undefined/null
*
* const filesWithUrlAndName = files.filter(hasPresentKeys(["url", "name"]));
* files[0].url || files[0].name // TS will know that this is present
* ```
*
* See https://github.com/microsoft/TypeScript/issues/16069
* why is that useful.
*/
export function hasPresentKeys<K extends string | number | symbol>(k: K[]) {
return function <T, V>(
a: T & { [k in K]?: V | null }
): a is T & { [k in K]: V } {
for (let i = 0; i < k.length; i++) {
if (a[k[i]] === undefined || a[k[i]] === null) {
return false;
}
}
return true;
};
}

/**
* Returns a function that can be used to filter down objects
* to the ones that have a specific value V under a key `k`.
Expand Down