-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { Line } from "./Line"; | ||
|
||
export class LineSplitter { | ||
constructor(private vocab: Map<string, number>, private maxWidth: number) {} | ||
|
||
split(text: string): Line[] { | ||
let accumulatedWidth = 0; | ||
let startIndex = 0; | ||
const lines = [] as Line[]; | ||
|
||
for (const [i, ch] of Array.from(text).entries()) { | ||
const charWidth = this.vocab.get(ch)!; | ||
accumulatedWidth += charWidth; | ||
if (accumulatedWidth > this.maxWidth) { | ||
const line = new Line(text.substring(startIndex, i)); | ||
lines.push(line); | ||
startIndex = i; | ||
accumulatedWidth = charWidth; | ||
} | ||
} | ||
if (accumulatedWidth > 0) { | ||
const line = new Line(text.substring(startIndex)); | ||
lines.push(line); | ||
} | ||
return lines; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { Line } from "@/domain/models/Line/Line"; | ||
import { LineSplitter } from "@/domain/models/Line/LineSplitter"; | ||
|
||
describe("LineSplitter component", () => { | ||
it("can split text", () => { | ||
const content = "example text"; | ||
const vocab = new Map(); | ||
const maxWidth = 3; | ||
|
||
const characterSet = new Set(content); | ||
const characterArray = Array.from(characterSet); | ||
characterArray.forEach((ch: string) => { | ||
vocab.set(ch, 1); | ||
}); | ||
|
||
const lineSplitter = new LineSplitter(vocab, maxWidth); | ||
const lines = lineSplitter.split(content); | ||
const expected = [ | ||
new Line("exa"), | ||
new Line("mpl"), | ||
new Line("e t"), | ||
new Line("ext"), | ||
]; | ||
expect(lines).toEqual(expected); | ||
}); | ||
}); |