Skip to content

Instantly share code, notes, and snippets.

@cwharris
Last active November 26, 2016 01:37
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 cwharris/e284d6831830e450673702587696308d to your computer and use it in GitHub Desktop.
Save cwharris/e284d6831830e450673702587696308d to your computer and use it in GitHub Desktop.
TypeScript Array<TItem> => { [key: TKey] }: TItem
import { toKeyedObjectWithNumber } from "./toKeyedObjectWithNumber";
var items = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];
var itemsById = toKeyedObject(items, item => item.id);
console.log(itemsById[2]);
export function toKeyedObject<TItem>(
items: Array<TItem>,
keySelector: (item: TItem) => string) {
return items.reduce(
(items: { [id: string]: TItem }, item: TItem) => {
items[keySelector(item)] = item;
return items;
},
{});
}
export function toKeyedObjectWithNumber<TItem>(
items: Array<TItem>,
keySelector: (item: TItem) => number) {
return items.reduce(
(items: { [id: number]: TItem }, item: TItem) => {
items[keySelector(item)] = item;
return items;
},
{});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment