Skip to content

Commit f8081c9

Browse files
authored
Merge pull request #83 from darkriszty/feature/col-length-calc-perf-improvement
Cache the table's longest column length calculation
2 parents 5ef8238 + 952f814 commit f8081c9

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
88
### Added
99
- Issue #78: Support tab indentation for tables without a border.
1010
- Issue #77: Monospacing Issue with CJK Font: separator length not calculated correctly.
11+
- Issue #82: Improve performance of column length calculation
1112
- Updated Node to the latest LTS for the Docker image.
1213
- Updated the devDependencies.
1314
- Updated the versions for running the tests.

src/models/table.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Row } from "./row";
33

44
export class Table {
55
private readonly _rows: Row[];
6+
private _longestColumnLengthsCache: number[] = null;
67

78
constructor(
89
rows: Row[],
@@ -33,11 +34,17 @@ export class Table {
3334
public getLongestColumnLengths(): number[] {
3435
if (!this.hasRows) return [];
3536

36-
let maxColLengths: number[] = new Array(this.columnCount).fill(0);
37+
this._longestColumnLengthsCache ??= this._calculateLongestColumnLengths();
38+
return this._longestColumnLengthsCache;
39+
}
40+
41+
private _calculateLongestColumnLengths(): number[] {
42+
let result = new Array(this.columnCount).fill(0);
43+
3744
for (let row = 0; row < this.rows.length; row++)
3845
for (let col = 0; col < this.rows[row].cells.length; col++)
39-
maxColLengths[col] = Math.max(this.rows[row].cells[col].getLength(), maxColLengths[col]);
46+
result[col] = Math.max(this.rows[row].cells[col].getLength(), result[col]);
4047

41-
return maxColLengths;
48+
return result;
4249
}
4350
}

0 commit comments

Comments
 (0)