badgen/lib/calc-text-width.js

29 wiersze
785 B
JavaScript
Czysty Zwykły widok Historia

2018-07-14 18:14:24 +00:00
const widthsVerdana11 = require('./widths-verdana-11.json')
const astralRegex = require('./unicode-astral-regex.js')
2018-05-30 02:43:23 +00:00
2018-06-22 15:49:01 +00:00
function calcWidth (charWidthTable) {
2018-07-11 05:36:30 +00:00
const SCALE = 10
const widthTable = charWidthTable.map(w => Math.round(w * SCALE))
return function (text, unicode) {
2018-07-18 05:59:40 +00:00
typeAssert(typeof text === 'string', 'Input must be string')
if (unicode) text = text.match(astralRegex)
2018-07-18 05:59:40 +00:00
let total = 0
let i = text.length
let charCode = 0
while (i--) {
charCode = text[i].charCodeAt()
total += widthTable[charCode < 127 ? charCode : 64] // "@" for overflows
2018-06-22 15:49:01 +00:00
}
2018-07-18 05:59:40 +00:00
return total / SCALE
2018-05-30 02:43:23 +00:00
}
}
2018-07-18 05:59:40 +00:00
const typeAssert = (assertion, message) => {
if (!assertion) throw new TypeError(message)
}
2018-05-30 02:43:23 +00:00
module.exports = {
2018-07-14 18:14:24 +00:00
Verdana11: calcWidth(widthsVerdana11)
2018-05-30 02:43:23 +00:00
}