All files / owid-grapher/coreTable CoreTableUtils.ts

90.44% Statements 454/502
82.18% Branches 83/101
80% Functions 16/20
90.44% Lines 454/502

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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 7051x 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 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 2534x 2534x 17714x 17714x 2534x 2534x 17x 1x 1x 1x   1x 1x 1x 1x 1x 1x 9x 9x 9x 24x 24x 9x 1762x 12340x 12340x 12340x 3509x 3509x 3509x 8831x 8831x 12340x 8789x 8784x 8784x 8789x 8789x 42x 12340x 21x 21x 21x 21x 21x 21x 21x 21x 1762x 1762x 9x 1x 1x 1x 1x 1x 9x 9x 9x 9x 66x 66x 66x 66x 66x 9x 9x     1x 1x 1x 1x 1x       1x 1x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 44x 44x 44x 44x 44x 56x 56x 56x 11x 56x 56x 11x 11x 11x 11x 11x 56x 56x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 349x 349x 349x 349x 349x 349x 1974x 1974x 349x 349x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 12x 12x 9x 9x 9x 3x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x   12x           12x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 24x 24x 15x 15x 15x 9x 9x 9x 24x 24x 6x 6x 6x 6x 6x 6x 6x 9x 9x 9x 9x 3x 3x 24x 24x 6x 6x 24x 24x 24x 24x 24x 24x 3x 3x 24x 3x 3x 3x 24x 6x 6x 6x 4x 4x 4x 4x 24x 24x 24x 9x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 22x 22x 22x 22x 22x 22x 6x 1x 1x 1x 1x 15x 783x 783x 1x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 10004x 10004x 5472x 5472x 5472x 5472x 5472x 5472x 5472x 5472x 10004x 10004x 92x 1x 1x                         1x 1x 18x 18x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 45x 45x 90x 90x 90x 87x 90x 3x 3x 3x 3x 3x 3x 90x 45x 45x 9x 9x 1x 1x 227x 227x 21x 21x 101x 101x 21x 21x 1x 1x                                         1x 1x 273x 273x 273x 273x 273x 273x 273x 273x 56x 56x 56x 56x 56x 56x 56x 273x     1x 1x 1x 11x 11x 11x 11x 110x 110x 110x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                        
import { dsvFormat, DSVParsedArray } from "d3-dsv"
import fastCartesian from "fast-cartesian"
import {
    findIndexFast,
    first,
    flatten,
    max,
    range,
    sampleFrom,
    slugifySameCase,
    toString,
    values,
} from "../clientUtils/Util"
import {
    CoreColumnStore,
    CoreRow,
    CoreMatrix,
    Time,
    CoreValueType,
} from "./CoreTableConstants"
import { ColumnTypeNames, CoreColumnDef } from "./CoreColumnDef"
import {
    ErrorValue,
    ErrorValueTypes,
    isNotErrorValueOrEmptyCell,
} from "./ErrorValues"
import {
    OwidEntityCodeColumnDef,
    OwidEntityIdColumnDef,
    OwidEntityNameColumnDef,
    OwidTableSlugs,
} from "./OwidTableConstants"
import { ColumnSlug } from "../clientUtils/owidTypes"
 
export const columnStoreToRows = (
    columnStore: CoreColumnStore
): Record<string, CoreValueType>[] => {
    const firstCol = Object.values(columnStore)[0]
    if (!firstCol) return []
    const slugs = Object.keys(columnStore)
    return firstCol.map((val, index) => {
        const newRow: Record<string, CoreValueType> = {}
        slugs.forEach((slug) => {
            newRow[slug] = columnStore[slug][index]
        })
        return newRow
    })
}
 
// If string exceeds maxLength, will replace the end char with a ... and drop the rest
export const truncate = (str: string, maxLength: number): string =>
    str.length > maxLength ? `${str.substr(0, maxLength - 3)}...` : str
 
