• Stars
    star
    176
  • Rank 216,987 (Top 5 %)
  • Language
    HTML
  • License
    MIT License
  • Created about 5 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ECMAScript Proposal, specs, and reference implementation for Map.prototype.upsert

Map.prototype.emplace

ECMAScript proposal and reference implementation for Map.prototype.emplace.

Author: Brad Farias (GoDaddy)

Champion: Erica Pramer (GoDaddy)

Stage: 2

Motivation

Adding and updating values of a Map are tasks that developers often perform in conjunction. There are currently no Map prototype methods for either of those two things, let alone a method that does both. The workarounds involve multiple lookups and developer inconvenience while avoiding encouraging code that is surprising or is potentially error prone.

Solution: emplace

We propose the addition of a method that will add a value to a map if the map does not already have something at key, and will also update an existing value at key. It’s worthwhile having this API for the average case to cut down on lookups. It is also worthwhile for developer convenience and expression of intent.

Examples & Proposed API

The following examples would all be optimized and made simpler by emplace. The proposed API allows a developer to do one lookup and update in place:

// given counts is a Map of object => id
counts.emplace(key, {
  insert(key, map) {
    return 0;
  },
  update(existing, key, map) {
    return existing + 1;
  }
});

Normalization of values during insertion

Currently you would need to do 3 lookups:

if (!map.has(key)) {
  map.set(key, value);
}
map.get(key).doThing();

With this proposal:

map.emplace(key, {
  insert: () => value
}).doThing();

Either update or insert for a specific key

You might get new data and want to calculate some aggregate if the key exists, but just insert if it's the first value at that key.

// two lookups
old = map.get(key);
if (!old) {
  map.set(key, value);
} else {
  map.set(key, updated);
}

With this proposal:

map.emplace(key, {
  update: () => updated,
  insert: () => value
});

Just insert if missing

You might omit an update if you're handling data that doesn't change, but can still be appended.

// two lookups
if (!map1.has(key)) {
  map1.set(key, value);
}

With this proposal:

map.emplace(key, {
  insert: () => value
});

Just update if present

You might want to omit an insert if you want to perform a function on all existing values in a Map (ex. normalization).

// three lookups
if (map.has(key)) {
  old = map.get(key);
  updated = old.doThing();
  map.set(key, updated);
}

With this proposal:

if (map.has(key)) {
  map.emplace(key, {
    update: (old) => old.doThing()
  });
}

Implementations in other languages

Similar functionality exists in other languages.

Java

C++

  • emplace inserts if missing
  • map[] assignment opts inserts if missing at key but also returns a value if it exists at key
  • insert_or_assign inserts if missing. updates existing value by replacing with a specific new one, not by applying a function to the existing value

Rust

  • and_modify Provides in-place mutable access to an occupied entry
  • or_insert_with inserts if empty. insertion value comes from a mapping function

Python

Elixir

  • Map.update/4 Updates the item with given function if key exists, otherwise inserts given initial value

FAQ

Is the goal to simplify the API or to optimize it?

  • This proposal seeks to simplify expressing intent for programmers, and should ease optimization without complex analysis. For engines without complex analysis like IOT VMs this should see wins by avoiding multiple entry lookups, at potential call stack cost.

Why not use existing JS engines that optimize by coalescing the lookup and mutation?

  • This does not cover all patterns (of which there are many), things such as ordering can cause the optimization to fail.
if (!x.has(a)) x.set(a, []);
if (!y.has(b)) y.set(b, []);
x.get(a).push(1);
y.get(b).push(2);

Why error if the key doesn't exist and no insert handler is provided.

  • This keeps the return type constrained to the union of insert and update without adding undefined. This alleviates a variety of static checker errors from code such as the following.
// map is a Map of object values
let x;
if (map.has(key)) {
  x = map.get(key); // can return undefined
} else {
  x = {};
  map.set(key, x);
}
// x's type is `undefined | object` 

