Last active
August 29, 2015 14:02
-
-
Save kl0tl/a791f19f8c326d691ddd to your computer and use it in GitHub Desktop.
Lazy initialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| ``` | |
| var foo = { | |
| lazy computed() { | |
| return []; | |
| } | |
| }; | |
| ``` | |
| An alternative syntax allows to declare a lazy property on a preexisting object | |
| ``` | |
| var foo = {}; | |
| lazy foo.property() { | |
| return []; | |
| }; | |
| ``` | |
| */ | |
| macro function_params { | |
| rule { ($param (,) ...) } | |
| } | |
| macro concise_function_expression { | |
| rule { $params:function_params { $body ... } } => { | |
| function $params { $body ... } | |
| } | |
| rule { $params:function_params => $body:expr } => { | |
| function $params { return $body } | |
| } | |
| } | |
| // cf http://stackoverflow.com/a/22414263 | |
| macro syntax2string { | |
| rule { $syntax } => { | |
| [makeValue(unwrapSyntax($syntax).toString(), $syntax)] | |
| } | |
| } | |
| macro stringify { | |
| case { _ ($syntax) } => { | |
| letstx $string = syntax2string(#{$syntax}); | |
| return #{$string}; | |
| } | |
| } | |
| let lazy = macro { | |
| rule { $name:ident $function:concise_function_expression } => { | |
| get $name() { | |
| return Object.defineProperty(this, stringify($name), { | |
| __proto__: null, | |
| value: $function.call(this), | |
| writable: false, | |
| enumerable: true, | |
| configurable: true | |
| }).$name; | |
| } | |
| } | |
| rule { $symbol:ident (.) ... $name:ident $function:concise_function_expression } => { | |
| Object.defineProperty($symbol (.) ..., stringify($name), { | |
| __proto__: null, | |
| get: function () { | |
| return Object.defineProperty(this, stringify($name), { | |
| __proto__: null, | |
| value: $function.call(this), | |
| writable: false, | |
| enumerable: true, | |
| configurable: true | |
| }).$name; | |
| }, | |
| enumerable: true, | |
| configurable: true | |
| }) | |
| } | |
| rule { $rest ... } => { lazy $rest ... } | |
| } | |
| export lazy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment