All files / owid-grapher/gridLang GridProgram.ts

90.69% Statements 224/247
89.13% Branches 41/46
80% Functions 20/25
90.69% Lines 224/247

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 3271x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x               1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 4x 9x 9x 74x 74x 17x 17x 74x 74x 67x 67x 67x 67x 65x 74x 27x 27x 27x 27x 27x 40x 40x 38x 38x 38x 38x 38x 9x 9x 9x 9x 1x 1x 5x 5x 5x 5x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 4x 19x 19x 2x 2x 1x 1x             1x 1x 1x 1x 1x 6x 6x 6x 6x 11x 11x 11x 11x 6x 6x 1x 1x 6x 6x 6x 6x 1x 1x 6x 6x 6x 1x 1x 16x 16x 16x 16x 16x 16x 16x 1x 1x 18x 18x 18x 18x 1x 1x 9x 9x 1x 1x 40x 40x 40x 1x 1x 7x 7x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 2x 2x 2x 2x 2x 2x                                                                                                                                                                
import { imemo, trimMatrix } from "../coreTable/CoreTableUtils"
import { isPresent } from "../clientUtils/isPresent"
import { GitCommit, SerializedGridProgram } from "../clientUtils/owidTypes"
 
import { GridCell } from "./GridCell"
import {
    CellDef,
    CellPosition,
    GRID_CELL_DELIMITER,
    GRID_EDGE_DELIMITER,
    GRID_NODE_DELIMITER,
    Origin,
    ParsedCell,
} from "./GridLangConstants"
 
/**
 * Block location for the below would be like (numRows = 2)
 * table             |
 *  slug name        | startRow = 1
 *  pop Population   | endRow   = 2
 */
interface BlockLocation {
    startRow: number
    endRow: number
    numRows: number
}
 
export class GridProgram {
    constructor(
        slug: string,
        tsv: string,
        lastCommit?: GitCommit,
        grammar?: CellDef
    ) {
        this.lines = tsv.replace(/\r/g, "").split(this.nodeDelimiter)
        this.slug = slug
        this.lastCommit = lastCommit
        this.grammar = grammar
    }
 
    private grammar?
 
    private static guids = 0
    guid = ++GridProgram.guids
 
    lastCommit?: GitCommit
    slug: string
 
    private nodeDelimiter = GRID_NODE_DELIMITER
    cellDelimiter = GRID_CELL_DELIMITER
    private edgeDelimiter = GRID_EDGE_DELIMITER
    lines: string[]
 
    toJson(): SerializedGridProgram {
        return {
            program: this.toString(),
            slug: this.slug,
            lastCommit: this.lastCommit,
        }
    }
 
    findNext(position: CellPosition) {
        const cell = this.getCell(position)
        const { contents } = cell
        return this.grepFirst(contents, {
            ...position,
            column: position.column + 1,
        })
    }
 
    findAll(position: CellPosition) {
        const cell = this.getCell(position)
        const { contents } = cell
        return this.grep(contents, {
            ...position,
            column: position.column + 1,
        })
    }
 
    private ring(position: CellPosition) {
        const matrix = this.asArrays
        const numRows = matrix.length
        if (!numRows) return (function* generator() {})()
        const pointer = {
            ...position,
            started: false,
            endRow: position.row,
            endCol: position.column,
        }
        if (pointer.row >= numRows) pointer.endRow = numRows - 1
 
        const lastLine = matrix[pointer.endRow]
        pointer.endCol =
            lastLine[pointer.endCol] === undefined
                ? lastLine.length
                : pointer.endCol
        function* generator() {
            while (true) {
                if (
                    pointer.started &&
                    pointer.row === pointer.endRow &&
                    pointer.column === pointer.endCol
                )
                    return
                pointer.started = true
 
                if (
                    matrix[pointer.row] === undefined ||
                    matrix[pointer.row][pointer.column] === undefined
                ) {
                    pointer.row++
                    pointer.column = 0
                    if (pointer.row >= numRows) pointer.row = 0
                    continue
                }
 
                yield {
                    row: pointer.row,
                    column: pointer.column,
                } as CellPosition
                pointer.column++
            }
        }
 
        return generator()
    }
 
    valuesFrom(position = Origin) {
        return Array.from(this.ring(position)).map((next) =>
            this.getCellContents(next)
        )
    }
 
    get numRows() {
        return this.lines.length
    }
 
    patch(obj: any) {
        Object.keys(obj).forEach((key) => this.setLineValue(key, obj[key]))
        return this
    }
 
    grepFirst(key: string, position = Origin) {
        for (const next of this.ring(position)) {
            if (this.getCellContents(next) === key) return next
        }
        return undefined
    }
 
    grep(key: string, position = Origin) {
        const hits: CellPosition[] = []
        for (const next of this.ring(position)) {
            if (this.getCellContents(next) === key) hits.push(next)
        }
        return hits
    }
 
