Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 38950  / 12 Years ago, tue, september 11, 2012, 12:00:00

I read some code where someone did this in Ruby:



puts ('A'..'Z').to_a.join(',')


output:



A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z


Is there something in Javascript that will allow this to be done just as easy? if not, is there Node module that allows for something similar?


More From » ruby

 Answers
67

Javascript doesn't have that functionality natively. Below you find some examples of how it could be solved:



Normal function, any characters from the base plane (no checking for surrogate pairs)



function range(start,stop) {
var result=[];
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
result.push(String.fromCharCode(idx));
}
return result;
};

range('A','Z').join();


The same as above, but as a function added to the array prototype, and therefore available to all arrays:



Array.prototype.add_range = function(start,stop) {
for (var idx=start.charCodeAt(0),end=stop.charCodeAt(0); idx <=end; ++idx){
this.push(String.fromCharCode(idx));
}
return this;
};

[].add_range('A','Z').join();


A range from preselected characters. Is faster than the functions above, and let you use alphanum_range('A','z') to mean A-Z and a-z:



var alphanum_range = (function() {
var data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split('');
return function (start,stop) {
start = data.indexOf(start);
stop = data.indexOf(stop);
return (!~start || !~stop) ? null : data.slice(start,stop+1);
};
})();

alphanum_range('A','Z').join();


Or any character from the ascii range. By using a cached array, it is faster than the functions that build the array every time.



var ascii_range = (function() {
var data = [];
while (data.length < 128) data.push(String.fromCharCode(data.length));
return function (start,stop) {
start = start.charCodeAt(0);
stop = stop.charCodeAt(0);
return (start < 0 || start > 127 || stop < 0 || stop > 127) ? null : data.slice(start,stop+1);
};
})();

ascii_range('A','Z').join();

[#83132] Monday, September 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;