Skip to content

Commit

Permalink
Add LineSplitter
Browse files Browse the repository at this point in the history
  • Loading branch information
Hironsan committed Jun 18, 2021
1 parent 2560d1c commit 5e27685
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module.exports = {
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
"@typescript-eslint/no-non-null-assertion": 0,
},
overrides: [
{
Expand Down
27 changes: 27 additions & 0 deletions src/domain/models/Line/LineSplitter.ts
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;
}
}
26 changes: 26 additions & 0 deletions tests/unit/domain/models/Line/lineSplitter.spec.ts
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);
});
});

0 comments on commit 5e27685

Please sign in to comment.