Skip to content

Commit

Permalink
feat: Make isEmpty a type guard (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
crgwbr committed Jul 23, 2024
1 parent ebf2823 commit 390571a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/utils/is-arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ import { getTagString } from './get-tag-string';
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
* @returns `true` if `o` is a function's array-like `arguments` variable
*/
export function isArguments(o: any): boolean {
export function isArguments(o: any): o is IArguments {
return getTagString(o) === '[object Arguments]';
}
31 changes: 28 additions & 3 deletions src/utils/is-empty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,32 @@ import { isArray } from './is-array';
import { isString } from './is-string';
import { isArguments } from './is-arguments';
import { isUndefined } from './is-undefined';
import { isNull } from './is-null';
import { isBoolean } from './is-boolean';
import { isNumber } from './is-number';
import { isSet } from './is-set';
import { isObject } from './is-object';


interface IEmptyArguments extends IArguments {
length: 0;
}

interface IEmptyObj {
[s: string]: never;
}

type IEmptyTypes = (
null |
undefined |
boolean |
number |
never[] |
'' |
IEmptyArguments |
Set<never> |
IEmptyObj
);

/**
* Checks if `o` is an empty object. An object is "empty" if it:
Expand All @@ -13,8 +38,8 @@ import { isSet } from './is-set';
*
* @returns `true` if `o` is empty
*/
export function isEmpty(o: any): boolean {
if (o === null || isUndefined(o)) {
export function isEmpty(o: unknown): o is IEmptyTypes {
if (isNull(o) || isUndefined(o) || isBoolean(o) || isNumber(o)) {
return true;
}
if (isArray(o) || isString(o) || isArguments(o)) {
Expand All @@ -23,5 +48,5 @@ export function isEmpty(o: any): boolean {
if (isSet(o)) {
return o.size === 0;
}
return Object.keys(o).length === 0;
return isObject(o) && Object.keys(o).length === 0;
}

0 comments on commit 390571a

Please sign in to comment.