Coder Social home page Coder Social logo

bloomberg / record-tuple-polyfill Goto Github PK

View Code? Open in Web Editor NEW
162.0 15.0 11.0 3.4 MB

A polyfill for the ECMAScript Record and Tuple proposal.

License: Apache License 2.0

JavaScript 99.97% HTML 0.03%
javascript tc39 tuple immutable polyfill record

record-tuple-polyfill's Introduction

Record & Tuple Polyfill

The Record and Tuple ECMAScript proposal introduces new deeply immutable value types to JavaScript that have similar access idioms to objects and arrays.

This is an experimental and explicitly not production ready polyfill for the Record and Tuple proposal, and a babel transform to support using the literal syntax.

The polyfill and transform are constant works in progress and are not the source of truth for the proposal.

Requirements

In order to use the syntax transform, babel must be installed with at least version 7.9.0.

In order to use the polyfill, the environment must support WeakMap, WeakRef, and FinalizationRegistry. If implementations of these features are not provided, an error will be thrown.

Installation

To install the transform and polyfill:

# install the babel transform as a dev dependency, only needed at compile time
npm install -D @babel/plugin-proposal-record-and-tuple

# install the polyfill as a regular dependency, needed at runtime
npm install --save @bloomberg/record-tuple-polyfill

Next, add the plugin to your babel configuration. Example:

{
    "plugins": [["@babel/plugin-proposal-record-and-tuple", { "syntaxType": "hash" }]]
}

Note, the syntaxType option is required, and must be set to either hash or bar.

Usage

If the babel transform and the polyfill are setup, you can start using the Record and Tuple literal syntax.

console.log(#{ a: 1 } === #{ a: 1 });
console.log(#[1, 2, 3] === #[1, 2, 3]);

If you want to use the Record or Tuple global objects, you can import them from the polyfill directly.

import { Record, Tuple } from "@bloomberg/record-tuple-polyfill";

const record = Record({ a: 1 });
const tuple = Tuple(1, 2, 3);
const array = [1,2,3];

console.log(Record.isRecord(record));
console.log(Record.keys(record));
console.log(Tuple.from(array));

Unsupported Features

typeof will return an incorrect value when provided a Record or Tuple. Storing +/-0 differs from the spec, Object.is( #[+0][0], #[-0][0] ) returns true when it should return false. This is because the polyfill implements the proposal via interning frozen objects.

Playground

The Record and Tuple polyfill has been deployed in an easy to use REPL here.

Supported Environments/Browsers

The Record and Tuple polyfill requires several JavaScript features that are only available experimentally in browsers, specifically WeakRef and FinalizationRegistry.

The following environments support these experimental features out-of-the-box.

environment supported
Chrome Canary โœ”๏ธ

In order to use these experimental features other browsers, you must run the browser/environment with specific flags:

environment flags
node --harmony-weak-refs
Chrome --js-flags="--harmony-weak-refs"
Firefox Nightly javascript.options.experimental.weakrefs

record-tuple-polyfill's People

Contributors

acutmore avatar dead-claudia avatar dependabot[bot] avatar nicolo-ribaudo avatar rickbutton avatar robpalme avatar rricard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

record-tuple-polyfill's Issues

The modules are all non-public

The modules @bloomberg/record-tuple-polyfill and @bloomberg/babel-plugin-proposal-record-tuple are both published as private.

You can verify by visiting either of these two links while signed out:

I also noticed the lack of a "publishConfig": {"access": "public"} within those packages in this repo, which may have been a contributing factor.

Records may only have String keys

Describe the bug
According to proposal-record-tuple, the key of Record can only be a string.

Records may only have String keys, not Symbol keys, due to the issues described in tc39/proposal-record-tuple#15. Creating a Record with a Symbol key is a TypeError.

To Reproduce

const record = #{ [Symbol()]: #{} };

Expected behavior
It should show the error // TypeError: Record may only have string as keys

Typescript typings

Awesome work!

Is your feature request related to a problem? Please describe.
Is there ambitions to add typescript typings for this project?
If so, I could maybe help you do them.

Describe the solution you'd like
The thing is, I'm not sure how we would go about implementing types for the "syntax-sugar"-mode of this, i.e. #{} and #[], maybe orta (https://github.com/orta) could chime in on this. But, the Record and Tuple constructors should be possible to do I think.

Describe alternatives you've considered
I think just waiting it out would be OK for me too ๐Ÿ‘

Additional context
None that I can think of.

WeakMap.set(Record) does not trigger a TypeError as stated in [proposal](https://github.com/tc39/proposal-record-tuple#weakmap-and-weakset)

Describe the bug
WeakMap.set(Record) does not throw a TypeError as stated in proposal.

To Reproduce
There is my code:
babel.config.js

module.exports = {
    presets: ["@babel/preset-env"],
    plugins: [
        ["@babel/plugin-proposal-record-and-tuple", {
            importPolyfill: true,
            // "hash" | "bar"
            syntaxType: "hash"  
        }]
    ]
}

index.js

const imutableRecord_1 = #{
    name: "vinsurs",
    age: 18
}
const imutableTuple_1 = #[1, 2, 4]

const weakMap = new WeakMap()
weakMap.set(imutableRecord_1, "imutableRecord")
weakMap.set(imutableTuple_1, "imutableTuple")
// TypeError does not throw and can get results normally.
console.log("weakMap", weakMap.get(imutableRecord_1), weakMap.get(imutableTuple_1))

Current behavior
The console can log result normally
Expected behavior
The console should throw a TypeError because WeakMap cannot accept a primitive value as it's key, or as mentioned in Record-and-Tuple Proposal..

Environment (please complete the following information):

  • System:
    • OS: Windows 10 10.0.19042
  • Binaries:
    • Node: 16.12.0
    • Yarn: 1.22.17
    • npm: 8.3.0
  • npmPackages:
    • @babel/cli: ^7.17.6 => 7.17.6
    • @babel/core: ^7.17.8 => 7.17.8
    • @babel/plugin-proposal-record-and-tuple: ^7.16.7 => 7.16.7
    • @babel/preset-env: ^7.16.11 => 7.16.11

Design and implement "loose mode"

It could be helpful for practical usage to enable a version which is faster and less spec-compliant. It's not clear what the semantics should be exactly. This project is lower priority than supporting an as-compliant-as-possible playground.

Enumerate spec violations

I think it would be useful to enumerate spec violations and see which ones we can and can't fix over time.

Readme: WeakRef and FinalizationRegistry now widely supported

README.md states:

The Record and Tuple polyfill requires several JavaScript features that are only available experimentally in browsers, specifically WeakRef and FinalizationRegistry.

And then cites Chrome Canary ans the only browser supporting these features out of the box.

This was last updated 2 years ago, apparently.

Per canisue.com, these have been supported in the leading browsers for more than 2 years:

Would it make sense to remove the Supported Environments/Browsers section entirely?

Record.fromEntries argument type assertion

Describe the bug
It's Record.fromEntries argument type assertion issue, which is an array-like object for each item in its argument.

To Reproduce

const record = Record.fromEntries([["a", 1], #["b", 2], "c3"]);
console.log(record);
// print:  Record {a: 1, b: 2, c: "3"}

Expected behavior
In terms of Record.fromEntries spec, it should throw this error.

Uncaught TypeError: Iterator value c3 is not an entry object

JSON.parseImmutable not implemented

Describe the bug

JSON.parseImmutable is missing

To Reproduce

const user = JSON.parseImmutable('{ "name": "danny", "admin": false, "score": 42 }');
    "JSON.parseImmutable is not a function"

    TypeError {}

Expected behavior

Json gets parsed into a record

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • Windows 10
  • Firefox 78

Additional context
Add any other context about the problem here.

Tuple.prototype.sorted not implemented

Describe the bug
A clear and concise description of what the bug is.

To Reproduce

console.log(#[3, 2, 1].sorted() === #[1, 2, 3]);
    "_recordTuplePolyfill.Tuple(...).sorted is not a function"

    TypeError {}

Expected behavior

Shows true

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • Windows 10
  • Firefox 78.0.1

Additional context
Add any other context about the problem here.

Improve performances of large records

It seems that the current implementation of updating a record is naive.

For large records, the spread operator has bad performance.

A possible improvement is to implement efficient persistent data structures like in Clojure and Immutable.js.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.