badgen/lib/calc-text-width.js

31 wiersze
901 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-18 16:35:09 +00:00
const SCALE = 10 // Prevent results like 60.599999999999994
const widthTable = charWidthTable.map(w => Math.round(w * SCALE))
2018-07-18 16:35:09 +00:00
widthTable[64] = widthTable[64] + 2 // Slightly increase width of "@" by 0.2px
2018-07-18 16:50:28 +00:00
return function (text, astral) {
2018-07-18 05:59:40 +00:00
typeAssert(typeof text === 'string', 'Input must be string')
2018-07-18 16:50:28 +00:00
if (astral) text = text.match(astralRegex)
2018-07-18 05:59:40 +00:00
let total = 0
2018-07-18 16:35:09 +00:00
let code = 0
2018-07-18 05:59:40 +00:00
let i = text.length
while (i--) {
2018-07-18 16:35:09 +00:00
code = text[i].charCodeAt()
total += widthTable[code < 127 ? code : 64] // Width as "@" 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
}