Created
July 31, 2020 22:11
-
-
Save johnsogg/0a704e0d359f87febb2fd9d7d3cabece to your computer and use it in GitHub Desktop.
ID Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// id_map.ts | |
// | |
// Convert an array of objects T that have a string ID to a | |
// Record<string, T>. | |
export type Identifiable = { | |
id: string; | |
}; | |
export type IDMap<T> = { | |
[key: string]: T; | |
}; | |
export const toIDMap = <T extends Identifiable>(data: T[]) => { | |
return data.reduce((acc, val) => { | |
acc[val.id] = val; | |
return acc; | |
}, {} as IDMap<T>); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { toIDMap } from "./id_map"; | |
interface Point { | |
id: string; | |
x: number; | |
y: number; | |
} | |
it("converts an array of things to a Record dictionary", () => { | |
const data: Point[] = [ | |
{ id: "one", x: 10, y: 20 }, | |
{ id: "two", x: 20, y: 40 }, | |
{ id: "three", x: 30, y: 80 }, | |
{ id: "two", x: 99, y: 999 } | |
]; | |
const xfm = toIDMap(data); | |
expect(Object.keys(xfm).length).toBe(3); | |
expect(xfm["one"].x).toBe(10); | |
expect(xfm["two"].y).toBe(999); // because dupe keys not ok, this comes later | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment