UNPKG

text-aligner

Version:

Align text by adding spaces to each string so that all strings have the same number of English and Chinese characters.

82 lines (81 loc) 2.41 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { alignText: () => alignText }); module.exports = __toCommonJS(index_exports); var DefaultPaddingMap = { cjk: { test: isCJK, width: 2 } }; function isCJK(char) { const cjkRanges = [ [19968, 40959], [13312, 19903], [131072, 173791], [173824, 177983], [177984, 178207], [178208, 183983], [63744, 64255], [194560, 195103], [12352, 12447], [12448, 12543], [12784, 12799], [44032, 55203], [4352, 4607], [12592, 12687], [65280, 65519] ]; const charCode = char.codePointAt(0); return cjkRanges.some(([start, end]) => charCode >= start && charCode <= end); } function getCharWidth(char, rules) { for (const rule of Object.values(rules)) { const matched = typeof rule.test === "function" ? rule.test(char) : rule.test.test(char); if (matched) { return rule.width; } } return 1; } function getStringWidth(str, rules) { let width = 0; for (const char of str) { width += getCharWidth(char, rules); } return width; } function alignText(strings, paddingMap = {}, placeholder = " ") { const mergedPaddingMap = { ...DefaultPaddingMap, ...paddingMap }; const widths = strings.map((str) => getStringWidth(str, mergedPaddingMap)); const maxWidth = Math.max(...widths); return strings.map((str, index) => { const diff = maxWidth - widths[index]; return str + placeholder.repeat(diff); }); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { alignText }); //# sourceMappingURL=index.cjs.map