// Picks a type for each column from the first row then autotypes all rows after that so all values in
// a column will have the same type. Only chooses between strings and numbers.
const numberOnly = /^-?\d+\.?\d*$/
export const makeAutoTypeFn = (
    numericSlugs?: ColumnSlug[]
): ((object: any) => any) => {
    const slugToType: any = {}
    numericSlugs?.forEach((slug) => {
        slugToType[slug] = "number"
    })
    return (object: any): any => {
        for (const columnSlug in object) {
            const value = object[columnSlug]
            const type = slugToType[columnSlug]
            if (type === "string") {
                object[columnSlug] = value
                continue
            }
 
            const number = parseFloat(value) // The "+" type casting that d3 does for perf converts "" to 0, so use parseFloat.
            if (type === "number") {
                object[columnSlug] = isNaN(number)
                    ? ErrorValueTypes.NaNButShouldBeNumber
                    : number
                continue
            }
 
            if (isNaN(number) || !numberOnly.test(value)) {
                object[columnSlug] = value
                slugToType[columnSlug] = "string"
                continue
            }
 
            object[columnSlug] = number
            slugToType[columnSlug] = "number"
        }
        return object
    }
}
 
// Removes whitespace and non-word characters from column slugs if any exist.
// The original names are moved to the name property on the column def.
export const standardizeSlugs = (
    rows: CoreRow[]
): { rows: CoreRow[]; defs: { name: string; slug: string }[] } | undefined => {
    const firstRow = rows[0] ?? {}
    const colsToRename = Object.keys(firstRow)
        .map((name) => {
            return {
                name,
                slug: slugifySameCase(name),
            }
        })
        .filter((col) => col.name !== col.slug)
    if (!colsToRename.length) return undefined

    rows.forEach((row: CoreRow) => {
        colsToRename.forEach((col) => {
            row[col.slug] = row[col.name]
            delete row[col.name]
        })
    })

    return { rows, defs: colsToRename }
}
 
export const guessColumnDefFromSlugAndRow = (
    slug: string,
    sampleValue: any
): CoreColumnDef => {
    const valueType = typeof sampleValue
 
    const name = slug
 
    if (slug === "Entity")
        return {
            slug,
            type: ColumnTypeNames.EntityName,
            name,
        }
 
    if (slug === "day")
        return {
            slug,
            type: ColumnTypeNames.Day,
            name: "Day",
        }
 
    if (slug === "year" || slug === "Year")
        return {
            slug,
            type: ColumnTypeNames.Year,
            name: "Year",
        }
 
    if (slug === OwidTableSlugs.entityName) return OwidEntityNameColumnDef
    if (slug === OwidTableSlugs.entityCode) return OwidEntityCodeColumnDef
    if (slug === OwidTableSlugs.entityId) return OwidEntityIdColumnDef
 
    if (slug === "date")
        return {
            slug,
            type: ColumnTypeNames.Date,
            name: "Date",
        }
 
    if (valueType === "number")
        return {
            slug,
            type: ColumnTypeNames.Numeric,
            name,
        }
 
    if (valueType === "string") {
        if (sampleValue.match(/^\d+$/))
            return {
                slug,
                type: ColumnTypeNames.Numeric,
                name,
            }
    }
 
    return { slug, type: ColumnTypeNames.String, name }
}
 
export const makeRowFromColumnStore = (
    rowIndex: number,
    columnStore: CoreColumnStore
): CoreRow => {
    const row: CoreRow = {}
    const columns = Object.values(columnStore)
    Object.keys(columnStore).forEach((slug, colIndex) => {
        row[slug] = columns[colIndex][rowIndex]
    })
    return row
}
 
export interface InterpolationContext {}
 
export interface LinearInterpolationContext extends InterpolationContext {
    // whether to extrapolate a variable at the start or end, where we cannot do linear interpolation
    // but need to just copy over the first/last value present over to empty fields.
    // e.g. [Error, Error, 2, 3, 4] would become [2, 2, 2, 3, 4] with extrapolateAtStart=true.
    extrapolateAtStart?: boolean
    extrapolateAtEnd?: boolean
}
 
export interface ToleranceInterpolationContext extends InterpolationContext {
    timeTolerance: number
}
 
export type InterpolationProvider<C extends InterpolationContext> = (
    valuesSortedByTimeAsc: (number | ErrorValue)[],
    timesAsc: Time[],
    context: C,
    start: number,
    end: number
) => void
 
