Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/floppy-chefs-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"unicode-segmenter": minor
---

Add `collectGraphemeIndices(input, dest)` API that collects the start indices of the grapheme clusters found in the input string into the given destination array.

This is a faster and more GC friendly version of `collectGraphemes(input)` since the input string is not split into every grapheme cluster.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ lcov.info
*.hermes.js
*.hermes.hbc
*.bundle.js

.idea/
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,22 @@ collectGraphemes('#️⃣*️⃣0️⃣1️⃣2️⃣'); // => ["#️⃣", "*️

However, it collects all grapheme clusters at once, so it's not good for large text or streamed input.


#### Example: Collect grapheme start indices into a reusable array

If you only want the **start indices** of each grapheme cluster, use `collectGraphemeIndices()`, which is optimized to avoid allocations for segments and the output array.

It populates a reusable target array in-place, returns the number of indices written, and is typically **2-4x faster** than `collectGraphemes()` and more GC friendly, so you can call it in a hot path.

```js
import { collectGraphemeIndices } from 'unicode-segmenter/grapheme';

const dest = [];
const str = 'a🏳️‍🌈b';
str.length; // => 8
const count = collectGraphemeIndices('a🏳️‍🌈b', dest); // 3 + fills dest with [0, 1, 7]
```

#### Example: Count graphemes

If you need only the count, use `countGraphemes()`, which is optimized to avoid allocations for segments.
Expand Down
4 changes: 4 additions & 0 deletions benchmark/grapheme/codspeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ import {
countGraphemes,
splitGraphemes,
collectGraphemes,
collectGraphemeIndices,
} from 'unicode-segmenter/grapheme';
import { testcases } from './_testcases.js';
import { corpora } from './_corpora.js';

const bench = withCodSpeed(new Bench());

const sharedIndexBuffer = new Array(65536).fill(0);

/**
* One factory per API, so that the function CodSpeed measures contains a single call and nothing else.
*
Expand All @@ -24,6 +27,7 @@ const apis = [
['countGraphemes', input => () => { void countGraphemes(input); }],
['splitGraphemes', input => () => { void [...splitGraphemes(input)]; }],
['collectGraphemes', input => () => { void collectGraphemes(input); }],
['collectGraphemeIndices', input => () => { void collectGraphemeIndices(input, sharedIndexBuffer); }],
];

/**
Expand Down
64 changes: 64 additions & 0 deletions benchmark/grapheme/perf-collect-indices.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {
group,
summary,
barplot,
bench,
run,
do_not_optimize,
} from 'mitata';

import {
splitGraphemes,
collectGraphemes,
collectGraphemeIndices,
} from '../../src/grapheme.js';
import { testcases } from './_testcases.js';

// Node.js, Deno, Bun
const isSystemRuntime = typeof process === 'object' || typeof Deno === 'object' && typeof Bun === 'object';
const isWebWorker = !isSystemRuntime && typeof self === 'object';

const intlSegmenter = new Intl.Segmenter();

const sharedIndexBuffer = new Array(65536).fill(0);

for (const [title, input] of testcases) {
group(title, () => {
summary(() => {
barplot(() => {
bench('unicode-segmenter (collect indices)', () => {
do_not_optimize(collectGraphemeIndices(input, sharedIndexBuffer));
}).gc('inner').baseline(true);

bench('unicode-segmenter (collect)', () => {
do_not_optimize([...collectGraphemes(input)]);
}).gc('inner');

bench('unicode-segmenter (split)', () => {
do_not_optimize([...splitGraphemes(input)]);
}).gc('inner');

bench('Intl.Segmenter (naive)', () => {
do_not_optimize([...intlSegmenter.segment(input)].map(s => s.segment));
}).gc('inner');
});
});
});
}

await run({
format: (!isWebWorker && process.env.MITATA_FORMAT) || 'mitata',
...isWebWorker && {
colors: false,
print(s) {
self.postMessage({ type: 'log', message: s });
},
},
...isSystemRuntime && {
colors: !process.env.NO_COLOR,
},
});

if (isWebWorker) {
self.postMessage({ type: 'done' });
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@
"perf:grapheme:hermes": "node benchmark/grapheme/perf-hermes.js",
"perf:grapheme:quickjs": "node benchmark/grapheme/perf-quickjs.js",
"perf:grapheme-count": "node --expose-gc benchmark/grapheme/perf-count.js",
"perf:grapheme-collect": "node --expose-gc benchmark/grapheme/perf-collect.js"
"perf:grapheme-collect": "node --expose-gc benchmark/grapheme/perf-collect.js",
"perf:grapheme-collect-indices": "node --expose-gc benchmark/grapheme/perf-collect-indices.js"
},
"alias": {
"process": false
Expand Down
54 changes: 54 additions & 0 deletions src/grapheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,57 @@ export function collectGraphemes(input) {
result.push(input.slice(index));
return result;
}

/**
* Collect all extended grapheme cluster start indices in the given text.
*
* Writes the start index of each grapheme cluster into `dest` and returns
* the number of indices written. Useful for zero-allocation iteration or buffer reuse.
*
* @param {string} input
* @param {number[]} dest - The destination array to write start indices into.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is an input array strictly necessary for your use case? While it might be desirable to further reduce the number of temporary objects, I’d prefer to keep the API surface area as small as possible, or use a wrapper to reduce duplication.

To maintain consistency with the existing collect API, we would likely need to add a separate method something like collectGraphemeIndiciesInto().

So it would be collectGraphemeIndiciesInto() as you added ans plus:

function collectGraphemeIndicies(input) {
  let ret = [];
  collectGraphemeIndiciesInto(input, ret);
  return ret;
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is necessary for my use case. I'm ok with splitting it into those two methods if that's the direction you'd like to take.

* @return {number} The number of graphemes (and indices written to `dest`).
*
* @example
* const dest = [];
* const str = 'a🏳️‍🌈b';
* str.length; // => 8
* const count = collectGraphemeIndices('a🏳️‍🌈b', dest); // 3 + fills dest with [0, 1, 7]
*/
export function collectGraphemeIndices(input, dest) {
let len = input.length;
if (len === 0) return 0;

let cp = /** @type {number} */ (input.codePointAt(0));
let cursor = cp > 0xFFFF ? 2 : 1;

/** Category of the last consumed code point */
let catBefore = cat(cp);

/** Packed sequence state, seeded with the always-set bit 0 */
let st = nextState(1, catBefore, cp);

/** Start index of the current segment */
let index = 0;

/** how many boundary indices have been written to dest */
let boundaryCount = 0;

while (cursor < len) {
cp = /** @type {number} */ (input.codePointAt(cursor));
let catAfter = cat(cp);
let boundary = !(st & PAIR[catBefore << 4 | catAfter]);

st = nextState(st, catAfter, cp);

if (boundary) {
dest[boundaryCount++] = index;
index = cursor;
}
cursor += cp > 0xFFFF ? 2 : 1;
catBefore = catAfter;
}

dest[boundaryCount++] = index;
return boundaryCount;
}
71 changes: 71 additions & 0 deletions test/grapheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
collectGraphemes,
} from 'unicode-segmenter/grapheme';
import { assertObjectContaining } from './_helper.js';
import {collectGraphemeIndices} from "#src/grapheme.js";

