"Fossies" - the Fresh Open Source Software Archive

Member "scala-js-1.0.0-RC1/library/src/main/scala/scala/scalajs/js/ArrayOpsCommon.scala" (21 Nov 2019, 1797 Bytes) of package /linux/www/scala-js-1.0.0-RC1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Scala source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "ArrayOpsCommon.scala": 0.6.31_vs_1.0.0-RC1.

    1 /*
    2  * Scala.js (https://www.scala-js.org/)
    3  *
    4  * Copyright EPFL.
    5  *
    6  * Licensed under Apache License 2.0
    7  * (https://www.apache.org/licenses/LICENSE-2.0).
    8  *
    9  * See the NOTICE file distributed with this work for
   10  * additional information regarding copyright ownership.
   11  */
   12 
   13 package scala.scalajs.js
   14 
   15 import scala.annotation.tailrec
   16 
   17 import scala.scalajs.js
   18 
   19 private[js] object ArrayOpsCommon {
   20 
   21   /** Efficient concatenation of two JS arrays. */
   22   def concat[A](left: js.Array[_ <: A], right: js.Array[_ <: A]): js.Array[A] = {
   23     val leftLength = left.length
   24     val rightLength = right.length
   25     val result = new js.Array[A](leftLength + rightLength)
   26 
   27     @inline
   28     @tailrec
   29     def loop(src: js.Array[_ <: A], i: Int, len: Int, offset: Int): Unit = {
   30       if (i != len) {
   31         result(i+offset) = src(i)
   32         loop(src, i+1, len, offset)
   33       }
   34     }
   35 
   36     loop(left, 0, leftLength, 0)
   37     loop(right, 0, rightLength, leftLength)
   38     result
   39   }
   40 
   41   def reduceLeft[A, B >: A](array: js.Array[A], op: (B, A) => B): B = {
   42     val length = array.length
   43     if (length <= 0)
   44       throwUnsupported("empty.reduceLeft")
   45 
   46     @inline
   47     @tailrec
   48     def loop(start: Int, z: B): B =
   49       if (start == length) z
   50       else loop(start+1, op(z, array(start)))
   51 
   52     loop(1, array(0))
   53   }
   54 
   55   def reduceRight[A, B >: A](array: js.Array[A], op: (A, B) => B): B = {
   56     val length = array.length
   57     if (length <= 0)
   58       throwUnsupported("empty.reduceRight")
   59 
   60     @inline
   61     @tailrec
   62     def loop(end: Int, z: B): B =
   63       if (end == 0) z
   64       else loop(end-1, op(array(end-1), z))
   65 
   66     loop(length-1, array(length-1))
   67   }
   68 
   69   /** Extract the throw in a separate, non-inlineable method. */
   70   private def throwUnsupported(msg: String): Nothing =
   71     throw new UnsupportedOperationException(msg)
   72 
   73 }