export function linearInterpolation(
    valuesSortedByTimeAsc: (number | ErrorValue)[],
    timesAsc: Time[],
    context: LinearInterpolationContext,
    start: number = 0,
    end: number = valuesSortedByTimeAsc.length
): void {
    if (!valuesSortedByTimeAsc.length) return
 
    let prevNonBlankIndex = -1
    let nextNonBlankIndex = -1
 
    for (let index = start; index < end; index++) {
        const currentValue = valuesSortedByTimeAsc[index]
        if (isNotErrorValueOrEmptyCell(currentValue)) {
            prevNonBlankIndex = index
            continue
        }
 
        if (nextNonBlankIndex === -1 || nextNonBlankIndex <= index) {
            nextNonBlankIndex = findIndexFast(
                valuesSortedByTimeAsc,
                (val) => isNotErrorValueOrEmptyCell(val),
                index + 1,
                end
            )
        }
 
        const prevValue = valuesSortedByTimeAsc[prevNonBlankIndex]
        const nextValue = valuesSortedByTimeAsc[nextNonBlankIndex]
 
        let value
        if (
            isNotErrorValueOrEmptyCell(prevValue) &&
            isNotErrorValueOrEmptyCell(nextValue)
        ) {
            const distLeft = index - prevNonBlankIndex
            const distRight = nextNonBlankIndex - index
            value =
                (prevValue * distRight + nextValue * distLeft) /
                (distLeft + distRight)
        } else if (
            isNotErrorValueOrEmptyCell(prevValue) &&
            context.extrapolateAtEnd
        )
            value = prevValue
        else if (
            isNotErrorValueOrEmptyCell(nextValue) &&
            context.extrapolateAtStart
        )
            value = nextValue
        else value = ErrorValueTypes.NoValueForInterpolation
 
        prevNonBlankIndex = index
 
        valuesSortedByTimeAsc[index] = value
    }
}
 
export function toleranceInterpolation(
    valuesSortedByTimeAsc: (number | ErrorValue)[],
    timesAsc: Time[],
    context: ToleranceInterpolationContext,
    start: number = 0,
    end: number = valuesSortedByTimeAsc.length
): void {
    if (!valuesSortedByTimeAsc.length) return
 
    let prevNonBlankIndex: number | undefined = undefined
    let nextNonBlankIndex: number | undefined = undefined
 
    for (let index = start; index < end; index++) {
        const currentValue = valuesSortedByTimeAsc[index]
        if (isNotErrorValueOrEmptyCell(currentValue)) {
            prevNonBlankIndex = index
            continue
        }
 
        if (
            nextNonBlankIndex !== -1 &&
            (nextNonBlankIndex === undefined || nextNonBlankIndex <= index)
        ) {
            nextNonBlankIndex = findIndexFast(
                valuesSortedByTimeAsc,
                isNotErrorValueOrEmptyCell,
                index + 1,
                end
            )
        }
 
        const timeOfCurrent = timesAsc[index]
        const timeOfPrevIndex =
            prevNonBlankIndex !== undefined
                ? timesAsc[prevNonBlankIndex]
                : -Infinity
        const timeOfNextIndex =
            nextNonBlankIndex !== undefined && nextNonBlankIndex !== -1
                ? timesAsc[nextNonBlankIndex]
                : Infinity
 
        const prevTimeDiff = Math.abs(timeOfPrevIndex - timeOfCurrent)
        const nextTimeDiff = Math.abs(timeOfNextIndex - timeOfCurrent)
 
        if (
            nextNonBlankIndex !== -1 &&
            nextTimeDiff <= prevTimeDiff &&
            nextTimeDiff <= context.timeTolerance
        ) {
            valuesSortedByTimeAsc[index] =
                valuesSortedByTimeAsc[nextNonBlankIndex!]
            timesAsc[index] = timesAsc[nextNonBlankIndex!]
        } else if (
            prevNonBlankIndex !== undefined &&
            prevTimeDiff <= context.timeTolerance
        ) {
            valuesSortedByTimeAsc[index] =
                valuesSortedByTimeAsc[prevNonBlankIndex!]
            timesAsc[index] = timesAsc[prevNonBlankIndex!]
        } else
            valuesSortedByTimeAsc[index] =
                ErrorValueTypes.NoValueWithinTolerance
    }
}
 
export function interpolateRowValuesWithTolerance<
    ValueSlug extends ColumnSlug,
    TimeSlug extends ColumnSlug,
    Row extends { [key in TimeSlug]?: Time } & { [key in ValueSlug]?: any }
>(
    rowsSortedByTimeAsc: Row[],
    valueSlug: ValueSlug,
    timeSlug: TimeSlug,
    timeTolerance: number
): Row[] {
    const values = rowsSortedByTimeAsc.map((row) => row[valueSlug])
    const times = rowsSortedByTimeAsc.map((row) => row[timeSlug])
    toleranceInterpolation(values, times, { timeTolerance })
    return rowsSortedByTimeAsc.map((row, index) => {
        return {
            ...row,
            [valueSlug]: values[index],
            [timeSlug]: times[index],
        }
    })
}
 
// A dumb function for making a function that makes a key for a row given certain columns.
export const makeKeyFn =
    (columnStore: CoreColumnStore, columnSlugs: ColumnSlug[]) =>
    (rowIndex: number): string =>
        // toString() handles `undefined` and `null` values, which can be in the table.
        columnSlugs
            .map((slug) => toString(columnStore[slug][rowIndex]))
            .join(" ")
 
// Memoization for immutable getters. Run the function once for this instance and cache the result.
export const imemo = <Type>(
    target: unknown,
    propertyName: string,
    descriptor: TypedPropertyDescriptor<Type>
): void => {
    const originalFn = descriptor.get!
    descriptor.get = function (this: Record<string, Type>): Type {
        const propName = `${propertyName}_memoized`
        if (this[propName] === undefined) {
            // Define the prop the long way so we don't enumerate over it
            Object.defineProperty(this, propName, {
                configurable: false,
                enumerable: false,
                writable: false,
                value: originalFn.apply(this),
            })
        }
        return this[propName]
    }
}
 
export const appendRowsToColumnStore = (
    columnStore: CoreColumnStore,
    rows: CoreRow[]
): CoreColumnStore => {
    const slugs = Object.keys(columnStore)
    const newColumnStore = columnStore
    slugs.forEach((slug) => {
        newColumnStore[slug] = columnStore[slug].concat(
            rows.map((row) => row[slug])
        )
    })
    return newColumnStore
}
 
const getColumnStoreLength = (store: CoreColumnStore): number => {
    return max(values(store).map((v) => v.length)) ?? 0
}
 
export const concatColumnStores = (
    stores: CoreColumnStore[],
    slugsToKeep?: ColumnSlug[]
): CoreColumnStore => {
    if (!stores.length) return {}
 
    const lengths = stores.map(getColumnStoreLength)
    const slugs = slugsToKeep ?? Object.keys(first(stores)!)
 
    const newColumnStore: CoreColumnStore = {}
    slugs.forEach((slug) => {
        newColumnStore[slug] = flatten(
            stores.map((store, i) => {
                const values = store[slug] ?? []
                const toFill = Math.max(0, lengths[i] - values.length)
                if (toFill === 0) {
                    return values
                } else {
                    return values.concat(
                        new Array(lengths[i] - values.length).fill(
                            ErrorValueTypes.MissingValuePlaceholder
                        )
                    )
                }
            })
        )
    })
    return newColumnStore
}
 
export const rowsToColumnStore = (rows: CoreRow[]): CoreColumnStore => {
    const columnsObject: CoreColumnStore = {}
    if (!rows.length) return columnsObject
 
    Object.keys(rows[0]).forEach((slug) => {
        columnsObject[slug] = rows.map((row) => row[slug])
    })
    return columnsObject
}
 
const guessColumnDefsFromRows = (
    rows: CoreRow[],
    definedSlugs: Map<ColumnSlug, any>
): CoreColumnDef[] => {
    if (!rows[0]) return []
    return Object.keys(rows[0])
        .filter((slug) => !definedSlugs.has(slug))
        .map((slug) => {
            const firstRowWithValue = rows.find(
                (row) =>
                    row[slug] !== undefined &&
                    row[slug] !== null &&
                    row[slug] !== ""
            )
            const firstValue = firstRowWithValue
                ? firstRowWithValue[slug]
                : undefined

            return guessColumnDefFromSlugAndRow(slug, firstValue)
        })
}
 
export const autodetectColumnDefs = (
    rowsOrColumnStore: CoreColumnStore | CoreRow[],
    definedSlugs: Map<ColumnSlug, any>
): CoreColumnDef[] => {
    if (!Array.isArray(rowsOrColumnStore)) {
        const columnStore = rowsOrColumnStore as CoreColumnStore
        return Object.keys(columnStore)
            .filter((slug) => !definedSlugs.has(slug))
            .map((slug) => {
                return guessColumnDefFromSlugAndRow(
                    slug,
                    columnStore[slug].find(
                        (val) => val !== undefined && val !== null
                    )
                )
            })
    }
    return guessColumnDefsFromRows(rowsOrColumnStore, definedSlugs)
}
 
// Convenience method when you are replacing columns
export const replaceDef = <ColumnDef extends CoreColumnDef>(
    defs: ColumnDef[],
    newDefs: ColumnDef[]
): ColumnDef[] =>
    defs.map((def) => {
        const newDef = newDefs.find((newDef) => newDef.slug === def.slug)
        return newDef ?? def
    })
 
export const reverseColumnStore = (
    columnStore: CoreColumnStore
): CoreColumnStore => {
    const newStore: CoreColumnStore = {}
    Object.keys(columnStore).forEach((slug) => {
        newStore[slug] = columnStore[slug].slice().reverse()
    })
    return newStore
}
 
export const renameColumnStore = (
    columnStore: CoreColumnStore,
    columnRenameMap: { [columnSlug: string]: ColumnSlug }
): CoreColumnStore => {
    const newStore: CoreColumnStore = {}
    Object.keys(columnStore).forEach((slug) => {
        if (columnRenameMap[slug])
            newStore[columnRenameMap[slug]] = columnStore[slug]
        else newStore[slug] = columnStore[slug]
    })
    return newStore
}
 
export const replaceCells = (
    columnStore: CoreColumnStore,
    columnSlugs: ColumnSlug[],
    replaceFn: (val: CoreValueType) => CoreValueType
): CoreColumnStore => {
    const newStore: CoreColumnStore = { ...columnStore }
    columnSlugs.forEach((slug) => {
        newStore[slug] = newStore[slug].map(replaceFn)
    })
    return newStore
}
 
// Returns a Set of random indexes to drop in an array, preserving the order of the array
export const getDropIndexes = (
    arrayLength: number,
    howMany: number,
    seed = Date.now()
): Set<number> => new Set(sampleFrom(range(0, arrayLength), howMany, seed))
 
export const replaceRandomCellsInColumnStore = (
    columnStore: CoreColumnStore,
    howMany = 1,
    columnSlugs: ColumnSlug[] = [],
    seed = Date.now(),
    replacementGenerator: () => any = () => ErrorValueTypes.DroppedForTesting
): CoreColumnStore => {
    const newStore: CoreColumnStore = Object.assign({}, columnStore)
    columnSlugs.forEach((slug) => {
        const values = newStore[slug]
        const indexesToDrop = getDropIndexes(values.length, howMany, seed)
        newStore[slug] = values.map((value, index) =>
            indexesToDrop.has(index) ? replacementGenerator() : value
        )
    })
    return newStore
}
 
export class Timer {
    constructor() {
        this._tickTime = Date.now()
        this._firstTickTime = this._tickTime
    }
 
    private _tickTime: number
    private _firstTickTime: number
 
    tick(msg?: string): number {
        const elapsed = Date.now() - this._tickTime
        // eslint-disable-next-line no-console
        if (msg) console.log(`${elapsed}ms ${msg}`)
        this._tickTime = Date.now()
        return elapsed
    }
 
    getTotalElapsedTime(): number {
        return Date.now() - this._firstTickTime
    }
}
 
export const rowsFromMatrix = (matrix: CoreMatrix): any[] => {
    const table = trimMatrix(matrix)
    const header = table[0]
    return table.slice(1).map((row) => {
        const newRow: any = {}
        header.forEach((col, index) => {
            newRow[col] = row[index]
        })
        return newRow
    })
}
 
