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

Add isomorphics/oneOf #42

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
1 change: 1 addition & 0 deletions src/isomorphics/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as entries } from './entries';
export { default as isIterable } from './isIterable';
export { default as oneOf } from './oneOf';
17 changes: 17 additions & 0 deletions src/isomorphics/oneOf/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Validate that the given data type exists as a primitive value in the given Array/Object/Enum shape
*/
const oneOf = (data: unknown, shape: Array<any> | Record<any, any>) => {
if (!shape || typeof shape !== 'object') {
throw new TypeError('You need to provide a shape to validate to oneOf');
}

if (Array.isArray(shape)) {
return shape.some(s => s === data);
}

// @ts-ignore
return Object.values(shape).some(s => s === data);
};

export default oneOf;
20 changes: 20 additions & 0 deletions src/isomorphics/oneOf/oneOf.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import oneOf from '.';

describe(`[Isomorphics]: oneOf`, () => {
it(`should return true if the given data occurs in the provided shape`, () => {
expect(oneOf(3, [1, 2, 3])).toBe(true);
expect(oneOf(`string`, [`string`, `s`, `[Object object]`])).toBe(true);
});

it(`should return false if the given data does not occur in the provided shape`, () => {
expect(oneOf(undefined, [1, 2, 3])).toBe(false);
expect(oneOf(null, [`string`, `s`, `[Object object]`])).toBe(false);
expect(oneOf(() => {}, [{}, `s`, `[Object object]`])).toBe(false);
expect(oneOf({}, [3, `s`, `[Object object]`])).toBe(false);
});

it(`should throw a TypeError if no shape is provided`, () => {
expect(() => oneOf(3)).toThrowError(TypeError);
expect(() => oneOf(3, function() {})).toThrowError(TypeError);
});
});