yjs / yjs

Shared data types for building collaborative software
https://docs.yjs.dev
Other
16.27k stars 593 forks source link

Accept iterator as Y.Map() constructor param #206

Closed canadaduane closed 4 years ago

canadaduane commented 4 years ago

Y.Map is nearly identical to Map in its method signatures. I've been using new Map(Object.entries({ x, y z })) as a way to initialize a regular Map, and thought it would be handy if this also worked for Y.Map:

const pos = { x: 10, y: 10, z: 100 }
const ymap = new Y.Map(Object.entries(pos))

Without this parameter, I think the only way to set a Y.Map value is to call set multiple times:

const pos = { x: 10, y: 10, z: 100 }
const ymap = new Y.Map()
ymap.set('x', pos.x)
ymap.set('y', pos.y)
ymap.set('z', pos.z)

Another feature of the regular Map is the ability to merge values from two Maps on initialization:

let first = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
])

let second = new Map([
  [1, 'uno'],
  [2, 'dos']
])

// Merge two maps. The last repeated key wins.
// Spread operator essentially converts a Map to an Array
let merged = new Map([...first, ...second])

Would it make sense to mimic this behavior for Y.Map also?

Huly®: YJS-159

dmonad commented 4 years ago

Sure, I think that makes a lot of sense. The plan was always to mimic the JavaScript default types. So the argument should work exactly as defined by the EcmaScript spec. I expect that Map accepts any kind of iterable object.

I think i can work on this next week, but if anyone is interested this would also be a good first issue :)