diff options
author | Yuriy Glukhov <yutiy.glukhov@gmail.com> | 2016-04-07 22:57:35 +0300 |
---|---|---|
committer | Yuriy Glukhov <yutiy.glukhov@gmail.com> | 2016-04-07 22:57:35 +0300 |
commit | 2bf6f579307b67fdebfd8fca48020b6cd6f86dd2 (patch) | |
tree | 0a5a249e61883767829dcc162df1e50a2ee65cd3 /tests/js/tclosures.nim | |
parent | 9a747828feeb3c25e5fe0caedc04a2af10ca3ce2 (diff) | |
download | Nim-2bf6f579307b67fdebfd8fca48020b6cd6f86dd2.tar.gz |
Added js closures test. Fixes #3132.
Diffstat (limited to 'tests/js/tclosures.nim')
-rw-r--r-- | tests/js/tclosures.nim | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/tests/js/tclosures.nim b/tests/js/tclosures.nim new file mode 100644 index 000000000..c0d93814c --- /dev/null +++ b/tests/js/tclosures.nim @@ -0,0 +1,51 @@ +discard """ + action: run +""" + +import math, strutils +const consolePrefix = "jsCallbacks" + +asm """ + var callback = [] + function regCallback (fn) { callback.push (fn); } + function runCallbacks () { + var result = "\n" + var n = 0 + for (var fn in callback) { + n += 1 + result += "("+String (n)+")" + result += callback [fn] () + result += "\n" + } + return result + } + function print (text) { console.log (text); } +""" + +proc consoleprint (str:cstring): void {.importc: "print", noDecl.} +proc print* (a: varargs[string, `$`]) = consoleprint "$1: $2" % [consolePrefix, join (a, " ")] + +type CallbackProc {.importc.} = proc () : cstring + +proc regCallback (fn:CallbackProc) {.importc.} +proc runCallbacks ():cstring {.importc.} + +proc `*` (s:string, n:Natural) : string = s.repeat (n) + +proc outer (i:Natural) : (string, int) = + let c = $char (random (93) + 33) + let n = random (40) + let s = c * n + proc inner () : cstring = ("[$1]" % $n) & s & " <--" + regCallback (inner) + return (s, n) + +var expected = "\n" +for i in 1 .. 10: + let (s, n) = outer (i) + expected &= ("($1)[$2]" % [$i, $n]) & s & " <--" + expected &= "\n" + +let results = runCallbacks () + +doAssert(expected == results) |