From 9762ad4bfbfeb51222b1d1dc0718009b0e9970f4 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Mon, 12 Nov 2018 22:19:37 +0000 Subject: [PATCH] Bring Record toward the needs of Syndicate/js Struct --- implementations/javascript/src/index.js | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/implementations/javascript/src/index.js b/implementations/javascript/src/index.js index ad0bbd5..ef44782 100644 --- a/implementations/javascript/src/index.js +++ b/implementations/javascript/src/index.js @@ -303,6 +303,24 @@ class Record { this.fields = fromJS(fields); } + equals(other) { + return (other instanceof Record) && + Immutable.is(this.label, other.label) && + Immutable.is(this.fields, other.fields); + } + + hashCode() { + return Immutable.List([this.label, this.fields]).hashCode(); + } + + get(index, defaultValue) { + return this.fields.get(index, defaultValue); + } + + set(index, newValue) { + return new Record(this.label, this.fields.set(index, newValue)); + } + [PreserveOn](encoder) { if (Immutable.is(encoder.shortForms[0], this.label)) { encoder.header(2, 0, this.fields.size); @@ -318,11 +336,33 @@ class Record { } } +Record.makeConstructor = function (label, fieldNames) { + const arity = fieldNames.length; + const ctor = (...fields) => { + if (fields.length !== arity) { + throw new Error("Record: cannot instantiate " + (label && label.toString()) + + " expecting " + arity + " fields with " + fields.length + " fields"); + } + return new Record(label, fields); + }; + ctor.meta = label; + ctor.isClassOf = (v) => ((v instanceof Record) && Immutable.is(label, v.label)); + return ctor; +}; + class Float { constructor(value) { this.value = value; } + equals(other) { + return (other instanceof Float) && (other.value === this.value); + } + + hashCode() { + return this.value | 0; // TODO: something better? + } + [PreserveOn](encoder) { encoder.leadbyte(0, 0, 2); encoder.makeroom(4);