From 6310540deae1a5e05d46767a35d8ec32865f2c33 Mon Sep 17 00:00:00 2001 From: Dave Coates Date: Tue, 16 Feb 2016 21:06:27 +1100 Subject: [PATCH] Add support for flatmap --- src/list.js | 19 +++++++++++++++++++ src/test/list.js | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/list.js b/src/list.js index 53722e4..84c0783 100644 --- a/src/list.js +++ b/src/list.js @@ -275,6 +275,25 @@ class TypedList extends BaseTypeInferedList { } } } + flatMap(mapper, context) { + if (this.size === 0) { + return this + } else { + const result = TypeInferedList.from(this).flatMap(mapper, context) + if (this[$store] === result[$store]) { + return this + } + if (result[$type] === this[$type]) { + const list = construct(this) + list[$store] = result[$store] + list.size = result.size + return list + } else { + return result + } + } + } + } export const List = function(descriptor, label) { diff --git a/src/test/list.js b/src/test/list.js index f623fbc..eebc71e 100644 --- a/src/test/list.js +++ b/src/test/list.js @@ -985,3 +985,22 @@ test('empty list optimization', assert => { assert.equal(Points([Point({x: 1})]).clear(), Points([Point({x: 1}), Point({y: 2})]).clear()) }) + +test('flatMap', assert => { + var numbers = NumberList.of(97, 98, 99); + var letters = numbers.flatMap(v => Immutable.fromJS([ + String.fromCharCode(v), + String.fromCharCode(v).toUpperCase(), + ])) + + assert.deepEqual(letters.toArray(), ['a','A','b','B','c','C']) + + var letters = numbers.flatMap(v => [ + String.fromCharCode(v), + String.fromCharCode(v).toUpperCase(), + ]) + + assert.deepEqual(letters.toArray(), ['a','A','b','B','c','C']) + +}) +