# Create a new context
ctx <- v8();
# Evaluate some code
ctx$eval("var foo = 123")
ctx$eval("var bar = 456")
ctx$eval("foo+bar")
# Functions and closures
ctx$eval("JSON.stringify({x:Math.random()})")
ctx$eval("(function(x){return x+1;})(123)")
# Objects (via JSON only)
ctx$assign("mydata", mtcars)
ctx$get("mydata")
outlist <- ctx$get("mydata", simplifyVector = FALSE)
outlist[1]
# Assign JavaScript
ctx$assign("foo", JS("function(x){return x*x}"))
ctx$assign("bar", JS("foo(9)"))
ctx$get("bar")
# Validate script without evaluating
ctx$validate("function foo(x){2*x}") #TRUE
ctx$validate("foo = function(x){2*x}") #TRUE
ctx$validate("function(x){2*x}") #FALSE
# Use a JavaScript library
ctx$source("https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js")
ctx$call("_.filter", mtcars, JS("function(x){return x.mpg < 15}"))
# Example from underscore manual
ctx$eval("_.templateSettings = {interpolate: /\\{\\{(.+?)\\}\\}/g}")
ctx$eval("var template = _.template('Hello {{ name }}!')")
ctx$call("template", list(name = "Mustache"))
# Call anonymous function
ctx$call("function(x, y){return x * y}", 123, 3)
if (FALSE) {
#CoffeeScript
ct2 <- v8()
ct2$source("http://coffeescript.org/v1/browser-compiler/coffee-script.js")
jscode <- ct2$call("CoffeeScript.compile", "square = (x) -> x * x", list(bare = TRUE))
ct2$eval(jscode)
ct2$call("square", 9)
# Interactive console
ct3 <- v8()
ct3$console()
# //this is JavaScript
# var test = [1,2,3]
# JSON.stringify(test)
# exit
}
Run the code above in your browser using DataLab