Skip to content

Commit

Permalink
feat: isTruthy helper
Browse files Browse the repository at this point in the history
  • Loading branch information
hmerritt committed Jul 12, 2024
1 parent b8cced2 commit ada63f9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 17 deletions.
2 changes: 1 addition & 1 deletion scripts/bootstrap/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as core from "./core";
/**
* Internal adrift version.
*/
export const adriftVersion = "0.11.510";
export const adriftVersion = "0.11.512";

/**
* Bumps the adrift `patch` version number using the total commit count.
Expand Down
2 changes: 0 additions & 2 deletions src/lib/type-assertions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const getKeys = Object.keys as <T extends object>(obj: T) => Array<keyof T>;

/**
* Deep `keyof` of a nested object. INCLUDES root key as well as all nested.
*
Expand Down
48 changes: 34 additions & 14 deletions src/lib/type-guards.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,48 @@
export const isObj = (v: unknown): v is Record<string, unknown> => {
return !!v && typeof v === "object";
};

export const hasProp = <K extends PropertyKey>(
data: object,
prop: K
): data is Record<K, unknown> => {
return prop in data;
};

/**
* Helper to conditionally spread an item into an array.
* Conditionally spread an item into an array.
*/
export const arraySpread = <TItem>(
/** Conditional value. When truthy, `itemToSpread` is returned. */
isTruthy: any,
conditional: any,
/** Item that gets returned when conditional is truthy */
itemToSpread: TItem | TItem[],
/** Option to spread multiple values when `itemToSpread` is an array */
spreadMultiple = false
) => {
if (isTruthy)
if (isTruthy(conditional))
return spreadMultiple && Array.isArray(itemToSpread)
? (itemToSpread as TItem[])
: [itemToSpread as TItem];
return [] as TItem[];
};

export const hasProp = <K extends PropertyKey>(
data: object,
prop: K
): data is Record<K, unknown> => {
return prop in data;
};

export const isObj = (v: unknown): v is Record<string, unknown> => {
return !!v && typeof v === "object";
};

/**
* @returns `true` when all supplied values are NOT any of the bellow:
* - Is falsy
* - Is empty array
* - Is empty object
*/
export const isTruthy = (...v: any[]) => {
for (let i = 0; i < v.length; i++) {
if (
!v[i] ||
(Array.isArray(v[i]) && v[i]?.length === 0) ||
(isObj(v[i]) && Object.keys(v[i] ?? {})?.length === 0)
)
return false;
}
return true;
};

export const objKeys = Object.keys as <T extends object>(obj: T) => Array<keyof T>;

0 comments on commit ada63f9

Please sign in to comment.