Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Last active August 29, 2015 14:02
Show Gist options
  • Save kl0tl/f1b1aef296f6d980d685 to your computer and use it in GitHub Desktop.
Save kl0tl/f1b1aef296f6d980d685 to your computer and use it in GitHub Desktop.
Inline `Object.create`
let create = macro {
rule { Object. | (null) } => { Object.create(null); }
rule infix { Object. | ($proto:expr) } => {
(function (proto, ObjectConstructor) {
if (typeof proto !== 'object' && typeof proto !== 'function') {
throw new TypeError('Object prototype may only be an Object or null:' + proto);
}
if (proto === null) {
return ObjectConstructor.create(null);
}
function Object() {}
Object.prototype = proto;
return new Object();
}($proto, Object))
}
rule infix { Object. | ($proto:expr, $properties:expr) } => {
(function (proto, properties, ObjectConstructor) {
if (typeof proto !== 'object' typeof proto !== 'function') {
throw new TypeError('Object prototype may only be an Object or null:' + proto);
}
if (proto === null) {
return ObjectConstructor.create(null, properties);
}
function Object() {}
Object.prototype = proto;
return ObjectConstructor.defineProperties(new Object(), properties);
}($proto, $properties, Object))
}
rule { $rest ... } => { create $rest ... }
}
export create;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment