2023-11-13 15:33:56 -05:00
|
|
|
import { chars } from './utils.ts';
|
2023-11-14 15:53:45 -05:00
|
|
|
import { getRuntime } from './runtime.ts';
|
2023-11-13 14:46:04 -05:00
|
|
|
|
|
|
|
export class Row {
|
|
|
|
chars: string[] = [];
|
|
|
|
|
|
|
|
constructor(s: string = '') {
|
|
|
|
this.chars = chars(s);
|
|
|
|
}
|
|
|
|
|
|
|
|
public toString(): string {
|
|
|
|
return this.chars.join('');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Document {
|
|
|
|
#rows: Row[];
|
|
|
|
|
|
|
|
private constructor() {
|
|
|
|
this.#rows = [];
|
|
|
|
}
|
|
|
|
|
2023-11-16 11:10:33 -05:00
|
|
|
get numRows(): number {
|
2023-11-13 14:46:04 -05:00
|
|
|
return this.#rows.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static empty(): Document {
|
|
|
|
return new Document();
|
|
|
|
}
|
|
|
|
|
2023-11-14 15:53:45 -05:00
|
|
|
public isEmpty(): boolean {
|
|
|
|
return this.#rows.length === 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async open(filename: string): Promise<Document> {
|
|
|
|
const { file } = await getRuntime();
|
|
|
|
|
|
|
|
// Clear any existing rows
|
|
|
|
if (!this.isEmpty()) {
|
|
|
|
this.#rows = [];
|
|
|
|
}
|
2023-11-13 14:46:04 -05:00
|
|
|
|
2023-11-14 15:53:45 -05:00
|
|
|
const rawFile = await file.openFile(filename);
|
|
|
|
rawFile.split(/\r?\n/)
|
|
|
|
.forEach((row) => this.appendRow(row));
|
2023-11-13 14:46:04 -05:00
|
|
|
|
2023-11-14 15:53:45 -05:00
|
|
|
return this;
|
2023-11-13 14:46:04 -05:00
|
|
|
}
|
|
|
|
|
2023-11-14 15:53:45 -05:00
|
|
|
public row(i: number): Row | null {
|
2023-11-13 14:46:04 -05:00
|
|
|
if (this.#rows[i] !== undefined) {
|
|
|
|
return this.#rows[i];
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
2023-11-14 15:53:45 -05:00
|
|
|
|
|
|
|
protected appendRow(s: string): void {
|
|
|
|
this.#rows.push(new Row(s));
|
|
|
|
}
|
2023-11-13 14:46:04 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default Document;
|