diff --git a/README.md b/README.md index f679525..02fe06e 100644 --- a/README.md +++ b/README.md @@ -11,17 +11,6 @@ codeclimate

-

- - greenkeeper - - - greenkeeper - - - greenkeeper - -

semantic-release diff --git a/package.json b/package.json index 0d4c929..523c1d9 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,12 @@ "maybe", "result", "either", - "functional" + "list", + "functional", + "list-monad", + "maybe-monad", + "either-monad", + "result-monad" ], "scripts": { "test": "jest", diff --git a/src/list/list.spec.ts b/src/list/list.spec.ts index 855644c..dcf94c3 100644 --- a/src/list/list.spec.ts +++ b/src/list/list.spec.ts @@ -2,8 +2,9 @@ import { List } from './list' import { listFrom } from './list.factory' class Animal { - constructor(public name: string) { } + constructor(public name: string, public nickname?: string) { } } + class Dog extends Animal { dogtag!: string dogyear!: number @@ -228,6 +229,24 @@ describe(List.name, () => { }) }) + describe('ToDictionary', () => { + const Rex = new Dog('Rex', 'Rdawg') + const Meow = new Cat('Meow') + const sut = List.of(Rex, Meow) + + it('should handle nominal keyed case', () => { + expect(sut.toDictionary('name')).toEqual({ Rex, Meow }) + }) + + it('should handle unkeyed', () => { + expect(sut.toDictionary()).toEqual({ 0: Rex, 1: Meow }) + }) + + it('should handle missing keys', () => { + expect(sut.toDictionary('nickname')).toEqual({ Rdawg: Rex }) + }) + }) + // describe('OrderBy', () => { // it('should order by object', () => { // const dog1 = new Dog('Atlas') diff --git a/src/list/list.ts b/src/list/list.ts index af6121e..2dd703b 100644 --- a/src/list/list.ts +++ b/src/list/list.ts @@ -210,6 +210,26 @@ export class List { return this.filter(a => a instanceof type) } + + /** + * Converts the list into an object with numbered indices mathing the array position of the item. + */ + public toDictionary(): { [key: number]: T } + + /** + * Converts the list into an object deriving key from the specified property. + */ + public toDictionary(key: keyof T): { [key: string]: T } + public toDictionary(key?: keyof T): { [key: number]: T } | { [key: string]: T } { + return this.reduce((acc, curr, idx) => { + return key + ? curr[key] + ? { ...acc, [curr[key] as any]: curr } + : acc + : { ...acc, [idx]: curr } + }, {}) + } + // /** // * Sorts the elements of a sequence in ascending order. // */