Setting up symbol-valued constants via proxies — 2ality.com

Dean Tribble (via Rob Palmer) has come up with a neat trick to create constants whose values are strings with their names. With a minor change, we can use it to set up symbol-valued constants. Setting up constants   const SymbolFactory = new Proxy({}, { get: (_target, propKey, _receiver) => Symbol(propKey) }); const {red, green, blue} = SymbolFactory; assert.equal( typeof red, 'symbol' ); assert.equal( String(red), 'Symbol(red)' ); How does it work?   Each property of the pattern that object-destructures SymbolFactory, triggers a property get operation. Therefore, line B is equivalent to: const red = SymbolFactory.red; const green = SymbolFactory.green; const blue = SymbolFactory.blue; The method in line A intercepts each of these get operations. Among other information, it is provided with the key of the relevant property. It then creates and returns a symbol whose description is the property key. Further reading  

Read More



This site uses cookies to give the best and personalised experience. By continuing to browse the site you are agreeing to our use of cookies. Find out more here.

Sign Up or Login

Invalid username or password
Not yet on CircleMe? Join now
Please input a email
Please input a valid email
Max 50 characters
Email already in use
{{email_serverError}}
Please input a username
Min 3 characters
Max 20 characters
Please use only A-Z, 0-9 and "_"
Username is taken
Please input a password
Min 6 characters
Max 20 characters
By clicking the icons, you agree to CircleMe terms & conditions
Already have an account? Login Now