Skip to content

Instantly share code, notes, and snippets.

@pbouzakis
Last active August 29, 2015 14:04
Show Gist options
  • Save pbouzakis/8f771ae454faa6762e04 to your computer and use it in GitHub Desktop.
Save pbouzakis/8f771ae454faa6762e04 to your computer and use it in GitHub Desktop.
Playing around with macro's using sweet.js. Here is an attempt at sweetening privacy with private maps.
/*
Sweet.js macros for privacy sugar.
Below could be rewritten using es6 weakmaps.
*/
macro privacy {
rule {} => {
var id = ++privates.id
var privMap = {}
this.__id = id
privates[id] = privMap
}
}
macro class {
rule {
$className {
constructor $cparams $cbody
$($mname $mparams $mbody) ...
}
} => {
function $className $cparams $cbody
$($className.prototype.$mname
= function $mname $mparams $mbody; ) ...
}
}
macro @ {
rule { $x = $y } => {
privates[this.__id].$x = $y
}
rule { $x } => {
privates[this.__id].$x
}
}
var privates = { id: 0 };
class BazBar {
constructor() {
privacy;
@color = "blue";
@size = 200;
}
baz() {
console.log(@color);
console.log(@size * 10);
}
}
var bar = new BazBar();
bar.baz();
@pbouzakis
Copy link
Author

The id set on the object should be exposed as a getter.

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