    /**
     * Returns all non-blocks as an object literal
     */
    get tuplesObject() {
        const obj: { [key: string]: any } = {}
        this.lines
            .filter((line) => !line.startsWith(this.edgeDelimiter))
            .forEach((line) => {
                const words = line.split(this.cellDelimiter)
                const key = words.shift()
                if (key) obj[key.trim()] = words.join(this.cellDelimiter).trim()
            })
        return obj
    }
 
    getLine(keyword: string) {
        return this.lines.find((line) =>
            line.startsWith(keyword + this.cellDelimiter)
        )
    }
 
    getLineValue(keyword: string) {
        const line = this.getLine(keyword)
        return line ? line.split(this.cellDelimiter)[1] : undefined
    }
 
    protected getBlockLocation(blockRowNumber: number): BlockLocation {
        const startRow = blockRowNumber + 1
        let numRows = this.lines
            .slice(startRow)
            .findIndex((line) => line && !line.startsWith(this.edgeDelimiter))
        if (numRows === -1) numRows = this.lines.slice(startRow).length
        return { startRow, endRow: startRow + numRows, numRows }
    }
 
    protected getKeywordIndex(key: string) {
        return this.lines.findIndex(
            (line) => line.startsWith(key + this.cellDelimiter) || line === key
        )
    }
 
    getCell(position: CellPosition): ParsedCell {
        return new GridCell(this.matrix, position, this.grammar!)
    }
 
    getCellContents(position: CellPosition) {
        const line = this.matrix[position.row]
        return line ? line[position.column] : undefined
    }
 
    @imemo private get matrix() {
        return this.lines.map((line) => line.split(this.cellDelimiter))
    }
 
    deleteBlock(row?: number) {
        if (row === undefined) return this
        const location = this.getBlockLocation(row)
        if (!location) return this
 
        this.lines.splice(location.startRow, location.numRows)
        return this
    }
 
    deleteLine(row?: number) {
        if (row === undefined) return this
        this.lines.splice(row, 1)
        return this
    }
 
    appendLine(line: string) {
        this.lines.push(line)
        return this
    }
 
    // todo: make immutable and return a new copy
    setCell(row: number, col: number, value: string) {
        const line = this.lines[row]
        const words = line.split(this.cellDelimiter)
        words[col] = value
        this.lines[row] = words.join(this.cellDelimiter)
        return this
    }
 
    setLineValue(key: string, value: string | undefined) {
        const index = this.getKeywordIndex(key)
        const newLine = `${key}${this.cellDelimiter}${value}`
        if (index === -1 && value !== undefined) this.lines.push(newLine)
        else if (value === undefined) this.deleteLine(index)
        else this.lines[index] = newLine
        return this
    }
 
    getBlock(keywordIndex: number) {
        const location = this.getBlockLocation(keywordIndex)
        return this.lines
            .slice(location.startRow, location.endRow)
            .map((line) => line.substr(1))
            .join(this.nodeDelimiter)
    }
 
    updateBlock(rowNumber: number, value: string) {
        const location = this.getBlockLocation(rowNumber)
        this.lines.splice(
            location.startRow,
            location.numRows,
            ...value
                .split(this.nodeDelimiter)
                .map((line) => this.edgeDelimiter + line)
        )
        return this
    }
 
    protected appendBlock(key: string, value: string) {
        this.lines.push(key)
        value
            .split(this.nodeDelimiter)
            .forEach((line) => this.lines.push(this.edgeDelimiter + line))
    }
 
    getRowNumbersStartingWith(startsWith: string) {
        return this.lines
            .map((line, index) =>
                line.startsWith(startsWith + this.cellDelimiter) ||
                line === startsWith
                    ? index
                    : null
            )
            .filter(isPresent)
    }
 
    private static lineMatchesWords = (
        line: string[],
        words: (string | undefined)[]
    ): boolean =>
        words.every((word, index) => word === undefined || line[index] === word)
 
    getRowMatchingWords(...words: (string | undefined)[]): number {
        return this.asArrays.findIndex((line) =>
            GridProgram.lineMatchesWords(line, words)
        )
    }
 
    getAllRowsMatchingWords(...words: (string | undefined)[]): number[] {
        const rows: number[] = []
        this.asArrays.forEach((line: string[], rowIndex: number) => {
            if (GridProgram.lineMatchesWords(line, words)) rows.push(rowIndex)
        })
        return rows
    }
 
    get asArrays(): string[][] {
        return this.lines.map((line) => line.split(this.cellDelimiter))
    }
 
    // The max number of columns in any row when you view a program as a spreadsheet
    get width() {
        return Math.max(...this.asArrays.map((arr) => arr.length))
    }
 
    toString() {
        return this.prettify()
    }
 
    protected prettify() {
        return trimMatrix(this.asArrays)
            .map((line) => line.join(this.cellDelimiter))
            .join(this.nodeDelimiter)
    }
}