Last active
March 12, 2021 02:43
-
-
Save smithcommajoseph/4956138 to your computer and use it in GitHub Desktop.
A JS implementation of Ruby's constantize
This file contains 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
// 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; | |
} | |
}; |
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
Why not just
return eval(str);