Create an array of characters from specified range

后端 未结 12 2238
名媛妹妹
名媛妹妹 2020-12-17 08:19

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         


        
12条回答
  •  清歌不尽
    2020-12-17 08:47

    https://stackoverflow.com/a/64599169/8784402

    Generate Character List with one-liner

    const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));
    
    console.log("from A to G", charList('A', 'G'));
    console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));
    console.log("reverse order from Z to P", charList('Z', 'P', -1));
    console.log("from 0 to 5", charList('0', '5', 1));
    console.log("from 9 to 5", charList('9', '5', -1));
    console.log("from 0 to 8 with step 2", charList('0', '8', 2));
    console.log("from α to ω", charList('α', 'ω'));
    console.log("Hindi characters from क to ह", charList('क', 'ह'));
    console.log("Russian characters from А to Я", charList('А', 'Я'));

    For TypeScript
    const charList = (p: string, q: string, d = 1) => {
      const a = p.charCodeAt(0),
        z = q.charCodeAt(0);
      return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>
        String.fromCharCode(a + i * d)
      );
    };
    

提交回复
热议问题