Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/llimllib/display-width

A fast function for determining a string's display width
https://github.com/llimllib/display-width

Last synced: about 1 month ago
JSON representation

A fast function for determining a string's display width

Awesome Lists containing this project

README

        

# display-width

A node.js port of [uwcwidth](https://github.com/Z4JC/uwcwidth), a fast function for determining a string's display width

That code is a port of POSIX [wcswidth](https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/functions/wcswidth.html), a standard function for counting the number of columns occupied by a string, and is derived from [musl libc](https://github.com/kraj/musl/blob/ffb23aef/src/ctype/wcwidth.c#L11-L29)

## How to use it

```js
import { wcswidth } from "display-width";

// wcswidth("๐Ÿ‘ฉโ€โค๏ธโ€๐Ÿ‘จ") == 2
console.log(wcswidth("\u{1F469}\u{200D}\u{2764}\u{FE0F}\u{200D}\u{1F468}"));
```

## Why to use it

```
>> wcswidth("cafeฬ") == 4
>> "cafeฬ".length == 5

>> wcswidth("โš ๏ธŽ warning") == 9
>> "โš ๏ธŽ warning".length == 10

>> wcswidth("๐Ÿ‘จโ€๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ง") == 2
>> "๐Ÿ‘จโ€๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ง".length == 11

>> wcswidth("๐Ÿ‘ฉโ€โค๏ธโ€๐Ÿ‘จ") == 2
>> "๐Ÿ‘ฉโ€โค๏ธโ€๐Ÿ‘จ".length == 8
```

## Is it fast?

yes! Compared to [string-width](https://www.npmjs.com/package/string-width), it's about **33x** faster

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ (index) โ”‚ Task Name โ”‚ ops/sec โ”‚ Average Time (ns) โ”‚ Margin โ”‚ Samples โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ 0 โ”‚ 'display-width' โ”‚ '188,426' โ”‚ 5307.115321339439 โ”‚ 'ยฑ1.55%' โ”‚ 18843 โ”‚
โ”‚ 1 โ”‚ 'string-width' โ”‚ '5,586' โ”‚ 179008.73345259373 โ”‚ 'ยฑ11.73%' โ”‚ 559 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

see the [bench directory](https://github.com/llimllib/display-width/tree/main/bench) for details

## Is it large?

no!

## Does it have any dependencies?

no!

## Do you completely understand it?

no! I ported the code and all the tests from
[uwcwidth](https://github.com/Z4JC/uwcwidth) though, so I have good vibes about
it