schlechtenburg/packages/rich-text/lib/slice.ts
2024-10-08 09:15:26 +02:00

27 lines
882 B
TypeScript

import { RichTextValue } from "./types";
/**
* Slice a Rich Text value from `startIndex` to `endIndex`. Indices are
* retrieved from the selection if none are provided. This is similar to
* `String.prototype.slice`.
*
* @param {RichTextValue} value Value to modify.
* @param {number} [startIndex] Start index.
* @param {number} [endIndex] End index.
*
* @return {RichTextValue} A new extracted value.
*/
export function slice( value: RichTextValue, startIndex: number = value.start || 0, endIndex: number = value.end || 0 ): RichTextValue {
const { formats, replacements, text } = value;
if ( startIndex === undefined || endIndex === undefined ) {
return { ...value };
}
return {
formats: formats.slice( startIndex, endIndex ),
replacements: replacements.slice( startIndex, endIndex ),
text: text.slice( startIndex, endIndex ),
};
}