Created
July 27, 2016 09:32
-
-
Save siriux/dc65d136f2ddbd681caae5d3664f668b to your computer and use it in GitHub Desktop.
Scala-js optimized array transforms test
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
import scala.scalajs.js | |
import js.JSApp | |
@inline | |
class TransformedArray[A, B](origArray: js.Array[A], transformFunction: (A, B => Unit) => Unit) { | |
@inline | |
def map[C](f: B => C): TransformedArray[A,C] = { | |
new TransformedArray(origArray, { (e, cb) => | |
transformFunction(e, x => cb(f(x))) | |
}) | |
} | |
@inline | |
def filter(f: B => Boolean): TransformedArray[A,B] = { | |
new TransformedArray(origArray, { (e, cb) => | |
transformFunction(e, x => if (f(x)) cb(x)) | |
}) | |
} | |
@inline | |
def foreach[U](cb: B => U): Unit = { | |
origArray.foreach { e => | |
transformFunction(e, cb(_)) | |
} | |
} | |
} | |
@inline | |
object TransformedArray { | |
@inline | |
def apply[A](a: js.Array[A]): TransformedArray[A,A] = { | |
new TransformedArray(a, (a: A, cb: A => Unit) => cb(a)) | |
} | |
} | |
object Main extends JSApp { | |
def main(): Unit = { | |
var sum = 0 | |
val a = js.Array(1,2,3) | |
val ta = TransformedArray(a) | |
ta.map(_*2).filter(_ < 6).foreach(e => sum += e) // Works if a couple of operations are performed | |
//ta.map(_*2).filter(_ < 6).foreach(e => sum += e) // If done a second time, it doesn't | |
//val ta2 = TransformedArray(a) | |
//ta2.map(_*2).filter(_ < 6).foreach(e => sum += e) // If done a second time over a different TA, works | |
//val foo = ta.map(_*2).filter(_ < 6) // Doesn't work if we don't traverse it directly | |
//println(foo.toString) // To use foo in some way | |
//ta.map(_*2).filter(_ < 6).filter(_ > 2).foreach(e => sum += e) // Doesn't work if it's too long | |
//val foo = ta.map(_*2).filter(_ == 7) // It works if we split the chain | |
//foo.foreach(e => sum += e) | |
println(sum) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment