Skip to content

Commit f847604

Browse files
committed
feat: add SegmentSplitter class
1 parent 94cd918 commit f847604

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,30 @@ console.log(secondWord);
169169

170170
---
171171

172+
## SegmentSplitter Class
173+
174+
Alternatively, the `SegmentSplitter` class allows you to create an instance that can be directly used with JavaScript's `String.prototype.split` method for basic segmentation.
175+
176+
### Constructor
177+
178+
```typescript
179+
new SegmentSplitter<T extends Granularity>(granularity: T, options?: SegmentationOptions<T>);
180+
```
181+
182+
- **granularity**: Specifies the segmentation granularity level (`'grapheme'`, `'word'`, `'sentence'`, etc.).
183+
- **options**: Optional settings to customize the segmentation for the given granularity.
184+
185+
## Example Usage
186+
187+
```typescript
188+
const str = "Hello, world!";
189+
const wordSplitter = new SegmentSplitter("word", { isWordLike: true });
190+
const words = str.split(wordSplitter);
191+
console.log(words); // ["Hello", "world"]
192+
```
193+
194+
---
195+
172196
## Individual Functions
173197

174198
### `getRawSegments`

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "segment-string",
3-
"version": "0.0.7",
3+
"version": "0.0.8",
44
"description": "A lightweight wrapper around Intl.Segmenter for segment-aware string operations",
55
"repository": {
66
"type": "git",

src/index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,3 +461,25 @@ export class SegmentString {
461461
return this.str;
462462
}
463463
}
464+
465+
/**
466+
* A class that implements the `Symbol.split` method to use segmentation for splitting strings.
467+
*
468+
* Example usage:
469+
* ```ts
470+
* const str = "Hello, world!";
471+
* const wordSplitter = new SegmentSplitter("word", { isWordLike: true });
472+
* const words = str.split(wordSplitter);
473+
* console.log(words); // ["Hello", "world"]
474+
* ```
475+
*/
476+
export class SegmentSplitter<T extends Granularity> {
477+
constructor(
478+
private readonly granularity: T,
479+
private readonly options: SegmentationOptions<T> = {},
480+
) {}
481+
482+
[Symbol.split](str: string): string[] {
483+
return [...getSegments(str, this.granularity, this.options)];
484+
}
485+
}

0 commit comments

Comments
 (0)