Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created December 25, 2024 11:19
Show Gist options
  • Save xuwei-k/1ebe245ab17269f9b755f4badaa58ecc to your computer and use it in GitHub Desktop.
Save xuwei-k/1ebe245ab17269f9b755f4badaa58ecc to your computer and use it in GitHub Desktop.
object ScalaRunTimeForScalaJS {
def main(a: Array[String]): Unit = {
println(replStringOf((1 to 200).toList, 10))
}
def replStringOf(arg: Any, maxElements: Int): String =
stringOf(arg, maxElements) match {
case null => "null toString"
case s if s.indexOf('\n') >= 0 => "\n" + s + "\n"
case s => s + "\n"
}
def stringOf(arg: Any, maxElements: Int): String = {
def isScalaClass(x: AnyRef) = x.getClass.getName startsWith "scala."
def isTuple(x: Any) = x != null && x.getClass.getName.startsWith("scala.Tuple")
type AnyConstr[X] = Any
def useOwnToString(x: Any) = x match {
case _: Range | _: collection.immutable.NumericRange[_] => true
case _: collection.SortedOps[_, _] => true
case _: collection.StringView | _: collection.StringOps | _: collection.mutable.StringBuilder => true
case _: collection.View[_] => true
case x: Iterable[_] => (!x.isInstanceOf[collection.StrictOptimizedIterableOps[_, AnyConstr, _]]) || !isScalaClass(x)
case _ => false
}
def mapInner(arg: Any): String = arg match {
case (k, v) => inner(k) + " -> " + inner(v)
case _ => inner(arg)
}
def arrayToString(x: AnyRef) = {
if (x.getClass.getComponentType == classOf[runtime.BoxedUnit])
(0 until math.min(java.lang.reflect.Array.getLength(x), maxElements)).map(_ => "()").mkString("Array(", ", ", ")")
else
x.asInstanceOf[Array[_]].iterator.take(maxElements).map(inner).mkString("Array(", ", ", ")")
}
def inner(arg: Any): String = arg match {
case null => "null"
case "" => "\"\""
case x: String => if (x.head.isWhitespace || x.last.isWhitespace) "\"" + x + "\"" else x
case x if useOwnToString(x) => x.toString
case x: AnyRef if x.getClass.isArray => arrayToString(x)
case x: Product1[_] if isTuple(x) => "(" + inner(x._1) + ",)" // that special trailing comma
case x: Product if isTuple(x) => x.productIterator.map(inner).mkString("(", ",", ")")
case x => x.toString
}
inner(arg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment