UNPKG

@paydirt/fmt

Version:

String formating using commonly used standards

304 lines (287 loc) 10.7 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@paydirt/fmt"] = {})); })(this, (function (exports) { 'use strict'; function string (flag, mods, value) { var quotes = flag.toLowerCase() === 'q'; var result = String(value); if (mods.transform === '_') { result = String(value).toLowerCase(); } if (mods.transform === '^' || flag === 'S' || flag === 'Q') { result = String(value).toUpperCase(); } if (mods.padding) { result = result[mods.negative ? 'padEnd' : 'padStart'](mods.padding); } if (quotes) { return "\"".concat(escape(result), "\""); } return result; } var typeMap = new Map([ ['string', 's'], ['boolean', 't'], ['number', 'f'], ]); function object (_, mods, value) { var flag = typeMap.get(typeof value); if (flag !== undefined) { return string(flag, mods, value); } if (mods.negative) { return JSON.stringify(Object.values(value)); } return JSON.stringify(value); } function type (_, mods, value) { return string('s', mods, (typeof value === 'object' ? (Array.isArray(value) ? 'array' : 'object') : typeof value)); } function boolean (_, mods, value) { return string('s', mods, (value ? 'true' : 'false')); } function integer (_, mods, value) { var sign = (mods.sign && value >= 0) ? '+' : ''; return string('s', mods, sign + Math.floor(value).toString()); } function binary (_, mods, value) { if (typeof value === 'string') { var chars = (value.split('') .map(function (char) { return char.charCodeAt(0); })); return string('s', mods, chars.map(function (charCode) { return ((charCode >>> 0).toString(2).padStart(8, '0')); }).join(' ')); } return string('s', mods, (value >>> 0).toString(2).padStart(8, '0')); } function char (_, mods, value) { return string('s', mods, String.fromCharCode(Math.floor(value))); } function hex (flag, mods, value) { var result = ''; var as16BitHex = function (input) { var hex = ''; var len = input.length; for (var i = 0; i < len; i++) { hex += ('000' + input.charCodeAt(i).toString(16)).slice(-4); } return hex; }; switch (typeof value) { case 'number': result = value.toString(16); break; case 'string': result = as16BitHex(value); break; default: result = as16BitHex(JSON.stringify(value)); } return string(flag === 'X' ? 'S' : 's', mods, result); } function float (_, mods, value) { var result = String(value); var sign = (mods.sign && value >= 0) ? '+' : ''; if (mods.precision) { result = value.toFixed(mods.precision); } return string('s', mods, sign + result); } var flagMap = new Map([ ['v', object], ['T', type], ['t', boolean], ['d', integer], ['b', binary], ['c', char], ['X', hex], ['x', hex], ['f', float], ['Q', string], ['q', string], ['S', string], ['s', string] ]); function sprintf(format) { var a = []; for (var _i = 1; _i < arguments.length; _i++) { a[_i - 1] = arguments[_i]; } var i = -1; return format.replace(/(%%)|(?:%(?:(\+)?([\^_])?(\-)?(\d+)?(?:\.(\d+))?)?([vdsfbecxtq]))/gi, function (_, literal, sign, transform, negative, padding, precision, flag) { if (literal) { return '%'; } var mods = { sign: Boolean(sign), transform: transform, negative: Boolean(negative), padding: parseInt(padding, 10), precision: parseInt(precision, 10) }; var method = flagMap.get(flag); if (method) { return method(flag, mods, a[++i]); } throw new SyntaxError("Unrecognized flag \"".concat(flag, "\".")); }); } var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; function printf(format) { var a = []; for (var _i = 1; _i < arguments.length; _i++) { a[_i - 1] = arguments[_i]; } if (process) { return process.stdout.write(sprintf.apply(void 0, __spreadArray([format], a, false))); } return console.log(sprintf.apply(void 0, __spreadArray([format], a, false))); } var HEAVY = [ '┏━┳┓', '┃ ┃┃', '┣━╋┫', '┃ ┃┃', '┗━┻┛' ].join(''); var DEFAULT = [ '┏━┳┓', '┃ ┃┃', '┡━╇┩', '│ ││', '└─┴┘' ].join(''); var THIN = [ '┌─┬┐', '│ ││', '├─┼┤', '│ ││', '└─┴┘' ].join(''); var ROUNDED = [ '╭─┬╮', '│ ││', '├─┼┤', '│ ││', '╰─┴╯' ].join(''); var SEMI_ROUNDED = [ '┏━┳┓', '┃ ┃┃', '┡━╇┩', '│ ││', '╰─┴╯' ].join(''); var ASCII = [ '+-++', '| ||', '+-++', '| ||', '+-++' ].join(''); var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var defaultConfig = { palette: DEFAULT, padding: 1, silent: false }; function table(keyMap, data, configuration) { if (configuration === void 0) { configuration = defaultConfig; } // Fill in config gaps with defaults var config = __assign(__assign({}, defaultConfig), configuration); // Deconstruct the palette into managable chunks var _a = config.palette.split(''), TL = _a[0], TS = _a[1], TM = _a[2], TR = _a[3], LL = _a[4], LS = _a[5], LM = _a[6], LR = _a[7], ML = _a[8], MS = _a[9], MM = _a[10], MR = _a[11], RL = _a[12], RS = _a[13], RM = _a[14], RR = _a[15], BL = _a[16], BS = _a[17], BM = _a[18], BR = _a[19]; // Convert object based keyMap to array based keyMap var keys = Array.isArray(keyMap) ? keyMap : Object.keys(keyMap).map(function (key) { return __assign({ key: key }, keyMap[key]); }); // Figure out how many characters the longest value/label is per column var lengthMap = new Map(keys.map(function (_a) { var key = _a.key, label = _a.label; return ([ key, data.reduce(function (longest, item) { var itemLength = String(item[key]).length; return Math.max(longest, itemLength); }, label.length) + config.padding * 2 ]); })); // Generate placeholder whitespace for each column width var columns = keys.map(function (_a) { var key = _a.key; return (sprintf("%".concat(lengthMap.get(key), "s"), ' ')); }); // generateSolidRow returns a table row of provided parts var generateSolidRow = function (left, separator, middle, right) { return ("".concat(left).concat(columns.join(middle).replace(/ /g, separator)).concat(right)); }; // generateRow returns a table row with content var generateRow = function (left, separator, middle, right, row) { return (left + keys.map(function (_a) { var key = _a.key; return (sprintf("%".concat(config.padding, "s%-").concat(Number(lengthMap.get(key)) - config.padding, "s"), '', row[key])); }).join(middle) + right); }; // This is where the table will be stored var result = []; // top result.push(generateSolidRow(TL, TS, TM, TR)); // labels result.push(generateRow(LL, LS, LM, LR, keys.reduce(function (r, _a) { var key = _a.key, label = _a.label; r[key] = label; return r; }, {}))); // mid result.push(generateSolidRow(ML, MS, MM, MR)); // rows result.push(data.map(function (row) { var formattedRow = keys.reduce(function (r, _a) { var key = _a.key, format = _a.format; r[key] = format ? format(row[key]) : row[key]; return r; }, {}); return generateRow(RL, RS, RM, RR, formattedRow); }).join('\n')); // end result.push(generateSolidRow(BL, BS, BM, BR)); var finalizedResult = result.join('\n'); if (config.silent === false) { if (process) { process.stdout.write(finalizedResult + '\n'); } else { console.log(finalizedResult); } } return finalizedResult; } exports.TABLE_PALETTE_ASCII = ASCII; exports.TABLE_PALETTE_DEFAULT = DEFAULT; exports.TABLE_PALETTE_HEAVY = HEAVY; exports.TABLE_PALETTE_ROUNDED = ROUNDED; exports.TABLE_PALETTE_SEMI_ROUNDED = SEMI_ROUNDED; exports.TABLE_PALETTE_THIN = THIN; exports.printf = printf; exports.sprintf = sprintf; exports.table = table; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=index.js.map