TL;DR
// ['a', .. , 'z']
Array.apply(null, {length: 26})
.map(function (x,i) { return String.fromCharCode(97 + i) });
Or even
function range(first, last) {
var a = first.charCodeAt(0)
var b = last.charCodeAt(0) + 1
return Array.apply(null, {length: Math.abs(b - a)})
.map(function (x,i) { return String.fromCharCode(Math.min(a, b) + i) });
}
range('K','M') // => ['K','L','M']
range('$','z') // => "$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz"
I think this can be expressed clearest in a functional way: map [0 .. 25]
to ['a' .. 'z']
.
We can use fromCharCode(n)
to convert a number into a string. To find the numerical value corresponding to a character we need it's inverse function, toCharCode(s)
:
var toCharCode = function(s){ return s.charCodeAt(0) } // 'a' => 97, 'b' => 98, ..
Then the rest is easy:
Array.apply(null, {length: 26})
.map(function (x,i) { return String.fromCharCode(97 + i) });
Constructs an array of 26 undefined's: [undefined, ... , undefined]
. Then map
index i
of each value to 97 + i
== 'a'.charCodeAt(0) + i
(for uppercase start at 'A' => 65
).
This first line might need some explanation. What we are effectively doing is the same as Array(1,2,3)
== [1,2,3]
. Instead of passing an actual array to apply
, we pass something that quacks like an array (has the length
property). This results in calling Array(undefined, .. , undefined)
.
See
apply
and
"generic array-like object"
for more infomation.