The proposal could guarantee that the type does not include undefined:

// map is a Map of object values
let x = map.emplace(key, {
  insert: () => { return {}; }
});
// x's type is `object`

Why not have a single function that has a boolean if performing an update and the potentially existing value?

  • By naming the handlers, you can increase readability and reduce overall boilerplate. Additionally, generally there are not common workflows that have code paths that cover both updating and insertion. See the following which only seeks to insert a value if none exists:
x = map.emplace(key, (updating, value) => updating ? value : []);

The proposal allows a handler to avoid the boilerplate condition and focus only on the relevant workflows:

x = map.emplace(key, {
  insert: () => []
});

Why not have a single function that inserts the value if no such key is mapped?

  • By only having a single function that inserts a variety of workflows become less clear. In particular, by only having insert, a usage of a default value must be inserted with an anti-update operation already applied.
// have to set the default value to -1, not 0
const n = counts.emplace(key, () => -1);
// have to perform an additional set afterwards
counts.set(key, n + 1);

The proposal allows a handler to avoid the odd default value and avoid the extra .set. This does still require coding logic for both, but keeps the intent more readable and localized.

counts.emplace(key, {
  insert: () => 0,
  update: (v) => v + 1
});
  • This can also lead to insertion of values that are incomplete/invalid regarding the intended type of the Map:
updateNameOf(key) {
  // contacts only has objects which must have a string value
  const contact = contacts.insert(key, () => ({name:null}));
  // inserted and can be assured of same reference on .get
  contact.name = getName();
  // if getName throws, contact is incomplete/invalid
  // .name remains null
}

This can be rewritten to be less error prone by moving getName above

updateNameOf(key) {
  const name = getName();
  const contact = contacts.insert(key, () => ({name:null}));
  contact.name = name;
}

This code is less error prone (unless contact.name fails assignment for example), but it still has an invalid value being inserted into the map.

This can again be rewritten to be less constraint breaking by avoiding insert() entirely.

updateNameOf(key) {
  const name = getName();
  const existing = contacts.get(key) ?? {name:null};
  contact.name = name;
  contacts.set(key);
}

This design does avoid ever inserting the invalid value into the map, but is a bit confusing to read. This proposal by combining update and insert can be a little clearer:

updateNameOf(key, name) {
  const name = getName();
  contacts.emplace(key, {
    insert: () => ({name}),
    update: (contact) => {
      contact.name = name;
      return contact;
    }
  });
}

by having both operations co-located it would feel odd to try and getName after .emplace and no invalid value is inserted into the map.

Why not have a single function that updates the value if no if the key is mapped?

  • By only having a single function that updates a variety of workflows become less clear. In particular in order to guarantee that the result type is not a union with undefined it should error if the key is not mapped.
let n;
try {
  n = counts.emplace(key, (existing) => existing + 1);
} catch (e) {
  // this is a fragile detection and quite hard to determine it was
  // counts.emplace that caused an error, and not something internal to
  // the update callback
  if (e instanceof MissingEntryError) {
    counts.set(key, n = 0);
  }
}
if (n > RETRIES) {
  // ...
}

A alteration to return a boolean to see if an action is taken requires boilerplate and reduces the utility of the return value:

let updated = counts.emplace(key, (existing) => existing + 1);
if (!updated) {
  counts.set(key, 0);
}
let n = counts.get(key);
if (n > RETRIES) {
  // ...
}

The proposal allows a handler to avoid the odd default value and avoid the extra .set.

let n = counts.emplace(key, {
  insert: () => 0,
  update: (v) => v + 1
});
if (n > RETRIES) {
  // ...
}

