Skip to content

Commit

Permalink
feature/add-new-null-if-empty-function
Browse files Browse the repository at this point in the history
  • Loading branch information
= authored and Zlaylink committed May 17, 2024
1 parent cbbac5c commit c3a6f92
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
55 changes: 55 additions & 0 deletions packages/common/src/null-if-empty.function.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { nullIfEmpty } from './null-if-empty.function';

describe('null-if-empty.function.ts', () => {
it('should be true if argument is null', () => {
expect(nullIfEmpty(null)).toBe(null);
});

it('should be true if argument is undefined', () => {
expect(nullIfEmpty(undefined)).toBe(null);
});

it('should be true if argument is empty string', () => {
expect(nullIfEmpty('')).toBe(null);
});

it('should be true if argument is empty array', () => {
expect(nullIfEmpty([])).toBe(null);
});

it('should be true if argument is empty object', () => {
expect(nullIfEmpty({})).toBe(null);
});

it('should be false if argument is boolean value', () => {
expect(nullIfEmpty(false)).toBe(false);
});

it('should be false if argument is non-empty string', () => {
expect(nullIfEmpty('Hello')).toEqual('Hello');
});

it('should be equals input if argument is non-empty array', () => {
expect(nullIfEmpty([1, 2, 3])).toEqual([1, 2, 3]);
});

it('should be equals input if argument is non-empty object', () => {
expect(nullIfEmpty({ key: 'value' })).toEqual({ key: 'value' });
});

it('should be equals input if argument is number', () => {
expect(nullIfEmpty(42)).toBe(42);
});

it('should be equals input if argument is boolean true', () => {
expect(nullIfEmpty(true)).toBe(true);
});

it('should be true if argument is an empty Set', () => {
expect(nullIfEmpty(new Set())).toBe(null);
});

it('should be true if argument is an empty Map', () => {
expect(nullIfEmpty(new Map())).toBe(null);
});
});
5 changes: 5 additions & 0 deletions packages/common/src/null-if-empty.function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { isEmpty } from './is-empty.function';

export function nullIfEmpty<T>(value: T): T | null {
return isEmpty(value) ? null : value;
}

0 comments on commit c3a6f92

Please sign in to comment.