UNPKG

@pefish/js-node-assist

Version:
770 lines 22.6 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Calculator = exports.RoundingMode = void 0; const bignumber_js_1 = __importDefault(require("bignumber.js")); const array_1 = __importDefault(require("./array")); const buffer_1 = __importDefault(require("./buffer")); // 进制计算的结果都要带上相应前缀 二进制0b 八进制0o 十六进制0x var RoundingMode; (function (RoundingMode) { RoundingMode[RoundingMode["ROUND_UP"] = 0] = "ROUND_UP"; RoundingMode[RoundingMode["ROUND_DOWN"] = 1] = "ROUND_DOWN"; RoundingMode[RoundingMode["ROUND_CEIL"] = 2] = "ROUND_CEIL"; RoundingMode[RoundingMode["ROUND_FLOOR"] = 3] = "ROUND_FLOOR"; RoundingMode[RoundingMode["ROUND_HALFUP"] = 4] = "ROUND_HALFUP"; RoundingMode[RoundingMode["ROUND_HALFDOWN"] = 5] = "ROUND_HALFDOWN"; RoundingMode[RoundingMode["ROUND_HALFEVEN"] = 6] = "ROUND_HALFEVEN"; RoundingMode[RoundingMode["ROUND_HALFCEIL"] = 7] = "ROUND_HALFCEIL"; RoundingMode[RoundingMode["ROUND_HALFFLOOR"] = 8] = "ROUND_HALFFLOOR"; RoundingMode[RoundingMode["EUCLID"] = 9] = "EUCLID"; })(RoundingMode || (exports.RoundingMode = RoundingMode = {})); class Calculator { constructor(data = `0`) { this.data = data.toString(); } toString() { return this.data; } /** * 加 * @param val * @returns {any} */ add(val) { val = val.toString(); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.plus(val)); } /** * 乘以10的几次方 * @param num */ shiftedBy(num) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.shiftedBy(new Calculator(num.toString()).toNumber())); } unShiftedBy(num) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.shiftedBy(new Calculator(num.toString()).negated().toNumber())); } /** * 取相反数 * @returns {string} */ negated() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.negated()); } /** * 减 * @param val * @returns {any} */ sub(val) { val = val.toString(); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.minus(val).toString()); } /** * 乘 * @param val * @returns {any} */ multi(val) { val = val.toString(); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.times(val).toString()); } /** * 乘方 * @param val * @returns {any} */ pow(val) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.exponentiatedBy(new Calculator(val.toString()).toNumber()).toString()); } /** * 除 * @param val * @returns {string} */ div(val) { val = val.toString(); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.div(val).toString()); } /** * 求余 * @param val * @returns {string} */ mod(val) { val = val.toString(); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.mod(val).toString()); } /** * 开根号 * @returns {string} */ sqrt() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); return new Calculator(num1.sqrt().toString()); } /** * 是否大于 * @param val * @returns {boolean} */ gt(val) { val = val.toString(); const num1 = new bignumber_js_1.default(this.data); return num1.comparedTo(val) === 1; } /** * 大于或等于 * @param val * @returns {boolean} */ gte(val) { val = val.toString(); const num1 = new bignumber_js_1.default(this.data); const result = num1.comparedTo(val); return result === 1 || result === 0; } /** * 是否小于 * @param val * @returns {boolean} */ lt(val) { val = val.toString(); const num1 = new bignumber_js_1.default(this.data); return num1.comparedTo(val) === -1; } /** * 小于或等于 * @param val * @returns {boolean} */ lte(val) { val = val.toString(); const num1 = new bignumber_js_1.default(this.data); const result = num1.comparedTo(val); return result === -1 || result === 0; } /** * 是否相等 * @param val * @returns {boolean} */ eq(val) { val = val.toString(); const num1 = new bignumber_js_1.default(this.data); return num1.comparedTo(val) === 0; } /** * 保留小数点后几位。默认小数部分最后不带0 * @param decimalRemain * @param remainMethod {number} * @returns {string} */ remainDecimal(decimalRemain, remainMethod = RoundingMode.ROUND_HALFUP, withZero = false) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(this.data); let result = num1.toFixed(decimalRemain, remainMethod); if (result.indexOf(".") !== -1 && withZero === false) { // 是小数 while (true) { const temp = StringUtil.removeLastStr(result, "0"); if (result === temp) { // 说明上面无0可去了 if (result.endsWith(".")) { result = result.substr(0, result.length - 1); } return new Calculator(result); } result = temp; } } return new Calculator(result); } /** * 取绝对值 * @returns {string} */ abs() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return new Calculator(num.abs()); } /** * 直接取整 * @returns {Number} */ toInt() { return parseInt(this.data); } /** * 转换为数值 * @returns {Number} */ toNumber() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return num.toNumber(); } /** * 转换成BigNumber对象 * @returns {BigNumber} */ toBigNumber() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); return new BN(this.data); } /** * 转换成 BigInt 对象 * @returns {BigInt} */ toBigInt() { return BigInt(this.data); } /** * 转换为二进制字符串 * @returns {string} */ toBinString() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return new Calculator("0b" + num.toString(2)); } /** * 转换为八进制字符串 * @returns {string} */ toOctString() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return new Calculator("0o" + num.toString(8)); } /** * 转十进制字符串 * @returns {number} */ toDecimalString() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return new Calculator(num.toString(10)); } /** * 转换为十六进制字符串 * @returns {string} */ toHexString() { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(this.data); return new Calculator("0x" + num.toString(16)); } end() { return this.data; } } exports.Calculator = Calculator; class StringUtil { // 支持"0x12"这种十六进制字串 static start(data) { canCastBigNumber(data); return new Calculator(data); } // 字符串处理 /** * 移除开头几位字符串 * @param num * @returns {Array} */ static removeFirst(src, num) { return src.substring(num, src.length); } /** * 获取小数部分的个数 */ static decimalCount(src) { canCastBigNumber(src); return src.split(".")[1].length; } /** * 加千分号 * @returns {string} */ static addThousandSign(src) { canCastBigNumber(src); const parts = src.split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts[1] === "" ? parts[0] : parts.join("."); } /** * 移除千分号 * @returns {string} */ static removeThousandSign(src) { canCastBigNumber(src); return src.replace(new RegExp(",", "g"), ""); } /** * hex string转换为number * @returns {number} */ static hexToNumber(src) { let temp = src; if (!temp.startsWith("0x")) { temp = "0x" + temp; } canCastBigNumber(temp); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(temp); return num.toNumber(); } /** * '190' --> 'BE' * @returns {string} */ static numberStrToHex(src) { const number = new Calculator(src).toNumber(); return number.toString(16).toUpperCase(); } /** * '190' --> 190 * @returns {string} */ static numberStrToNumber(src) { return new Calculator(src).toNumber(); } /** * 判断此值用于计算时是否具有精度问题 */ static hasPrecisionIssue(src) { canCastBigNumber(src); return new Calculator(src).gt("9007199254740992"); } /** * 移除最后几位字符串 * @param num * @returns {string} */ static removeLast(src, num) { return src.substring(0, src.length - num); } /** * 获取开头几位 * @param num * @returns {string} */ static getFirst(src, num) { return src.substring(0, num); } /** * 获取最后几位 * @param num * @returns {string} */ static getLast(src, num) { return src.substring(src.length - num, src.length); } /** * 全部替换(只能简单替换字符串) * @param regStr * @param replaceStr * @returns {string} */ static replaceAll(src, regStr, replaceStr) { return src.replace(new RegExp(regStr, "gm"), replaceStr); } /** * 从字符串中分类出指定区间的内容 * @param splitStr1 * @param splitStr2 * @returns {{}} */ static classify(src, splitStr1, splitStr2) { const results = []; const regStr = `${splitStr1}(.*?)${splitStr2}`; const targets = this.findAll(src, regStr); for (let i = 0; i < targets.length; i++) { if (i === 0) { results.push({ name: src.substring(0, targets[i].index), is: false, index: results.length, }); } else { results.push({ name: src.substring(targets[i - 1].index + targets[i - 1].outputFull.length, targets[i].index), is: false, index: results.length, }); } results.push({ name: targets[i]["output"], is: true, index: results.length, }); if (i === targets.length - 1) { results.push({ name: src.substring(targets[i]["index"] + targets[i]["outputFull"].length, src.length), is: false, index: results.length, }); } } return results; } static findAll(src, regStr) { const reg = new RegExp(regStr, "g"); //作用是能够对正则表达式进行编译,被编译过的正则在使用的时候效率会更高,适合于对一个正则多次调用的情况下 let results = []; let a; while ((a = reg.exec(src))) { //数组中第0个元素是匹配的子字符串,第二个元素是正则中的第一个子分组匹配的结果(如果有子分组,即正则中存在用圆括号括起来的分组),第三个是正则中第二个子分组匹配的结果(如果有第二个子分组) results.push({ outputFull: a[0], output: a[1], index: a["index"], input: a["input"], }); } return results; } /** * 十六进制字符串转化为Buffer。与Buffer.toHexString相反 * @returns {Array} */ static hexToBuffer(src) { let temp = src; if (temp.startsWith("0x")) { temp = temp.substring(2, temp.length); } // 长度奇数前面加0 if (temp.length % 2 !== 0) { temp = "0" + temp; } return Buffer.from ? Buffer.from(temp, "hex") : new Buffer(temp, `hex`); } /** * 普通字符串转buffer * @returns {Buffer} */ static toUtf8Buffer(src) { return Buffer.from ? Buffer.from(src) : new Buffer(src); } /** * 十六进制字符串转化为十进制字符串 * @returns {number|*} */ static hexToDecimalString(src) { let temp = src; if (!temp.startsWith("0x")) { temp = "0x" + temp; } canCastBigNumber(temp); const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num = new BN(temp); return num.toString(10); } /** * 检查是否是严格的hex数据 * @returns {boolean} */ static isStrictHexString(src) { return /^(-)?0x[0-9a-f]*$/i.test(src); } /** * 清空hex字符串左边或右边的00 * @param typeStr {string} left/right/both * @returns {string | void | *} 结果不带0x */ static clearHexZeroZero(src, typeStr) { let hex = src.replace(/^0x/i, ""); if (typeStr === "left") { hex = hex.replace(/^(?:00)*/, ""); } else if (typeStr === "right") { hex = hex.split("").reverse().join(""); hex = hex.replace(/^(?:00)*/, ""); hex = hex.split("").reverse().join(""); } else if (typeStr === "both") { hex = hex.replace(/^(?:00)*/, ""); hex = hex.split("").reverse().join(""); hex = hex.replace(/^(?:00)*/, ""); hex = hex.split("").reverse().join(""); } return hex; } /** * 移除尾随的0 */ static removeTrailingZeros(src) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(parseFloat(src)); return num1.toString(); } static toArray(src, eleLen, arrLen) { if (eleLen !== undefined && arrLen === undefined) { const num = src.length % eleLen === 0 ? parseInt((src.length / eleLen).toString()) : parseInt((src.length / eleLen).toString()) + 1; const newArrays = []; for (let i = 0; i < num; i++) { const arr = src.slice(eleLen * i, eleLen * (i + 1)); if (arr.length > 0) { newArrays.push(arr); } } return newArrays; } else if (eleLen === undefined && arrLen !== undefined) { const newArrays = []; const num = parseInt((src.length / arrLen).toString()); for (let i = 0; i < arrLen; i++) { const arr = src.slice(num * i, num * (i + 1)); if (arr.length > 0) { newArrays.push(arr); } } if (num * arrLen < src.length) { newArrays[newArrays.length - 1] = newArrays[newArrays.length - 1].concat(src.slice(num * arrLen, src.length)); } return newArrays; } else { throw new Error("eleLen and arrLen must only one to be set!!"); } } static hexStrToBase64(src) { return Buffer.from(src, "hex").toString("base64"); } static base64ToHexStr(src, prefix = true) { return buffer_1.default.toHexString(Buffer.from(src, "base64"), prefix); } static strToBase64(src) { return Buffer.from(src).toString("base64"); } static base64ToStr(src) { return Buffer.from(src, "base64").toString(); } static removeLastEnter(src) { if (src.endsWith("\r\n")) { return this.removeLast(src, 2); } if (src.endsWith("\n")) { return this.removeLast(src, 1); } return src; } /** * 移除最后一段字符串 */ static removeLastStr(src, str) { if (!src.endsWith(str)) { return src; } return src.substring(0, src.length - str.length); } /** * 移除开头一段字符串 */ static removeFirstStr(src, str) { if (!src.startsWith(str)) { return src; } return src.substring(str.length, src.length); } /** * 移除字符串最后一段。 * @param str */ static removeLastByStr(src, str) { const arr = src.split(str); if (arr.length === 1) { return src; } return array_1.default.removeLastOne(arr).join(str); } static removeFirstByStr(src, str) { const arr = src.split(str); if (arr.length === 1) { return src; } return array_1.default.removeFirstOne(arr).join(str); } static toNoScientificString(src) { const BN = bignumber_js_1.default.clone({ EXPONENTIAL_AT: 1e9, }); const num1 = new BN(src); return num1.toString(); } static canCastNumber(src) { return !isNaN(Number(src)); } static utf8HexStringToString(src) { return this.hexToBuffer(src).toString("utf8"); } static toUtf8HexString(src, prefix = true) { return buffer_1.default.toHexString(this.toUtf8Buffer(src), prefix); } static toUtf8Uint8Array(src) { return new TextEncoder().encode(src); } static toPretty(src) { return format(src, "\t"); } } exports.default = StringUtil; function canCastBigNumber(value) { try { const _ = new bignumber_js_1.default(value.toString()); } catch (err) { throw new Error(`<${value}> can not cast to bignumber`); } } function format(data, indentChar, indentBase) { indentChar = indentChar ? indentChar : "\t"; indentBase = indentBase ? indentBase : ""; let formattedJSON = ""; let dataObject = undefined; try { dataObject = JSON.parse(data); } catch (Error) { throw new TypeError("data parameter is not a valid JSON string !"); } let dataIsArray = JSONtypeOf(dataObject) == "array"; let dataIsObject = JSONtypeOf(dataObject) == "object"; // OPEN if (dataIsArray) { if (data.length == 0) // Test empty array case return "[]"; formattedJSON = "["; } else if (dataIsObject) { let objectsCount = 0; for (let _ in dataObject) { objectsCount++; break; } if (objectsCount == 0) // Test empty object case return "{}"; formattedJSON = "{"; } else { return data; } // CONTENT let objectsCount = 0; let keys = Object.keys(dataObject); for (let keyID = 0; keyID < keys.length; ++keyID) { if (objectsCount > 0) formattedJSON += ","; if (dataIsArray) formattedJSON += `\n${indentBase}${indentChar}`; else formattedJSON += `\n${indentBase}${indentChar}"${keys[keyID]}": `; switch (JSONtypeOf(dataObject[keys[keyID]])) { case "array": case "object": formattedJSON += format(JSON.stringify(dataObject[keys[keyID]]), indentChar, indentBase + indentChar); break; case "number": formattedJSON += dataObject[keys[keyID]].toString(); break; case "null": formattedJSON += "null"; break; case "string": formattedJSON += `"${dataObject[keys[keyID]]}"`; break; case "boolean": formattedJSON += dataObject[keys[keyID]]; break; } objectsCount++; } // CLOSE if (dataIsArray) formattedJSON += `\n${indentBase}]`; else formattedJSON += `\n${indentBase}}`; return formattedJSON; } function JSONtypeOf(obj) { let typeOf = typeof obj; if (typeOf == "object") { if (obj === null) return "null"; if (Array.isArray(obj)) return "array"; return "object"; } return typeOf; } //# sourceMappingURL=string.js.map