Skip to content

Commit

Permalink
types: type safer implementation and more accurate inference of retur…
Browse files Browse the repository at this point in the history
…n value type for `shake`
  • Loading branch information
AliubYiero committed May 5, 2024
1 parent 069b26c commit aeee6af
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 18 deletions.
6 changes: 2 additions & 4 deletions cdn/radash.esm.js
Original file line number Diff line number Diff line change
Expand Up @@ -620,12 +620,10 @@ const shake = (obj, filter = (x) => x === void 0) => {
return {};
const keys2 = Object.keys(obj);
return keys2.reduce((acc, key) => {
if (filter(obj[key])) {
return acc;
} else {
if (!filter(obj[key])) {
acc[key] = obj[key];
return acc;
}
return acc;
}, {});
};
const mapKeys = (obj, mapFunc) => {
Expand Down
6 changes: 2 additions & 4 deletions cdn/radash.js
Original file line number Diff line number Diff line change
Expand Up @@ -623,12 +623,10 @@ var radash = (function (exports) {
return {};
const keys2 = Object.keys(obj);
return keys2.reduce((acc, key) => {
if (filter(obj[key])) {
return acc;
} else {
if (!filter(obj[key])) {
acc[key] = obj[key];
return acc;
}
return acc;
}, {});
};
const mapKeys = (obj, mapFunc) => {
Expand Down
2 changes: 1 addition & 1 deletion cdn/radash.min.js

Large diffs are not rendered by default.

23 changes: 15 additions & 8 deletions src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,30 @@ type UppercasedKeys<T extends Record<string, any>> = {
}

/**
* Removes (shakes out) undefined entries from an
* object. Optional second argument shakes out values
* Removes (shakes out) undefined entries from an object.
* Optional second argument shakes out values
* by custom evaluation.
*
* @example use generics
* let obj = {a: 1, b: 2};
* shake<typeof obj, 'a'>(obj, (item) => item < 2);
* // --> { b: 2 }
*
* @example default using
* shake({a: 1, b: 2, c: undefined})
* // --> {a: 1, b: 2}
*/
export const shake = <RemovedKeys extends string, T>(
export const shake = <T extends Object, RemovedKeys extends keyof T>(
obj: T,
filter: (value: any) => boolean = x => x === undefined
filter: (value: T[keyof T]) => boolean = x => x === undefined
): Omit<T, RemovedKeys> => {
if (!obj) return {} as T
const keys = Object.keys(obj) as (keyof T)[]
return keys.reduce((acc, key) => {
if (filter(obj[key])) {
return acc
} else {
if (!filter(obj[key])) {
acc[key] = obj[key]
return acc
}
return acc
}, {} as T)
}

Expand Down
2 changes: 1 addition & 1 deletion src/tests/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe('object module', () => {
})
})
test('handles undefined input', () => {
const result = _.shake(undefined)
const result = _.shake(undefined as unknown as Object)
assert.deepEqual(result, {})
})
})
Expand Down

0 comments on commit aeee6af

Please sign in to comment.