From d371712afa5d3281df9aa98099e2148b776dfb58 Mon Sep 17 00:00:00 2001 From: Amio Date: Wed, 18 Jul 2018 13:59:40 +0800 Subject: [PATCH] Improve error handling --- lib/calc-text-width.js | 24 +++++++++++++----------- test/calc-text-width.spec.js | 5 +++++ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/lib/calc-text-width.js b/lib/calc-text-width.js index f66b458..79ff612 100644 --- a/lib/calc-text-width.js +++ b/lib/calc-text-width.js @@ -4,21 +4,23 @@ function calcWidth (charWidthTable) { const SCALE = 10 const widthTable = charWidthTable.map(w => Math.round(w * SCALE)) return function (text) { - if (typeof text !== 'string') { - return 0 - } else { - let total = 0 - let i = text.length - let charCode = 0 - while (i--) { - charCode = text[i].charCodeAt() - total += widthTable[charCode < 127 ? charCode : 64] // "@" for overflows - } - return total / SCALE + typeAssert(typeof text === 'string', 'Input must be string') + + let total = 0 + let i = text.length + let charCode = 0 + while (i--) { + charCode = text[i].charCodeAt() + total += widthTable[charCode < 127 ? charCode : 64] // "@" for overflows } + return total / SCALE } } +const typeAssert = (assertion, message) => { + if (!assertion) throw new TypeError(message) +} + module.exports = { Verdana11: calcWidth(widthsVerdana11) } diff --git a/test/calc-text-width.spec.js b/test/calc-text-width.spec.js index 768ee59..8399242 100644 --- a/test/calc-text-width.spec.js +++ b/test/calc-text-width.spec.js @@ -7,3 +7,8 @@ tap.test('calc width for "npm"', t => { t.is(calcWidth('npm'), 24.9, 'result is correct value') t.end() }) + +tap.test('exception handling', t => { + t.throws(() => calcWidth(0), TypeError, 'throw if feed with non-string input') + t.end() +})