Skip to content

Allow Map to be initialized with an iterable #2940

Description

@pebrianz

Feature suggestion

Right now, to create a map and fill it with data, we have to do it in two steps: first create an empty map, then add each item one by one with .set().

This is what our code currently looks like:

let map = new Map<string, i32>();
map.set('a', 1);
map.set('b', 2);

This works, but it can get a bit long and clunky, especially for a lot of data.

My suggestion is to allow the Map constructor to accept an array of key-value pairs. This would let us create and populate a map in a single, clean line of code.

Here's an example of what that would look like:

let map = new Map<string, i32>([
  ['a', 1],
  ['b', 2]
]);

This change would make our code much cleaner and easier to read, and it's a common pattern in other languages like JavaScript and typescript.

because assemblyscript not support mixed type like [K, V], we use entry object instead:

let map = new Map<string, i32>([
  {key: "a", value: 1},
  {key: "a", value: 2}
]}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions