Skip to content

Commit

Permalink
fix: handle falsy arg and types improve
Browse files Browse the repository at this point in the history
  • Loading branch information
rohmanhm committed Feb 14, 2021
1 parent 7a390c3 commit 70db74e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 16 deletions.
23 changes: 10 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type OxReturn<ObjectType> = RemoveIgnoredKey<ObjectType>;

const toStr = Object.prototype.toString;

function _ox<T extends Obj>(obj: T, strict: boolean): OxReturn<T> {
function cleanObject<T extends Obj>(obj: T, strict: boolean): OxReturn<T> {
let k: string;
for (k in obj) {
cleanProperty(k, obj[k], obj);
Expand Down Expand Up @@ -43,7 +43,7 @@ function _ox<T extends Obj>(obj: T, strict: boolean): OxReturn<T> {
if (toStr.call(obj[k]) === '[object Array]') {
ref[key] = ref[key].filter(shouldCleanProperty);
} else {
_ox(ref[key], strict);
cleanObject(ref[key], strict);
}

if (isEmpty(ref[key])) {
Expand All @@ -57,18 +57,15 @@ function _ox<T extends Obj>(obj: T, strict: boolean): OxReturn<T> {
}
}

export default function ox<T extends Obj>(
obj: T,
strict?: boolean
): OxReturn<T> {
strict = typeof strict === 'undefined' ? true : strict;
let newObj = _ox(obj, strict);

if (newObj === null) {
newObj = {} as any;
export default function ox<T, U extends boolean>(
obj?: T,
strict?: U
): T extends Obj ? (U extends false ? T : OxReturn<T>) : T {
if (typeof strict === 'undefined') {
strict = true as U;
}

return newObj;
if (!obj || typeof obj === 'boolean') return {} as any;
return cleanObject(obj as Obj, strict as boolean) ?? ({} as any);
}

export { isEmpty };
4 changes: 1 addition & 3 deletions src/isEmpty.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
const hasOwnProp = Object.prototype.hasOwnProperty;

export function isEmpty<ObjectType extends { [key: string]: unknown }>(
obj: ObjectType
) {
export function isEmpty<T extends { [key: string]: unknown }>(obj: T) {
// Check if obj has .length property
// and if === 0 - it's empty
if (obj.length) {
Expand Down
17 changes: 17 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,20 @@ test('disable strict mode not remove falsy key value', () => {

expect(actual).toEqual(expected);
});

test('handle falsy argument value', () => {
const expected = {};
let actual = ox();
expect(actual).toEqual(expected);

actual = ox(false);
expect(actual).toEqual(expected);

let active = false;
actual = ox(active && { lorem: 'ipsum' });
expect(actual).toEqual(expected);

active = true;
actual = ox(active && { lorem: 'ipsum' });
expect(actual).toEqual({ lorem: 'ipsum' });
});

0 comments on commit 70db74e

Please sign in to comment.