From e53c01c6c5fb3b9b93a05ff7d6881c8e580b91a0 Mon Sep 17 00:00:00 2001 From: Duane Johnson Date: Sun, 7 Jun 2020 07:44:37 -0600 Subject: [PATCH] Add 'size' getter to Y.Map --- src/types/YMap.js | 11 ++++++++++- tests/y-map.tests.js | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/types/YMap.js b/src/types/YMap.js index b3d7fd95..47df69ad 100644 --- a/src/types/YMap.js +++ b/src/types/YMap.js @@ -115,6 +115,15 @@ export class YMap extends AbstractType { return map } + /** + * Returns the size of the YMap (count of key/value pairs) + * + * @return {number} + */ + get size () { + return [...createMapIterator(this._map)].length + } + /** * Returns the keys for each element in the YMap Type. * @@ -143,7 +152,7 @@ export class YMap extends AbstractType { } /** - * Executes a provided function on once on overy key-value pair. + * Executes a provided function on once on every key-value pair. * * @param {function(T,string,YMap):void} f A function to execute on every element of this YArray. */ diff --git a/tests/y-map.tests.js b/tests/y-map.tests.js index f17fa746..ab8043d7 100644 --- a/tests/y-map.tests.js +++ b/tests/y-map.tests.js @@ -60,6 +60,7 @@ export const testBasicMapTests = tc => { t.assert(map0.get('boolean1') === true, 'client 0 computed the change (boolean)') t.compare(map0.get('object'), { key: { key2: 'value' } }, 'client 0 computed the change (object)') t.assert(map0.get('y-map').get('y-array').get(0) === -1, 'client 0 computed the change (type)') + t.assert(map0.size === 6, 'client 0 map has correct size') users[2].connect() testConnector.flushAllMessages() @@ -70,6 +71,7 @@ export const testBasicMapTests = tc => { t.assert(map1.get('boolean1') === true, 'client 1 computed the change (boolean)') t.compare(map1.get('object'), { key: { key2: 'value' } }, 'client 1 received the update (object)') t.assert(map1.get('y-map').get('y-array').get(0) === -1, 'client 1 received the update (type)') + t.assert(map1.size === 6, 'client 1 map has correct size') // compare disconnected user t.assert(map2.get('number') === 1, 'client 2 received the update (number) - was disconnected') @@ -157,6 +159,20 @@ export const testGetAndSetOfMapPropertyWithConflict = tc => { compare(users) } +/** + * @param {t.TestCase} tc + */ +export const testSizeAndDeleteOfMapProperty = tc => { + const { map0 } = init(tc, { users: 1 }) + map0.set('stuff', 'c0') + map0.set('otherstuff', 'c1') + t.assert(map0.size === 2, `map size is ${map0.size} expected 2`) + map0.delete('stuff') + t.assert(map0.size === 1, `map size after delete is ${map0.size}, expected 1`) + map0.delete('otherstuff') + t.assert(map0.size === 0, `map size after delete is ${map0.size}, expected 0`) +} + /** * @param {t.TestCase} tc */