Minimist: an example of writing native JavaScript bindings in R

[This article was first published on OpenCPU, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

opencpu logo

A new package has appeared on CRAN called minimist, which implements an interface to the popular JavaScript library. This package has only one function, used for argument parsing. For example in RGui on OSX, the output of commandArgs() looks like this:

> commandArgs()
[1] "R"                 "--no-save"         "--no-restore-data" "--gui=aqua"

Minimist turns that into this:

> library(minimist)
> minimist(commandArgs())
$`_`
[1] "R"

$save
[1] FALSE

$`restore-data`
[1] FALSE

$gui
[1] "aqua"

Note how it interprets the --no- prefix as FALSE and the --foo=bar as a key-value pair. It has some more of these rules, following the usual scripting argument syntax conventions. Cool, but not exactly ground breaking; there are already half a dozen packages on CRAN for parsing arguments (although this one is particularly nice :P).

Writing JavaScript bindings using V8

The main purpose of this new package is to exemplify how to write a package with bindings to a JavaScript library using V8. If you take a look at the package source, you might be surprised how small it is. The package consists of:

That’s it. To install this package from source no compiler is required. It will build out of the box, even on machines without Rtools or Xcode. Moreover, there are no external dependencies as is the case for e.g. Java code, where we need to install a JVM. Everything is self contained within R and V8. It’s fast too:

> system.time(minimist(commandArgs()))
   user  system elapsed 
  0.001   0.000   0.001

I’m working on several other packages to implement bindings to cool JavaScript libraries (see also yesterdays post). If you have some suggetions for other JavaScript libraries that might be useful in R, get in touch.

To leave a comment for the author, please follow the link and comment on their blog: OpenCPU.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)