Last active
August 31, 2016 08:59
-
-
Save antony/4fdfc0398f46f73887de21f490185097 to your computer and use it in GitHub Desktop.
ChanceJS from Groovy / Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package vendigo.support.extensions | |
import groovy.json.JsonOutput | |
import javax.script.ScriptEngine | |
import javax.script.ScriptEngineManager | |
class Chance { | |
private static ScriptEngine engine | |
static { | |
ScriptEngineManager factory = new ScriptEngineManager() | |
engine = factory.getEngineByName("nashorn") | |
engine.eval(""" | |
var window = { document: {} } | |
var JavaMath = Java.type('java.lang.Math') | |
load('./node_modules/chance/dist/chance.min.js') | |
window.chance.random = JavaMath.random | |
""") | |
} | |
def methodMissing(String name, args) { | |
String options = args ? JsonOutput.toJson(args[0]) : '' | |
return engine.eval("window.chance.${name}(${options})") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So I found that there was no randomness at all, for some reason chance.random() doesn't generate random numbers at all.
So I've overriden chance's random number generator to use Java's builtin random number generator.
I've gone deep now, way too meta, but it works flawlessly 👯