Skip to content

Instantly share code, notes, and snippets.

@johnsogg
Created July 31, 2020 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnsogg/0a704e0d359f87febb2fd9d7d3cabece to your computer and use it in GitHub Desktop.
Save johnsogg/0a704e0d359f87febb2fd9d7d3cabece to your computer and use it in GitHub Desktop.
ID Map
// 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>);
};
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