Skip to content

Commit

Permalink
perf: optimize binary search (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
inottn authored May 12, 2024
1 parent 4725cff commit e0221f5
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,15 +224,17 @@ export class MiniPoster {
getAllLines(data: TextConfig) {
const { context } = this;
const { width, content, lineClamp = Infinity } = data;
const contentLength = content.length;
const lines = [];
let index = 0;

while (index < content.length && lines.length < lineClamp) {
while (index < contentLength && lines.length < lineClamp) {
const prevIndex = index;

index =
binarySearch(
content,
index,
contentLength,
(end) =>
context.measureText(content.slice(index, end + 1)).width > width!,
) + 1;
Expand All @@ -241,7 +243,7 @@ export class MiniPoster {
index = prevIndex + 1;
}

if (lineClamp === lines.length + 1 && index < content.length) {
if (lineClamp === lines.length + 1 && index < contentLength) {
lines.push(content.slice(prevIndex, index - 1) + '...');
} else {
lines.push(content.slice(prevIndex, index));
Expand Down
6 changes: 2 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@ import type {
type BinarySearchValidate = (index: number) => boolean;

export const binarySearch = function (
value: string,
left: number,
right: number,
validate: BinarySearchValidate,
) {
let left = 0;
let right = value.length;

while (left < right) {
const mid = left + ((right - left) >> 1);

Expand Down

0 comments on commit e0221f5

Please sign in to comment.