Unfortunately, ECMAScript does not have a Range
in its standard library. However, what you can do, is to use the Array.from
factory function to construct an Array
using a mapping function.
Something like this:
const alphabet = Array.from({ length: 26 }, (_, i) => i + 97).map(String.fromCharCode);
Or, without magic numbers:
const charCodeOfA = "a".charCodeAt(0), //=> 97
charCodeOfZ = "z".charCodeAt(0), //=> 122
lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1, //=> 26
alphabet = Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
map(String.fromCharCode);
In future versions of ECMAScript, it would be nice to use do
expressions to avoid polluting the namespace with those temporary helper variables:
const alphabet = do {
const charCodeOfA = "a".charCodeAt(0), //=> 97
charCodeOfZ = "z".charCodeAt(0), //=> 122
lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1; //=> 26
Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
map(String.fromCharCode)
}