Skip to content

Instantly share code, notes, and snippets.

@smithcommajoseph
Last active March 12, 2021 02:43
Show Gist options
  • Save smithcommajoseph/4956138 to your computer and use it in GitHub Desktop.
Save smithcommajoseph/4956138 to your computer and use it in GitHub Desktop.
A JS implementation of Ruby's constantize
// A basic example of how Ruby's constantize _could_ work in JS
// See https://apidock.com/rails/String/constantize
function constantize (str) {
if (typeof str !== 'string') {
throw new TypeError('must pass in type of string');
}
if (str.match(/\W|\d/)) {
throw new SyntaxError('must pass in a valid Javascript name');
}
else {
var constant
eval("constant = " + str);
return constant;
}
};
@joyrows
Copy link

joyrows commented Aug 12, 2015

Why not just return eval(str);

@coleturner
Copy link

coleturner commented Apr 16, 2017

Whenever possible, a collection of objects with a object key lookup is much faster than eval:

https://jsperf.com/constantize-eval-vs-obj-key

Neat use of eval though!

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