celestialgod

R V8 javascript

Mar 15th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.63 KB | None | 0 0
  1. library(V8)
  2. ctx <- v8()
  3. ctx$source("http://underscorejs.org/underscore-min.js")
  4. ctx$eval("var list = [[0, 1], [2, 3], [4, 5]];")
  5. ctx$eval("var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);")
  6. ctx$get("flat")
  7. # [1] 4 5 2 3 0 1
  8.  
  9. ctx$assign("x", 1:5)
  10. ctx$eval("var y = _.each(x, function(x){ return x*3;})")
  11. ctx$get("y")
  12. # [1] 1 2 3 4 5
  13.  
  14. x2 <- 1:5
  15. ctx$call("_.each", x2, JS("function(x){ return x*3;}"))
  16. # [1] 1 2 3 4 5
  17.  
  18.  
  19. ctx$call("_.filter", mtcars, JS("function(x){return x.mpg < 15}"))
  20. #                      mpg cyl disp  hp drat    wt  qsec vs am gear carb
  21. # Duster 360          14.3   8  360 245 3.21 3.570 15.84  0  0    3    4
  22. # Cadillac Fleetwood  10.4   8  472 205 2.93 5.250 17.98  0  0    3    4
  23. # Lincoln Continental 10.4   8  460 215 3.00 5.424 17.82  0  0    3    4
  24. # Chrysler Imperial   14.7   8  440 230 3.23 5.345 17.42  0  0    3    4
  25. # Camaro Z28          13.3   8  350 245 3.73 3.840 15.41  0  0    3    4
  26.  
  27. # work with npm
  28. Sys.setenv(PATH = paste0(Sys.getenv("PATH"), ";C:\\Program Files\\nodejs;C:\\Users\\Jamal\\AppData\\Roaming\\npm"))
  29. Sys.setenv(NODE_PATH = "C:\\Program Files\\nodejs\\node_modules;C:\\Users\\Jamal\\AppData\\Roaming\\npm\\node_modules")
  30. system("npm install -g browserify js-beautify")
  31. writeLines("global.beautify = require('js-beautify');", "in.js")
  32. system("browserify in.js -o bundle.js")
  33.  
  34. ct <- v8()
  35. ct$source("bundle.js")
  36. test <- "(function(x,y){x = x || 1; y = y || 1; return y * x;})(4, 9)"
  37. pretty_test <- ct$call("pr.js_beautify", test, list(indent_size = 2))
  38. cat(pretty_test)
  39. # (function(x, y) {
  40. #   x = x || 1;
  41. #   y = y || 1;
  42. #   return y * x;
  43. # })(4, 9)
Advertisement
Add Comment
Please, Sign In to add comment