How to iterate through all alphabet letters in ClojureScript?

Table of Contents

Problem: JavaScript doesn’t have “chars”

EDIT [2022-07-19 Tue] no-interop solution from

In languages with an integer-based Char datatype, such as C and Java and probably by inheritance JVM Clojure, you could iterate through characters by the equivalent of (+ \A 1). JS doesn’t have chars though; only strings. Is there a nice way out-of-the-box to iterate through the characters of the alphabet, perhaps just in one case? I mean, obviously we could create a collection that contains all the letters we want, but is that already done somewhere?

Answer: code points

A beautiful little snippet shared by Plexus:1

(map String/fromCodePoint
       (range (.codePointAt \a 0) 
              (.codePointAt \z 0)))

Moral of the story: I need to do some better reading of the core libraries, both CLJS and JS!

Answer x 2: No Interop

The following example contains no interop, highlighting the odd reality that though Javascript does not have characters, ClojureScript has chars for compatibility sake.

(map char (range 97 122)) ; Lower case letters
(map char (range 65 91)) ; Upper case letters

Answer provided by Paul Dorman.

I would argue that this is one problem that the interop version is acceptable, for two reasons: First, Clojure[Script] is a hosted language, so a modest recognition of that fact isn’t wrong. Second, having the line like (.codePointAt \a 0) is self-describing, since I can better understand \a than 97.

On the flip side, there is a definite advantage to your code being able to work in CLJC. In that case I would simply wrap it like

(let [letter-a 97
       letter-z 122]
(map char (range letter-a letter-z))

Footnotes

1 Answered on ClojureVerse here: https://clojureverse.org/t/how-to-iterate-through-all-alphabet-letters-in-clojurescript/9131/2

Tory Anderson avatar
Tory Anderson
Full-time Web App Engineer, Digital Humanist, Researcher, Computer Psychologist