Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types): argument type and response type will be the same #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,37 @@
* @module
*/

export type JsonValue = number | string | boolean | null | JsonValue[] | { [key: string]: JsonValue };
export type JsonPrimitive = number | string | boolean | null;
export type JsonArray = JsonValue[];
export type JsonObject = { [key: string]: JsonValue };

/**
* This function clones the given JSON value.
*
* @param value The JSON value to be cloned. There are two invariants. 1) It must not contain circles
* as JSON does not allow it. This function will cause infinite loop for such values by
* design. 2) It must contain JSON values only. Other values like `Date`, `Regexp`, `Map`,
* `Set`, `Buffer`, ... are not allowed.
* @returns The cloned JSON value.
*/
export default function cloneJSON(value: JsonValue): JsonValue {
export type JsonValue = JsonPrimitive | JsonArray | JsonObject;

function _cloneJSON(value: JsonValue): JsonValue {
if (typeof value !== 'object' || value === null) {
return value;
} else if (Array.isArray(value)) {
return value.map(e => (typeof e !== 'object' || e === null ? e : cloneJSON(e)));
} else {
const ret: { [key: string]: JsonValue } = {};
const ret: JsonObject = {};
for (const k in value) {
const v = value[k];
ret[k] = typeof v !== 'object' || v === null ? v : cloneJSON(v);
}
return ret;
}
}

/**
* This function clones the given JSON value.
*
* @param value The JSON value to be cloned. There are two invariants. 1) It must not contain circles
* as JSON does not allow it. This function will cause infinite loop for such values by
* design. 2) It must contain JSON values only. Other values like `Date`, `Regexp`, `Map`,
* `Set`, `Buffer`, ... are not allowed.
* @returns The cloned JSON value.
*/
function cloneJSON<V extends JsonValue>(value: V): V {
// note: autoregressive function
return _cloneJSON(value) as V
}