Skip to content

Commit

Permalink
feat(bind): add support for undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
ASafaeirad committed Jun 14, 2024
1 parent 643e9fd commit 917e5f5
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
5 changes: 3 additions & 2 deletions docs/pages/nullable/bind.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import { bind } from '@fullstacksjs/toolbox';
### Signature

```typescript copy
function bind<T, U>(x: Nullable<T>, ...fns: Function[]): U {}
function bind<T, U>(x: Nullable<T>, ...fns: Function[]): Nullable<U> {}
```

### Examples

```typescript copy
bind(null,f) // null
bind(undefined, f) // undefined
bind(null, f) // null
bind(1, f) // f(1)
bind(2, f, g, h) // h(g(f(2)))
bind(null, f, g, h, j) // null
Expand Down
4 changes: 4 additions & 0 deletions src/nullable/bind.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ describe('bind', () => {
expect(bind(null, f, g, h, j, k)).eq(null);
});

it('should return undefined if first arg is undefined', () => {
expect(bind(undefined, f, g, h, j, k)).eq(undefined);
});

it('should return null if any composed function returned null', () => {
expect(bind('normal', f, g, getNull, h, j)).eq(null);
});
Expand Down
5 changes: 3 additions & 2 deletions src/nullable/bind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ import type { Nullable } from '../types';
*
* @example
*
* bind(undefined ,f) // undefined
* bind(null,f) // null
* bind(1, f) // f(1)
* bind(2, f, g, h) // h(g(f(2)))
* bind(null, f, g, h, j) // null
*/
export function bind(x: null, ...fns: any[]): null;
export function bind(x: Nullable, ...fns: any[]): Nullable;
export function bind<A, B>(
x: Nullable<A>,
f: (x: A) => Nullable<B>,
Expand Down Expand Up @@ -58,5 +59,5 @@ export function bind<A, B, C, D, E, F, G>(
l: (x: F) => Nullable<G>,
): Nullable<G>;
export function bind<A>(x: Nullable<A>, ...fns: any[]) {
return fns.reduce((v, f) => (v === null ? null : f(v)), x);
return fns.reduce((v, f) => (v == null ? v : f(v)), x);
}

0 comments on commit 917e5f5

Please sign in to comment.