Skip to content

Instantly share code, notes, and snippets.

@joliss
Last active September 14, 2015 20:14
Show Gist options
  • Select an option

  • Save joliss/f6ee03a4fe6f03588f34 to your computer and use it in GitHub Desktop.

Select an option

Save joliss/f6ee03a4fe6f03588f34 to your computer and use it in GitHub Desktop.

JavaScript is currently lacking user-defined types with "value semantics", by which I mean

  • equality and comparison are by value, not by object identity (this includes usage as keys in Map/Set), and
  • assignment creates a copy.

Some use cases not yet covered by Niko's ValueType proposal:

  1. Value semantics for mutable types (https://gist.github.com/joliss/7ca89af5947ddf7c9f57)

  2. Value semantics for variable-sized (heap-allocated) objects. Examples:

    • Python's tuples: (1, 2, 3) == (1, 2, 3)
    • C++'s std::vector<T>: vector<int>{1, 2, 3} == vector<int>{1, 2, 3}
    • As a real-world example where this is needed, Git's internal objects have value semantics (they form a Merkle tree) but are variable-sized: commit objects conceptually have a variable-sized parentCommits array, and tree objects (representing a directory and its contents, recursively) have a variable-sized directoryEntries map.
  3. Dynamic typing:

    • Python is dynamic at run-time: ('foo', 42) == ('foo', 42)
    • C++ has templating, so vector<T> has value semantics as long as T has value semantics; similarly you might use Color<float> and Color<double>.

    In contrast, the ValueType proposal requires us to specify all the leaf types ahead of time when we define the value type.

Edit: The ValueType proposal seems to be mostly about making values statically (stack) allocatable and transportable, so perhaps Niko's proposal is really about custom primitive types, and value semantics are actually orthogonal? I'm not sure.

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