kopia lustrzana https://github.com/badgen/badgen
Improve error handling
rodzic
cdc622ed75
commit
d371712afa
|
@ -4,21 +4,23 @@ function calcWidth (charWidthTable) {
|
||||||
const SCALE = 10
|
const SCALE = 10
|
||||||
const widthTable = charWidthTable.map(w => Math.round(w * SCALE))
|
const widthTable = charWidthTable.map(w => Math.round(w * SCALE))
|
||||||
return function (text) {
|
return function (text) {
|
||||||
if (typeof text !== 'string') {
|
typeAssert(typeof text === 'string', 'Input must be string')
|
||||||
return 0
|
|
||||||
} else {
|
let total = 0
|
||||||
let total = 0
|
let i = text.length
|
||||||
let i = text.length
|
let charCode = 0
|
||||||
let charCode = 0
|
while (i--) {
|
||||||
while (i--) {
|
charCode = text[i].charCodeAt()
|
||||||
charCode = text[i].charCodeAt()
|
total += widthTable[charCode < 127 ? charCode : 64] // "@" for overflows
|
||||||
total += widthTable[charCode < 127 ? charCode : 64] // "@" for overflows
|
|
||||||
}
|
|
||||||
return total / SCALE
|
|
||||||
}
|
}
|
||||||
|
return total / SCALE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const typeAssert = (assertion, message) => {
|
||||||
|
if (!assertion) throw new TypeError(message)
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
Verdana11: calcWidth(widthsVerdana11)
|
Verdana11: calcWidth(widthsVerdana11)
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,3 +7,8 @@ tap.test('calc width for "npm"', t => {
|
||||||
t.is(calcWidth('npm'), 24.9, 'result is correct value')
|
t.is(calcWidth('npm'), 24.9, 'result is correct value')
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
tap.test('exception handling', t => {
|
||||||
|
t.throws(() => calcWidth(0), TypeError, 'throw if feed with non-string input')
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
Ładowanie…
Reference in New Issue