UNPKG

json-processing

Version:

JSON Processing Tool

60 lines (59 loc) 2.02 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.human = exports.parse = void 0; const lodash_1 = __importDefault(require("lodash")); const filesize_1 = __importDefault(require("filesize")); function parse(...fields) { return (input) => process(input, fields, (value) => { try { const match = /^([-0-9.]+)\s*([a-zA-Z]+)$/.exec(value); if (match === null || match.length < 3) return value; else return +match[1] * multiplier(match[2]); } catch (e) { return value; } }); } exports.parse = parse; function human(...fields) { return (input) => process(input, fields, (value) => { try { return filesize_1.default(+value); } catch (e) { return value; } }); } exports.human = human; function process(input, fields, onEntry) { if ((lodash_1.default.isEmpty(input) && !lodash_1.default.isNumber(input)) || lodash_1.default.isBoolean(input)) return input; if (lodash_1.default.isArray(input)) return input.map((input) => process(input, fields, onEntry)); if (lodash_1.default.isObject(input)) { const _input = input; fields = lodash_1.default.isEmpty(fields) ? Object.keys(input) : fields; fields.forEach((field) => _input[field] = onEntry(_input[field])); return input; } return onEntry(input); } function multiplier(value) { switch (value.trim().toLowerCase()) { case 'b': return 1; case 'kb': return 1024; case 'mb': return Math.pow(1024, 2); case 'gb': return Math.pow(1024, 3); case 'tb': return Math.pow(1024, 4); case 'pb': return Math.pow(1024, 5); case 'eb': return Math.pow(1024, 6); default: return Number.NaN; } }