From d5c1d8439afb474b0531d835cb77755c399ba362 Mon Sep 17 00:00:00 2001 From: Jamie Wong Date: Tue, 16 Jan 2018 22:27:31 -0800 Subject: [PATCH] Add utils, time import more granularly --- application.tsx | 4 ++-- flamechart-view.tsx | 2 ++ utils.ts | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/application.tsx b/application.tsx index b2c0ddc..0055bba 100644 --- a/application.tsx +++ b/application.tsx @@ -159,9 +159,9 @@ export class Application extends ReloadableComponent<{}, ApplicationState> { }) console.timeEnd('import') - console.time('first render') + console.time('first setState') this.setState({ profile, flamechart, sortedFlamechart }, () => { - console.timeEnd('first render') + console.timeEnd('first setState') }) } diff --git a/flamechart-view.tsx b/flamechart-view.tsx index 04f9a81..cd0a3c3 100644 --- a/flamechart-view.tsx +++ b/flamechart-view.tsx @@ -99,6 +99,7 @@ export class FlamechartPanZoomView extends ReloadableComponent { diff --git a/utils.ts b/utils.ts index db2dc1b..7caa2d4 100644 --- a/utils.ts +++ b/utils.ts @@ -15,6 +15,41 @@ export function lastOf(ts: T[]): T | null { return ts[ts.length-1] || null } +export function sortBy(ts: T[], key: (t: T) => number | string): void { + function comparator(a: T, b: T) { + return key(a) < key(b) ? -1 : 1 + } + ts.sort(comparator) +} + +export function getOrInsert(map: Map, k: K, fallback: (k?: K) => V): V { + if (!map.has(k)) map.set(k, fallback(k)) + return map.get(k)! +} + +export function getOrElse(map: Map, k: K, fallback: (k?: K) => V): V { + if (!map.has(k)) return fallback(k) + return map.get(k)! +} + +export function* itMap(it: Iterable, f: (t: T) => U): Iterable { + for (let t of it) { + yield f(t) + } +} + +export function itForEach(it: Iterable, f: (t: T) => void): void { + for (let t of it) { f(t) } +} + +export function itReduce(it: Iterable, f: (a: U, b: T) => U, init: U): U { + let accum: U = init + for (let t of it) { + accum = f(accum, t) + } + return accum +} + // NOTE: This blindly assumes the same result across contexts. const measureTextCache = new Map() export function cachedMeasureTextWidth(ctx: CanvasRenderingContext2D, text: string): number {