Last active
November 26, 2016 01:37
-
-
Save cwharris/e284d6831830e450673702587696308d to your computer and use it in GitHub Desktop.
TypeScript Array<TItem> => { [key: TKey] }: TItem
This file contains hidden or 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 { toKeyedObjectWithNumber } from "./toKeyedObjectWithNumber"; | |
var items = [ | |
{ id: 1 }, | |
{ id: 2 }, | |
{ id: 3 } | |
]; | |
var itemsById = toKeyedObject(items, item => item.id); | |
console.log(itemsById[2]); |
This file contains hidden or 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
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; | |
}, | |
{}); | |
} |
This file contains hidden or 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
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