Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Converting JS Libraries to Clojure: Part 1
bop
bop

Posted on

     

Converting JS Libraries to Clojure: Part 1

What are we doing here?

This is a series of articles with two purposes: to improve my Clojure and ClojureScript knowledge and to help JavaScript developers learn Clojure.

The first library we will be transforming istitleize. We are starting with the simplest library I could think I ever used and maybe you used too.

Also becausesindresorhus has the largest, high-quality, open-source codebase of reusable js/ts snippets and libraries, I've seen.

The recommendation here is not necessarily to use it in a project but to know the basics of Clojure code that can be used on both Clojure and ClojureScript environments. Maybe if you have a Clojure(Script) project you can install this library, but if you just want atitleize function in your JavaScript code, just npm install the original one.

The titleize function

Let's start by digging into the original code. This is the titleize function. It has no dependencies. A very simple
straightforward JavaScript regex shenanigans. Take a look:

exportdefaultfunctiontitleize(string){if(typeofstring!=='string'){thrownewTypeError('Expected a string');}returnstring.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x=>x.toUpperCase());}
Enter fullscreen modeExit fullscreen mode

So the first thing to do is to create this function. I don't want to spend too much your time so let's just fire a REPL
and start doing stuff there. So run this:

$ clj

So now on the REPL, you can test some code. Run some sum example like(+ 1 2) and make sure you receive3 and then we
can start.

String functions

So first let's require Clojure's string standard library with the following code.

(require[clojure.string:asstring])
Enter fullscreen modeExit fullscreen mode

In the original code, we can see the author using the toLowerCase and toUpperCase methods from JavaScript's string type. The equivalents in Clojure would be:

(string/lower-case"BEING DEV IS NICE"); => being dev is nice(string/upper-case"being dev is cool"); => BEING DEV IS COOL
Enter fullscreen modeExit fullscreen mode

Ok. We could also refer to the functions directly.

(require[clojure.string:refer[lower-caseupper-case]])(lower-case"BEING DEV IS NICE"); => being dev is nice(upper-case"being dev is cool"); => BEING DEV IS COOL
Enter fullscreen modeExit fullscreen mode

Then we can see on the original implementation that we also have a usage ofreplaceAll with some regex. The
equivalent will also be fromclojure.string which is thereplace function.

Regex

In Clojure, the regex syntax is a little bit different. Of course, it will depend on the application but for now, we will ignore the modifiers (we can see the/g on the titleize implementation) and just transform that to our beloved clojure syntax:

Original:

/(?:^|\s|-)\S/g
Enter fullscreen modeExit fullscreen mode

Clojure:

#"(?:^|\s|-)\S"
Enter fullscreen modeExit fullscreen mode

Not trusting me? Ok. Make sure you know by yourself then:

(type#""); => java.util.regex.Pattern
Enter fullscreen modeExit fullscreen mode

Glueing everything together

Now let's write our function:

(require[clojure.string:refer[lower-caseupper-casereplace]])(defntitleize[str](replace(lower-casestr)#"(?:^|\s|-)\S"upper-case))
Enter fullscreen modeExit fullscreen mode

Done! Run the above on your REPL and then you can use it:

(titleize"the quick brown fox jumps over the lazy dog"); => The Quick Brown Fox Jumps Over The Lazy Dog
Enter fullscreen modeExit fullscreen mode

Let's refactor it a little

Our code is fine now. It works! But it still doesn't leverage one of the best things Clojure has: macros!

To make our code a little bit more readable and, I would say, better to maintain we will be using the thread first macro. Which can be simply described as:

The thread-first macro-> in Clojure allows you to write code in a more sequential and readable manner by threading the output of one function call into the first argument of the next function call. It simplifies nested function calls by enhancing code readability and reducing the need for intermediate variables. This macro assists in composing functions together in a natural left-to-right order, making the code easier to understand and maintain.

By applying that, our code will now look like this:

(defntitleize[str](->str(lower-case)(replace#"(?:^|\s|-)\S"upper-case)))
Enter fullscreen modeExit fullscreen mode

So pretty! Right? Clojure has a bunch of useful macros.

Tests

The original library has a very simple test chain, comparing a bunch of strings that we have. The repo uses ava to run the tests. Take a look:

importtestfrom'ava';importtitleizefrom'./index.js';test('main',t=>{t.is(titleize(''),'');t.is(titleize('unicorns and rainbows'),'Unicorns And Rainbows');t.is(titleize('UNICORNS AND RAINBOWS'),'Unicorns And Rainbows');t.is(titleize('unicorns-and-rainbows'),'Unicorns-And-Rainbows');t.is(titleize('UNICORNS-AND-RAINBOWS'),'Unicorns-And-Rainbows');t.is(titleize('unicorns   and rainbows'),'Unicorns   And Rainbows');});
Enter fullscreen modeExit fullscreen mode

For Clojure we have theclojure.test library so we just need to copy the test and apply it on Clojure syntax:

(nsexcelsia.titleize-test(:require[clojure.test:refer[deftestistesting]][excelsia.titleize:astitleize]))(defresult-map{"""""unicorns and rainbows""Unicorns And Rainbows""UNICORNS AND RAINBOWS""Unicorns And Rainbows""unicorns-and-rainbows""Unicorns-And-Rainbows""UNICORNS-AND-RAINBOWS""Unicorns-And-Rainbows""unicorns   and rainbows""Unicorns   And Rainbows"})(deftesttitleize-test(testing"titleize"(doseq[[inputexpected]result-map](is(=expected(titleize/titleizeinput))))))
Enter fullscreen modeExit fullscreen mode

Now, I'm not going too deep on that, but you can see on the repository that we are running tests both on the Clojure environment and on the Node.js environment to make sure the code works properly both on Clojure and ClojureScript.

Summary

So we grabbed a very small JS library and ported it to Clojure library compatible with ClojureScript. Tell me your
feedbacks and other small libraries you may want to see converted to Clojure.

Code

https://github.com/excelsia-dev/titleize

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a software developer currently working on multiple projects at Kellton Tech. Mostly doing TypeScript and React on a daily basis, focusing on front-end work. On a side note I also work with Clojure
  • Location
    Ribeirão Preto, Brazil
  • Education
    Bing Search
  • Pronouns
    he/him/his
  • Work
    Software Engineer @ Kellton
  • Joined

More frombop

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp