Shape objects
Andrea Giammarchi
andrea.giammarchi at gmail.com
Sat Jun 16 09:29:04 UTC 2018
StructType never really got a chance:
https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/StructType
but it's also easy to have those kind of shapes in userland:
```js
const shape = definition => {
const keys = Reflect.ownKeys(definition);
const key = k => keys.includes(k);
function type(key, i) {
var expected = definition[key];
var current = this[key];
return typeof current === 'object' ?
(!expected ||
current instanceof expected) :
expected(current) === current;
}
return class Shape {
constructor(details) {
const k = Reflect.ownKeys(details);
if (
k.length !== keys.length ||
!k.every(key) ||
!k.every(type, details)
)
throw new TypeError('wrong shape: ' + k);
Object.freeze(Object.assign(this, details));
}
}
};
```
Regards
On Sat, Jun 16, 2018 at 9:56 AM, Cyril Auburtin <cyril.auburtin at gmail.com>
wrote:
> I wish JS had Shape objects, which would not only ease performance
> optimization for the benefit of JS engines (https://youtu.be/5nmpokoRaZI?
> t=871), but also helps for validation, like an interface
>
> ```js
> shape Point { x: Number, y: Number, name: String };
>
> const p = Point({x: 1, y: 2, name: 'foo'})
>
> const p = Point({x: 1, y: 2, naem: 'foo'}) // throws
> ```
>
> That object would have its properties immutable
>
> I think proposal-first-class-protocols (https://github.com/
> michaelficarra/proposal-first-class-protocols/issues/27#
> issuecomment-386975099) could more or less directly do that feature
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180616/ccf0416e/attachment.html>
More information about the es-discuss
mailing list