diff --git a/libs/calc-text-width.js b/libs/calc-text-width.js new file mode 100644 index 0000000..d780855 --- /dev/null +++ b/libs/calc-text-width.js @@ -0,0 +1,20 @@ +// https://codesandbox.io/s/lr4ynm652 +const verdana12Widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4.21875,4.72265625,5.5078125,9.8203125,7.62890625,12.9140625,8.71875,3.22265625,5.44921875,5.44921875,7.62890625,9.8203125,4.365234375,5.44921875,4.365234375,5.44921875,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,7.62890625,5.44921875,5.44921875,9.8203125,9.8203125,9.8203125,6.544921875,12,8.203125,8.2265625,8.37890625,9.24609375,7.587890625,6.896484375,9.3046875,9.017578125,5.05078125,5.455078125,8.314453125,6.6796875,10.11328125,8.9765625,9.4453125,7.236328125,9.4453125,8.34375,8.203125,7.39453125,8.783203125,8.203125,11.865234375,8.220703125,7.3828125,8.220703125,5.44921875,5.44921875,5.44921875,9.8203125,7.62890625,7.62890625,7.20703125,7.4765625,6.251953125,7.4765625,7.1484375,4.21875,7.4765625,7.59375,3.29296875,4.130859375,7.1015625,3.29296875,11.671875,7.59375,7.283203125,7.4765625,7.4765625,5.12109375,6.251953125,4.728515625,7.59375,7.1015625,9.8203125,7.1015625,7.1015625,6.3046875,7.6171875,5.44921875,7.6171875,9.8203125] + +function Verdana12 (text) { + if (typeof text !== 'string') { + throw new TypeError('text should be string.') + } else { + return calcWidth(text, verdana12Widths) + } +} + +function calcWidth (text, charWidths) { + return Array.from(text).reduce((total, curr) => { + return total + charWidths[curr.charCodeAt()] + }, 0) +} + +module.exports = { + Verdana12 +}