test('graphemeSegments', async t => {
await t.test('empty string', () => {
Expand Down Expand Up @@ -216,6 +217,76 @@ test('collectGraphemes', async t => {
});
});

test('collectGraphemeIndices', async t => {
await t.test('latin', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('abcd', dest), 4);
assert.deepEqual(dest, [0, 1, 2, 3]);
});

await t.test('flags', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('🇷🇸🇮🇴', dest), 2);
assert.deepEqual(dest, [0, 4]);
});

await t.test('emoji', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('👻👩‍👩‍👦‍👦', dest), 2);
assert.deepEqual(dest, [0, 2]);

assert.equal(collectGraphemeIndices('🌷🎁💩😜👍🏳️‍🌈', dest), 6);
assert.deepEqual(dest, [0, 2, 4, 6, 8, 10]);
});

await t.test('diacritics as combining marks', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('Ĺo͂řȩm̅', dest), 5);
assert.deepEqual(dest, [0, 2, 4, 6, 8]);
});

await t.test('Jamo', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('가갉', dest), 2);
assert.deepEqual(dest, [0, 1]);
});

await t.test('Hindi', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('अनुच्छेद', dest), 4);
assert.deepEqual(dest, [0, 1, 3, 7]);
});

await t.test('demonic', () => {
/** @type {number[]} */
const dest = [];
assert.equal(collectGraphemeIndices('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞', dest), 6);
assert.deepEqual(dest, [0, 19, 28, 34, 47, 58]);
});

await t.test('reuses given array', () => {
/** @type {number[]} */
const dest = [];

assert.equal(collectGraphemeIndices('', dest), 0);
assert.deepEqual(dest, []);

assert.equal(collectGraphemeIndices('a🏳️‍🌈b🏳️‍🌈c', dest), 5);
assert.deepEqual(dest, [0, 1, 7, 8, 14]);

assert.equal(collectGraphemeIndices('xa🏳️‍🌈b🏳️‍🌈c🏳️‍🌈d', dest), 8);
assert.deepEqual(dest, [0, 1, 2, 8, 9, 15, 16, 22]);

assert.equal(collectGraphemeIndices('xya🏳️‍🌈b', dest), 5);
assert.deepEqual(dest, [0, 1, 2, 3, 9, 15, 16, 22]);
});
});


test('conformance', async t => {
Expand Down