@thi.ng/text-format
Version:
Customizable color text formatting with presets for ANSI & HTML
43 lines (42 loc) • 1.16 kB
JavaScript
import {
PRESETS_TPL
} from "./api.js";
const defFormat = (fmt, code) => (x) => fmt.format(code, x);
const defFormatPresets = (format2) => Object.keys(PRESETS_TPL).reduce(
(acc, id) => (acc[id] = defFormat(format2, PRESETS_TPL[id]), acc),
{ format: format2 }
);
const format = (format2, data, width = data.length, offset = 0) => {
const { start, end, prefix, suffix, zero } = format2;
const check = zero ? () => prevID !== -1 : () => prevID !== 0;
const res = [prefix];
let prevID, ch, id;
prevID = zero ? -1 : 0;
for (let x = 0; x < width; x++) {
ch = data[x + offset];
id = ch >>> 16;
if (id != prevID) {
check() && res.push(end);
(zero || id) && res.push(start(id));
prevID = id;
}
res.push(String.fromCharCode(ch & 65535));
}
check() && res.push(end);
res.push(suffix);
return res.join("");
};
const formatNone = (data, width = data.length, offset = 0) => {
const res = [];
for (let x = 0; x < width; x++) {
res.push(String.fromCharCode(data[x + offset] & 65535));
}
res.push("\n");
return res.join("");
};
export {
defFormat,
defFormatPresets,
format,
formatNone
};