diff --git a/src/types/YMap.js b/src/types/YMap.js index 47df69ad..1e675744 100644 --- a/src/types/YMap.js +++ b/src/types/YMap.js @@ -155,18 +155,21 @@ export class YMap extends AbstractType { * 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. + * @returns {Object} */ forEach (f) { - /** - * @type {Object} - */ - const map = {} - for (const [key, item] of this._map) { - if (!item.deleted) { - f(item.content.getContent()[item.length - 1], key, this) + if (this.doc !== null) { + for (const [key, item] of this._map) { + if (!item.deleted) { + f(item.content.getContent()[item.length - 1], key, this) + } + } + } else { + for (const [key, item] of /** @type {Map} */ (this._prelimContent)) { + f(item, key, this) } } - return map + return {} } /** @@ -215,7 +218,11 @@ export class YMap extends AbstractType { * @return {T|undefined} */ get (key) { - return /** @type {any} */ (typeMapGet(this, key)) + if (this.doc !== null) { + return /** @type {any} */ (typeMapGet(this, key)) + } else { + return /** @type {Map} */ (this._prelimContent).get(key) + } } /** @@ -225,7 +232,11 @@ export class YMap extends AbstractType { * @return {boolean} */ has (key) { - return typeMapHas(this, key) + if (this.doc !== null) { + return typeMapHas(this, key) + } else { + return /** @type {Map} */ (this._prelimContent).has(key) + } } /** diff --git a/tests/y-map.tests.js b/tests/y-map.tests.js index 2c3d128a..09c2665a 100644 --- a/tests/y-map.tests.js +++ b/tests/y-map.tests.js @@ -83,6 +83,35 @@ export const testBasicMapTests = tc => { compare(users) } +export const testMapPrelimGetAndHas = () => { + const map = new Y.Map(Object.entries({ number: 1 })) + t.assert(map.get('number') === 1, 'get numbershould retrieve prelim value') + t.assert(map.has('number') === true, 'has number should be true for prelim value') +} + +export const testMapPrelimForEach = () => { + const map = new Y.Map(Object.entries({ + number: 1, + string: 'test', + map: new Y.Map(Object.entries({ boolean: true })) + })) + + /** + * @type {Function[]} + */ + const assertions = [ + (/** @type {string} */ key, /** @type {number} */ value) => { t.assert(key === 'number' && value === 1, "map.forEach on prelim should have key 'number' === 1") }, + (/** @type {string} */ key, /** @type {string} */ value) => { t.assert(key === 'string' && value === 'test', "map.forEach on prelim should have key 'string' === 'test'") }, + (/** @type {string} */ key, /** @type {any} */ value) => { t.assert(key === 'map' && value.get('boolean') === true, "map.forEach on prelim should have key 'map' and have a 'boolean' key that is true") } + ] + let i = 0 + map.forEach((value, key) => { + assertions[i](key, value) + i++ + }) + t.assert(i === 3, `forEach iterates over all 3 prelim keys (${i} iterations)`) +} + /** * @param {t.TestCase} tc */