Why not have an API that exposes an Entry to collection types?

  • An Entry API is not prevented by this proposal. Explicit thought about re-entrancy was taken into consideration and was designed not to conflict with such an API. Desires for such an API should be done in a separate proposal.
  • An Entry API has much stricter implications on how implementations must store the backing data for a collection due to creating persistent references.
  • An Entry API is extremely complex regarding shared mutability and should be considered to be an extreme increase in scope to the goals of this proposal. See complexity such as the following about needing to think of an design an entire lifecycle and sharing scheme for multiple entry references:
let entry1 = map.mutableEntry(key);
let entry2 = map.mutableEntry(key);
entry2.remove();
entry1.insertIfMissing(0);

Why use functions instead of values for the parameters?

  • You may want to apply a factory function when inserting to avoid costs of potentially heavy allocation, or the key may be determined at insertion time.
// an example of when eager allocation of the value
// is undesirable
const sharedRequests = new Map();
function request(url) {
  return sharedRequests.emplace(url, {
    insert: () => {
      return fetch(url).then(() => {
        sharedRequests.delete(url);
      });
    }
  });
}
  • When updating, we will be able to perform a function on the existing value instead of just replacing the value. The action may also cause mutation or side-effects, which would want to be avoided if not updating.
const eventCounts = new Map();
obj.onevent(
  (eventName) => {
    // this API allows working with value type and primitive values
    eventCounts.emplace(eventName, {
      update: (n) => n + 1,
      insert: () => 1
    });
  }
);

This is important as primitives like BigInt, [Records, and Tuples](Records and Tuples), etc. are added to the language. This API should continue to be able to handle and work with such values as they are added.

Why are we calling this emplace?

  • updateOrInsert and insertOrUpdate seem too wordy.
    • in the case that only an insert operation is provided it may do neither update nor insert.
  • upsert was seen as too unique a term and the ordering was problematic as there was a desire to focus on insertion.
    • It is a combination of "update" & "insert" that is already used in other programming situations and many SQL variants use that exact term.
  • emplace matches a naming precedent from C++.

What happens during re-entrancy?

  • Other methods like Array methods while iterating using a higher order function do not re-iterate if mutated in a re-entrant manner. This method will modify the underlying storage cell that contains the existing value and any mutation of the map will act on new storage cells if that cell is removed from the map. This method will not perform a second lookup if the storage cell in the collection for the key is replaced with a new one.
  • See issue #9 for more.

Specification

Polyfill

A polyfill is available in the core-js library. You can find it in the ECMAScript proposals section.

More Repositories

1

proposals

Tracking ECMAScript Proposals
17,177
star
2

ecma262

Status, process, and documents for ECMA-262
HTML
14,437
star
3

proposal-pipeline-operator

A proposal for adding a useful pipe operator to JavaScript.
HTML
7,534
star
4

proposal-pattern-matching

Pattern matching syntax for ECMAScript
HTML
5,498
star
5

proposal-optional-chaining

HTML
4,942
star
6

proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
JavaScript
4,252
star
7

proposal-signals

A proposal to add signals to JavaScript.
3,387
star
8

proposal-temporal

Provides standard objects and functions for working with dates and times.
HTML
3,321
star
9

proposal-observable

Observables for ECMAScript
JavaScript
3,058
star
10

proposal-decorators

Decorators for ES6 classes
2,640
star
11

proposal-record-tuple

ECMAScript proposal for the Record and Tuple value types. | Stage 2: it will change!
HTML
2,496
star
12

test262

Official ECMAScript Conformance Test Suite
JavaScript
2,073
star
13

proposal-dynamic-import

import() proposal for JavaScript
HTML
1,863
star
14

proposal-bind-operator

This-Binding Syntax for ECMAScript
1,742
star
15

proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
HTML
1,722
star
16

proposal-async-await

Async/await for ECMAScript
HTML
1,578
star
17

proposal-object-rest-spread

Rest/Spread Properties for ECMAScript
HTML
1,493
star
18

proposal-shadowrealm

ECMAScript Proposal, specs, and reference implementation for Realms
HTML
1,429
star
19

