Proposal: Map#assign

森建 moriken at kimamass.com
Thu Jan 18 17:28:10 UTC 2018


Hi there,

I want to add `Map#assign` to TC39 Stage 1.

ECMAScript `Object` has `Object.assign`.
On the other hand `Map` doesn't have assigning method.

For example, we must write JavaScript like the following:

```js
const mapA = new Map([["foo", 1], ["bar", 2]]);
const mapB = new Map([["baz", 3], ["foo", 4]]);
const mapC = new Map([["baz", 5], ["foo", 6], ["hoge", 7]]);
```

```js
for (const [key, value] of mapB) {
   mapA.set(key, value);
}
for (const [key, value] of mapC) {
   mapA.set(key, value);
}

// Map(4) {"foo" => 6, "bar" => 2, "baz" => 5, "hoge" => 7}
console.log(mapA);
```

This code is redundant. I just want to write `mapA.assign(mapB, mapC);`.

## More Detail

Implementation example:

```js
Map.prototype.assign = function(...args) {
   // validation
   if (typeof this !== "object") { throw new TypeError; }
   if (this doesn't have [[MapData]] internal slot) { throw new TypeError; }
   for (const arg of args) {
     if (typeof arg !== "object") { throw new TypeError; }
     if (arg doesn't have [[MapData]] internal slot) { throw new TypeError; }
   }

   // iterate and set
   for (const map of args) {
     for (const [key, value] of map) {
       this.set(key, value);
     }
   }
}
```



More information about the es-discuss mailing list