JavaScript
Article
By Simon Willison

JavaScript and domain specific languages

By Simon Willison
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

I recently stumbled across a group of interesting JavaScript projects by Steve Yen: JavaScript Templates, TrimQuery and TrimSpreadsheet. The first is a JavaScript templating engine, similar to PHP’s Smarty. I was initially unconvinced by the wisdom of client-side templates, but Steve has a well considered blog entry in which he defends the idea in light of the increasing complexity of web applications. As an alternative to manually gluing strings together it’s likely to become a valuable tool.

TrimQuery and TrimSpreadsheet are even more interesting: the former is a SQL style data query language for interrogating JavaScript data structures, again designed to help build complex web applications, while the latter is a full Spreadsheet implementation in just 1700 lines of code.

All three projects are part of a wider exploration involving using JavaScript for domain specific languages. A domain specific language is a language which is designed to target a specific problem, such as SQL for processing relational data structures or regular expressions for matching patterns in text. Steve points out that JavaScript is well suited for implementing such mini-languages thanks to the little-used and much-maligned ‘eval’ and ‘with’ keywords. Here’s a neat example from TrimPath that uses ‘with’:

--ADVERTISEMENT--

var queryLang = TrimPath.makeQueryLang(tableColumnDefinitions);
with (queryLang) {
stmt = SELECT(X.a.AS("Foo"), Y.ALL,
FROM(X, Y), WHERE(EQ(X.a, Y.a)), ORDER_BY(Foo.ASC)
)
}

Steve’s code is well written and open-source; it’s well worth exploring.

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?