const trimEmptyColumns = (matrix: CoreMatrix): CoreMatrix =>
    matrix.map(trimArray)
export const trimMatrix = (matrix: CoreMatrix): CoreMatrix =>
    trimEmptyColumns(trimEmptyRows(matrix))
 
export const matrixToDelimited = (
    table: CoreMatrix,
    delimiter = "\t"
): string => {
    return table
        .map((row: any) =>
            row
                .map((cell: any) =>
                    cell === null || cell === undefined ? "" : cell
                )
                .join(delimiter)
        )
        .join("\n")
}
 
export const parseDelimited = (
    str: string,
    delimiter?: string,
    parseFn?: any
): DSVParsedArray<Record<string, unknown>> =>
    dsvFormat(delimiter ?? detectDelimiter(str)).parse(str, parseFn)
 
export const detectDelimiter = (str: string): "\t" | "," | " " =>
    str.includes("\t") ? "\t" : str.includes(",") ? "," : " "
 
export const rowsToMatrix = (rows: any[]): CoreMatrix | undefined =>
    rows.length
        ? [Object.keys(rows[0]), ...rows.map((row) => Object.values(row))]
        : undefined
 
const isRowEmpty = (row: any[]): boolean => row.every(isCellEmpty)
 
export const isCellEmpty = (cell: any): boolean =>
    cell === null || cell === undefined || cell === ""
 
export const trimEmptyRows = (matrix: CoreMatrix): CoreMatrix => {
    let trimAt = undefined
    for (let rowIndex = matrix.length - 1; rowIndex >= 0; rowIndex--) {
        if (!isRowEmpty(matrix[rowIndex])) break
        trimAt = rowIndex
    }
    return trimAt === undefined ? matrix : matrix.slice(0, trimAt)
}
 
export const trimArray = (arr: any[]): any[] => {
    let rightIndex: number
    for (rightIndex = arr.length - 1; rightIndex >= 0; rightIndex--) {
        if (!isCellEmpty(arr[rightIndex])) break
    }
    return arr.slice(0, rightIndex + 1)
}
 
export function cartesianProduct<T>(...allEntries: T[][]): T[][] {
    return fastCartesian(allEntries)
}
 
const applyNewSortOrder = (arr: any[], newOrder: number[]): any[] =>
    newOrder.map((index) => arr[index])
 
export const sortColumnStore = (
    columnStore: CoreColumnStore,
    slugs: ColumnSlug[]
): CoreColumnStore => {
    const firstCol = Object.values(columnStore)[0]
    if (!firstCol) return {}
    const len = firstCol.length
    const newOrder = range(0, len).sort(makeSortByFn(columnStore, slugs))
    const newStore: CoreColumnStore = {}
    Object.keys(columnStore).forEach((slug) => {
        newStore[slug] = applyNewSortOrder(columnStore[slug], newOrder)
    })
    return newStore
}
 
const makeSortByFn = (
    columnStore: CoreColumnStore,
    columnSlugs: ColumnSlug[]
): ((indexA: number, indexB: number) => 1 | 0 | -1) => {
    const numSlugs = columnSlugs.length
    return (indexA: number, indexB: number): 1 | 0 | -1 => {
        const nodeAFirst = -1
        const nodeBFirst = 1
 
        for (let slugIndex = 0; slugIndex < numSlugs; slugIndex++) {
            const slug = columnSlugs[slugIndex]
            const col = columnStore[slug]
            const av = col[indexA]
            const bv = col[indexB]
            if (av < bv) return nodeAFirst
            if (av > bv) return nodeBFirst
            // todo: handle ErrorValues
        }
        return 0
    }
}
 
export const emptyColumnsInFirstRowInDelimited = (str: string): string[] => {
    // todo: don't split a big string here, just do a faster first line scan
    const shortCsv = parseDelimited(str.split("\n").slice(0, 2).join("\n"))
    const firstRow: any = shortCsv[0] ?? {}
    const emptySlugs: string[] = []
    Object.keys(firstRow).forEach((slug) => {
        if (firstRow[slug] === "") emptySlugs.push(slug)
    })
    return emptySlugs
}