UNPKG

mihawk

Version:

A tiny & simple mock server tool, support json,js,cjs,ts(typescript).

79 lines (78 loc) 2.23 kB
'use strict'; import * as JSON5 from 'json5'; export function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } export function isType(obj, typeName) { return getType(obj) === typeName?.toLowerCase(); } export function isNil(value) { return value === null || value === undefined; } export const isNullOrUndefined = isNil; export const isUndefinedOrNull = isNil; export function isPrimitvieType(obj) { const type = getType(obj); return ['bigint', 'boolean', 'null', 'number', 'string', 'symbol', 'undefined'].includes(type); } export function isSimpleJsonPropType(obj) { const type = getType(obj); if (['null', 'string', 'boolean', 'number'].includes(type)) { return true; } return false; } export function isNumStrict(n) { return !isNaNStrict(n) && isType(n, 'number'); } export function isNaNStrict(obj) { return obj !== obj; } export function isObjStrict(obj) { if (isNil(obj)) return false; if (typeof obj === 'object') { if (Array.isArray(obj)) { return false; } else if (obj instanceof RegExp || obj instanceof Date || obj instanceof Error) { return false; } else if (obj instanceof Map || obj instanceof Set || obj instanceof WeakMap || obj instanceof WeakSet) { return false; } else if (obj instanceof Uint8Array || obj instanceof Uint16Array || obj instanceof Uint32Array) { return false; } else { return isType(obj, 'object'); } } return false; } export function isEmptyObj(obj) { if (isObjStrict(obj)) { return !Object.keys(obj)?.length; } return false; } export function isEmptyArr(arr) { if (Array.isArray(arr)) { return !arr.length; } return false; } export const isEmptyList = isEmptyArr; export function isJsonStr(jsonStr, isJson5 = false) { let isValidJsonCnt = false; try { isValidJsonCnt = JSON.parse(jsonStr); if (!isValidJsonCnt && isJson5) { isValidJsonCnt = JSON5.parse(jsonStr); } } catch (e) { isValidJsonCnt = false; } return isValidJsonCnt; }