import _ from 'lodash'; import jsonpack from 'jsonpack'; import merge from 'deepmerge'; import basex from 'base-x'; class JBase62 { static #instance = null static getInstance = (characters = null) => { if (characters || !JBase62.#instance) { JBase62.#instance = new JBase62(characters) } return JBase62.#instance } #basex = null constructor(characters = "") { if (!characters && !JBase62.#instance) { throw new "characters is required" } if (characters) { this.#basex = basex(characters) } else if (JBase62.#instance) { return JBase62.#instance } } encode = (json = {}) => { const jsonString = JSON.stringify(json, (__, v) => v === undefined ? null : v) const binaryString = jsonpack.pack(jsonString) return this.#basex.encode(Buffer.from(binaryString)) } decode = (base62 = '', defaultValue = {}) => { if (base62 === undefined || base62 === '') { return defaultValue } try { const binaryString = this.#basex.decode(base62).reduce((carry, bin) => carry + String.fromCharCode(bin), "") const jsonString = jsonpack.unpack(binaryString) return typeof (jsonString) === 'string' ? JSON.parse(jsonString) : jsonString } catch (e) { console.warn('JBase62.decode', e) return defaultValue } } get = (base62, path, defaultValue) => _.get(this.decode(base62), path, defaultValue) set = (base62, path, value) => { const obj = this.decode(base62) _.set(obj, path, value) return this.encode(obj) } assign = (base62, data = {}, isDeepMerge = false) => this.encode(isDeepMerge ? merge(this.decode(base62), data) : Object.assign(this.decode(base62), data)) } export default JBase62