proposal-iterator-helpers

Methods for working with iterators in ECMAScript
HTML
1,307
star
20

proposal-nullish-coalescing

Nullish coalescing proposal x ?? y
HTML
1,232
star
21

proposal-top-level-await

top-level `await` proposal for ECMAScript (stage 4)
HTML
1,083
star
22

proposal-partial-application

Proposal to add partial application to ECMAScript
HTML
1,002
star
23

proposal-do-expressions

Proposal for `do` expressions
HTML
990
star
24

proposal-binary-ast

Binary AST proposal for ECMAScript
961
star
25

agendas

TC39 meeting agendas
JavaScript
952
star
26

proposal-built-in-modules

HTML
891
star
27

proposal-async-iteration

Asynchronous iteration for JavaScript
HTML
857
star
28

proposal-explicit-resource-management

ECMAScript Explicit Resource Management
JavaScript
746
star
29

proposal-set-methods

Proposal for new Set methods in JS
HTML
655
star
30

proposal-string-dedent

TC39 Proposal to remove common leading indentation from multiline template strings
HTML
614
star
31

proposal-operator-overloading

JavaScript
610
star
32

proposal-import-attributes

Proposal for syntax to import ES modules with assertions
HTML
591
star
33

proposal-async-context

Async Context for JavaScript
HTML
587
star
34

proposal-bigint

Arbitrary precision integers in JavaScript
HTML
561
star
35

ecmascript_simd

SIMD numeric type for EcmaScript
JavaScript
540
star
36

ecma402

Status, process, and documents for ECMA 402
HTML
529
star
37

proposal-slice-notation

HTML
523
star
38

proposal-change-array-by-copy

Provides additional methods on Array.prototype and TypedArray.prototype to enable changes on the array by returning a new copy of it with the change.
HTML
511
star
39

notes

TC39 meeting notes
JavaScript
496
star
40

proposal-class-public-fields

Stage 2 proposal for public class fields in ECMAScript
HTML
489
star
41

proposal-iterator.range

A proposal for ECMAScript to add a built-in Iterator.range()
HTML
483
star
42

proposal-decimal

Built-in exact decimal numbers for JavaScript
HTML
477
star
43

proposal-uuid

UUID proposal for ECMAScript (Stage 1)
JavaScript
463
star
44

proposal-module-expressions

HTML
433
star
45

proposal-throw-expressions

Proposal for ECMAScript 'throw' expressions
JavaScript
425
star
46

proposal-UnambiguousJavaScriptGrammar

413
star
47

proposal-weakrefs

WeakRefs
HTML
409
star
48

proposal-array-grouping

A proposal to make grouping of array items easier
HTML
407
star
49

proposal-error-cause

TC39 proposal for accumulating errors
HTML
380
star
50

proposal-cancelable-promises

Former home of the now-withdrawn cancelable promises proposal for JavaScript
Shell
376
star
51

proposal-ecmascript-sharedmem

Shared memory and atomics for ECMAscript
HTML
374
star
52

proposal-module-declarations

JavaScript Module Declarations
HTML
369
star
53

proposal-first-class-protocols

a proposal to bring protocol-based interfaces to ECMAScript users
352
star
54

proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
HTML
351
star
55

proposal-global

ECMAScript Proposal, specs, and reference implementation for `global`
HTML
346
star
56

proposal-private-methods

Private methods and getter/setters for ES6 classes
HTML
345
star
57

proposal-numeric-separator

A proposal to add numeric literal separators in JavaScript.
HTML
330
star
58

proposal-private-fields

A Private Fields Proposal for ECMAScript
HTML
319
star
59

tc39.github.io

Get involved in specifying JavaScript
HTML
318
star
60

proposal-object-from-entries

TC39 proposal for Object.fromEntries
HTML
318
star
61

proposal-promise-allSettled

ECMAScript Proposal, specs, and reference implementation for Promise.allSettled
HTML
314
star
62

