UNPKG

@cloudpss/template

Version:

Lightweight string and object templating utilities with interpolation and formula support.

51 lines (43 loc) 1.69 kB
/** 是否为 ArrayBuffer */ export let isArrayBuffer: (value: object) => value is ArrayBuffer | SharedArrayBuffer; /** 是否为 Error */ export let isError: (value: unknown) => value is Error; declare global { /** @inheritdoc */ interface ErrorConstructor { /** @inheritdoc */ isError?(this: void, value: unknown): value is Error; } } if (typeof Error.isError == 'function') { isError = Error.isError; } if (typeof process == 'object' && typeof process.getBuiltinModule == 'function') { const typeUtils = process.getBuiltinModule('node:util/types'); isArrayBuffer = typeUtils.isAnyArrayBuffer; isError = typeUtils.isNativeError; } isError ??= (value: unknown): value is Error => { return value instanceof Error; }; isArrayBuffer ??= (value: object): value is ArrayBuffer | SharedArrayBuffer => { const tag = toString(value); return tag === '[object ArrayBuffer]' || tag === '[object SharedArrayBuffer]'; }; /** * Object.prototype.toString.call 的快捷方式 */ // eslint-disable-next-line @typescript-eslint/unbound-method export const toString = Function.call.bind(Object.prototype.toString) as (value: unknown) => string; export const { hasOwn } = Object; export const { isArray } = Array; export const isArrayBufferView = ArrayBuffer.isView.bind(ArrayBuffer); export const { stringify } = JSON; /** * 获取 ArrayBuffer 的拷贝 */ export function copyArrayBuffer(buffer: ArrayBuffer | SharedArrayBuffer, start: number, length?: number): ArrayBuffer { const copy = new ArrayBuffer(length ?? buffer.byteLength - start); new Uint8Array(copy).set(new Uint8Array(buffer, start, length)); return copy; }