wallet-core/node_modules/string-width/index.js

37 lines
649 B
JavaScript
Raw Normal View History

2017-05-03 15:35:00 +02:00
'use strict';
2017-12-27 19:33:54 +01:00
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');
2017-05-03 15:35:00 +02:00
2017-12-27 19:33:54 +01:00
module.exports = str => {
2017-05-03 15:35:00 +02:00
if (typeof str !== 'string' || str.length === 0) {
return 0;
}
str = stripAnsi(str);
2017-12-27 19:33:54 +01:00
let width = 0;
for (let i = 0; i < str.length; i++) {
const code = str.codePointAt(i);
2017-05-03 15:35:00 +02:00
2017-12-27 19:33:54 +01:00
// Ignore control characters
if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
2017-05-03 15:35:00 +02:00
continue;
}
2017-12-27 19:33:54 +01:00
// Ignore combining characters
if (code >= 0x300 && code <= 0x36F) {
continue;
2017-05-03 15:35:00 +02:00
}
2017-12-27 19:33:54 +01:00
// Surrogates
if (code > 0xFFFF) {
i++;
2017-05-03 15:35:00 +02:00
}
2017-12-27 19:33:54 +01:00
width += isFullwidthCodePoint(code) ? 2 : 1;
2017-05-03 15:35:00 +02:00
}
return width;
};