Welcome to my weblog. I write to help find my perspective, to reflect, and to give me a chance to see my ideas from different angles. Sometimes I vent. Sometimes I’m processing. Sometimes I just want to be helpful.
Simple sets in JavaScript
One of my favourite JavaScript features is its literal object notation. It allows you to declare data structures in JSON, which is a very succinct, C-like syntax. You can use this notation to declare SETs, and the a in b syntax to verify a variable is in a set: /* Declare your set as a JSON constant */ var valid_widgets = { 'widget-viewer': 1, 'special-viewer': 1, 'widget-editor': 1 }; /* Fail if something isn't in the set */ if ( ! (options.widget in valid_widgets) ) return false; /* Profit! */ As the in keyword operates on the index of the referred object, we set the value of the constants to 1 (true). A bit of a hack, but it results in a very clean way of checking if something is part of a set of valid values.