Skip to content

Commit

Permalink
feat: add atValue util to assist on new confirm, prompt, select api
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Jul 5, 2024
1 parent 1e83846 commit 6e79ea0
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/helpers/safe-serialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { type Serial, TypeGuard } from 'type-core';

export function safeSerialize(value: any): string {
if (TypeGuard.isUndefined(value) || TypeGuard.isString(value)) {
return String(value);
} else {
return JSON.stringify(walk(value));
}
}

function walk(value: any): Serial.Type {
if (
TypeGuard.isNullish(value) ||
TypeGuard.isBoolean(value) ||
TypeGuard.isString(value) ||
TypeGuard.isNumber(value)
) {
return value;
}

if (
TypeGuard.isArray(value) &&
Object.getPrototypeOf(value) === Array.prototype
) {
return value.map((item) => walk(item));
}

if (
TypeGuard.isRecord(value) &&
Object.getPrototypeOf(value) === Object.prototype
) {
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [key, walk(item)])
);
}

throw new Error(`Non serializable value: ${value}`);
}
20 changes: 20 additions & 0 deletions src/utils/at-value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { Dictionary, Serial } from 'type-core';

import type { Task } from '../definitions';
import { safeSerialize } from '../helpers/safe-serialize';

/**
* Takes a `tasks` record of `Task`s and returns a function
* that will return the `Task` of the record that matches the
* serialization of `value`; otherwise `null`.
* Particularly useful for stdio tasks such as
* confirm, prompt, and select.
*/
export function atValue(
tasks: Dictionary<Task>
): (value: Serial.Type) => Task | null {
return (value) => {
const field = safeSerialize(value);
return Object.hasOwnProperty.call(tasks, field) ? tasks[field] : null;
};
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './at-value';
export * from './cancellation';
export * from './fetch';
export * from './is-ci';
Expand Down

0 comments on commit 6e79ea0

Please sign in to comment.