proposal-await.ops

Introduce await.all / await.race / await.allSettled / await.any to simplify the usage of Promises
HTML
310
star
63

proposal-regex-escaping

Proposal for investigating RegExp escaping for the ECMAScript standard
JavaScript
309
star
64

proposal-export-default-from

Proposal to add `export v from "mod";` to ECMAScript.
HTML
306
star
65

proposal-logical-assignment

A proposal to combine Logical Operators and Assignment Expressions
HTML
302
star
66

proposal-promise-finally

ECMAScript Proposal, specs, and reference implementation for Promise.prototype.finally
HTML
279
star
67

proposal-json-modules

Proposal to import JSON files as modules
HTML
272
star
68

proposal-asset-references

Proposal to ECMAScript to add first-class location references relative to a module
270
star
69

proposal-cancellation

Proposal for a Cancellation API for ECMAScript
HTML
267
star
70

proposal-promise-with-resolvers

HTML
255
star
71

proposal-string-replaceall

ECMAScript proposal: String.prototype.replaceAll
HTML
253
star
72

proposal-export-ns-from

Proposal to add `export * as ns from "mod";` to ECMAScript.
HTML
242
star
73

proposal-structs

JavaScript Structs: Fixed Layout Objects
230
star
74

proposal-ses

Draft proposal for SES (Secure EcmaScript)
HTML
223
star
75

proposal-intl-relative-time

`Intl.RelativeTimeFormat` specification [draft]
HTML
215
star
76

proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
HTML
214
star
77

proposal-flatMap

proposal for flatten and flatMap on arrays
HTML
214
star
78

proposal-defer-import-eval

A proposal for introducing a way to defer evaluate of a module
HTML
208
star
79

ecmarkup

An HTML superset/Markdown subset source format for ECMAScript and related specifications
TypeScript
201
star
80

proposal-promise-any

ECMAScript proposal: Promise.any
HTML
200
star
81

proposal-optional-chaining-assignment

`a?.b = c` proposal
186
star
82

proposal-decorators-previous

Decorators for ECMAScript
HTML
184
star
83

proposal-smart-pipelines

Old archived draft proposal for smart pipelines. Go to the new Hack-pipes proposal at js-choi/proposal-hack-pipes.
HTML
181
star
84

proposal-array-from-async

Draft specification for a proposed Array.fromAsync method in JavaScript.
HTML
178
star
85

proposal-collection-methods

HTML
171
star
86

proposal-array-filtering

A proposal to make filtering arrays easier
HTML
171
star
87

proposal-ptc-syntax

Discussion and specification for an explicit syntactic opt-in for Tail Calls.
HTML
169
star
88

proposal-extractors

Extractors for ECMAScript
JavaScript
166
star
89

proposal-error-stacks

ECMAScript Proposal, specs, and reference implementation for Error.prototype.stack / System.getStack
HTML
166
star
90

proposal-intl-duration-format

164
star
91

how-we-work

Documentation of how TC39 operates and how to participate
161
star
92

proposal-Array.prototype.includes

Spec, tests, reference implementation, and docs for ESnext-track Array.prototype.includes
HTML
157
star
93

proposal-promise-try

ECMAScript Proposal, specs, and reference implementation for Promise.try
HTML
154
star
94

proposal-extensions

Extensions proposal for ECMAScript
HTML
150
star
95

proposal-hashbang

#! for JS
HTML
148
star
96

proposal-import-meta

import.meta proposal for JavaScript
HTML
146
star
97

proposal-intl-segmenter

Unicode text segmentation for ECMAScript
HTML
146
star
98

proposal-resizablearraybuffer

Proposal for resizable array buffers
HTML
145
star
99

proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
HTML
143
star
100

eshost

A uniform wrapper around a multitude of ECMAScript hosts. CLI: https://github.com/bterlson/eshost-cli
JavaScript
142
star