summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/update-notifier/node_modules/boxen/node_modules/string-width/index.js
blob: 25a8943c1dcad69fc85a576146b60f64d9b99bbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'use strict';
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');

module.exports = str => {
	if (typeof str !== 'string' || str.length === 0) {
		return 0;
	}

	let width = 0;

	str = stripAnsi(str);

	for (let i = 0; i < str.length; i++) {
		const code = str.codePointAt(i);

		// ignore control characters
		if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
			continue;
		}

		// surrogates
		if (code >= 0x10000) {
			i++;
		}

		if (isFullwidthCodePoint(code)) {
			width += 2;
		} else {
			width++;
		}
	}

	return width;
};