UNPKG

@clynn-fe/akfe-editor-jsonc

Version:

JSON Compress by using a map to reduce the size of keys and using gzip

76 lines (71 loc) 1.94 kB
export const unique = <T>(arr: T[]) => [...new Set(arr)] export const isObject = (obj: any) => toString.call(obj) === '[object Object]' /** * Converts a bidimensional array to object */ export const biDimensionalArrayToObject = <T>( arr: [string | number, T][] ): { [key: string]: T; [key: number]: T } => arr.reduce( (prev, [key, value]) => Object.assign(prev, { [key]: value }), {} ) /** * Convert a number to their ascii code/s. */ export const numberToKey = ( index: number, totalChar?: number, offset?: number ) => { const sKeys = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' const aArr: number[] = [] let currentChar = index totalChar = totalChar || sKeys.length offset = offset || 0 while (currentChar >= totalChar) { aArr.push(sKeys.charCodeAt((currentChar % totalChar) + offset)) currentChar = Math.floor(currentChar / totalChar - 1) } aArr.push(sKeys.charCodeAt(currentChar + offset)) return aArr.reverse() } /** * 使用给定的 map oKeys 来替换 obj 里的 key * 该方法不改变传入的 obj */ export const transformKeys = ( obj: any, oKeys: { [key: string]: string }, target = {} ): any => { if (Array.isArray(obj)) { return obj.map(item => transformKeys(item, oKeys)) } else if (isObject(obj)) { Object.entries(obj).forEach(([key, value]) => { const newKey = oKeys[key] /* c8 ignore next */ ?? key switch (true) { case Array.isArray(value): Object.assign(target, { [newKey]: (value as []).map(item => transformKeys(item, oKeys)) }) break case isObject(value): Object.assign(target, { [newKey]: transformKeys(value, oKeys) }) break default: Object.assign(target, { [newKey]: value }) } }) return target } else { return obj } }