CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-scala-js--scalajs-scalalib-2-13

Scala standard library implementation for Scala.js, providing core library functionality for Scala code compiled to JavaScript

Pending
Overview
Eval results
Files

math.mddocs/

Math Operations

Mathematical functions and numeric utilities optimized for JavaScript's number system and Math object, providing Scala's math API while leveraging JavaScript's native mathematical capabilities.

Capabilities

Basic Mathematical Functions

Core mathematical operations adapted for JavaScript's floating-point number system.

/**
 * Mathematical functions and constants
 * Delegates to JavaScript's Math object for optimal performance
 */
object math {
  /** Mathematical constants */
  val E: Double = 2.718281828459045
  val Pi: Double = 3.141592653589793
  
  /** Absolute value */
  def abs(x: Int): Int
  def abs(x: Long): Long  
  def abs(x: Float): Float
  def abs(x: Double): Double
  
  /** Maximum of two values */
  def max(x: Int, y: Int): Int
  def max(x: Long, y: Long): Long
  def max(x: Float, y: Float): Float
  def max(x: Double, y: Double): Double
  
  /** Minimum of two values */
  def min(x: Int, y: Int): Int
  def min(x: Long, y: Long): Long
  def min(x: Float, y: Float): Float
  def min(x: Double, y: Double): Double
  
  /** Sign of number (-1, 0, or 1) */
  def signum(x: Int): Int
  def signum(x: Long): Long
  def signum(x: Float): Float
  def signum(x: Double): Double
  
  /** Power function */
  def pow(x: Double, y: Double): Double
  
  /** Square root */
  def sqrt(x: Double): Double
  
  /** Cubic root */
  def cbrt(x: Double): Double
  
  /** Hypotenuse (sqrt(x² + y²)) */
  def hypot(x: Double, y: Double): Double
  
  /** Exponential function (e^x) */
  def exp(x: Double): Double
  
  /** Natural logarithm */
  def log(x: Double): Double
  
  /** Base-10 logarithm */
  def log10(x: Double): Double
  
  /** Ceiling (smallest integer >= x) */
  def ceil(x: Double): Double
  
  /** Floor (largest integer <= x) */
  def floor(x: Double): Double
  
  /** Round to nearest integer */
  def round(x: Float): Int
  def round(x: Double): Long
  
  /** Round toward zero */
  def truncate(x: Double): Double
  
  /** Remainder after division */
  def IEEEremainder(x: Double, y: Double): Double
}

/**
 * Random number generator using JavaScript's Math.random()
 * Provides utility methods for common random operations
 */
class Random(seed: Long = System.currentTimeMillis()) {
  def nextBoolean(): Boolean
  def nextInt(): Int
  def nextInt(n: Int): Int
  def nextLong(): Long
  def nextFloat(): Float
  def nextDouble(): Double
  def nextGaussian(): Double
  def nextBytes(bytes: Array[Byte]): Unit
  def shuffle[T](array: Array[T]): Unit
}

object Random {
  def apply(): Random
  def apply(seed: Long): Random
}

Trigonometric Functions

Complete set of trigonometric and hyperbolic functions using JavaScript's Math implementation.

object math {
  /** Trigonometric functions (radians) */
  def sin(x: Double): Double
  def cos(x: Double): Double  
  def tan(x: Double): Double
  
  /** Inverse trigonometric functions */
  def asin(x: Double): Double
  def acos(x: Double): Double
  def atan(x: Double): Double
  def atan2(y: Double, x: Double): Double
  
  /** Hyperbolic functions */
  def sinh(x: Double): Double
  def cosh(x: Double): Double
  def tanh(x: Double): Double
  
  /** Convert degrees to radians */
  def toRadians(angdeg: Double): Double
  
  /** Convert radians to degrees */
  def toDegrees(angrad: Double): Double
}

Numeric Type Utilities

Utilities for working with different numeric types and their limits.

/**
 * Numeric type companion objects with constants and utilities
 */
object Int {
  /** Minimum and maximum values */
  val MinValue: Int = -2147483648
  val MaxValue: Int = 2147483647
}

object Long {
  val MinValue: Long = -9223372036854775808L
  val MaxValue: Long = 9223372036854775807L
}

object Float {
  val MinValue: Float = -3.4028235e38f
  val MaxValue: Float = 3.4028235e38f
  val MinPositiveValue: Float = 1.4e-45f
  val PositiveInfinity: Float = Float.PositiveInfinity
  val NegativeInfinity: Float = Float.NegativeInfinity  
  val NaN: Float = Float.NaN
}

object Double {
  val MinValue: Double = -1.7976931348623157e308
  val MaxValue: Double = 1.7976931348623157e308
  val MinPositiveValue: Double = 4.9e-324
  val PositiveInfinity: Double = Double.PositiveInfinity
  val NegativeInfinity: Double = Double.NegativeInfinity
  val NaN: Double = Double.NaN
}

/**
 * BigInt for arbitrary precision integers
 * Uses JavaScript BigInt when available, falls back to string-based implementation  
 */
class BigInt(val bigInteger: java.math.BigInteger) {
  /** Basic arithmetic operations */
  def +(that: BigInt): BigInt
  def -(that: BigInt): BigInt  
  def *(that: BigInt): BigInt
  def /(that: BigInt): BigInt
  def %(that: BigInt): BigInt
  
  /** Comparison operations */
  def <(that: BigInt): Boolean
  def <=(that: BigInt): Boolean
  def >(that: BigInt): Boolean
  def >=(that: BigInt): Boolean
  
  /** Bitwise operations */
  def &(that: BigInt): BigInt
  def |(that: BigInt): BigInt
  def ^(that: BigInt): BigInt
  def unary_~ : BigInt
  
  /** Conversion methods */
  def toInt: Int
  def toLong: Long
  def toFloat: Float
  def toDouble: Double
  override def toString: String
  def toString(radix: Int): String
}

object BigInt {
  /** Create BigInt from various types */
  def apply(x: Int): BigInt
  def apply(x: Long): BigInt
  def apply(x: String): BigInt
  def apply(x: String, radix: Int): BigInt
  
  /** Predefined constants */
  val 0: BigInt
  val 1: BigInt
  val 2: BigInt
  val 10: BigInt
}

/**
 * BigDecimal for arbitrary precision decimal numbers
 */
class BigDecimal(val bigDecimal: java.math.BigDecimal) {
  /** Arithmetic operations with precision control */
  def +(that: BigDecimal): BigDecimal
  def -(that: BigDecimal): BigDecimal
  def *(that: BigDecimal): BigDecimal
  def /(that: BigDecimal): BigDecimal
  def %(that: BigDecimal): BigDecimal
  
  /** Precision and scale */
  def precision: Int
  def scale: Int
  def setScale(newScale: Int): BigDecimal
  def setScale(newScale: Int, roundingMode: RoundingMode): BigDecimal
  
  /** Comparison */
  def compare(that: BigDecimal): Int
  
  /** Conversion */
  def toDouble: Double
  def toFloat: Float
  def toLong: Long
  def toInt: Int
  override def toString: String
}

object BigDecimal {
  /** Create BigDecimal from various types */
  def apply(x: Int): BigDecimal
  def apply(x: Long): BigDecimal
  def apply(x: Double): BigDecimal
  def apply(x: String): BigDecimal
  
  /** Rounding modes */
  object RoundingMode extends Enumeration {
    val UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY = Value
  }
}

Usage Examples:

import scala.math._

// Basic mathematical operations
val distance = sqrt(pow(3, 2) + pow(4, 2)) // Pythagorean theorem
println(s"Distance: $distance") // 5.0

val area = Pi * pow(5, 2) // Circle area
println(f"Circle area: $area%.2f")

// Trigonometric calculations
val angle = toRadians(45) // Convert 45 degrees to radians
val sinValue = sin(angle)
val cosValue = cos(angle)
println(f"sin(45°) = $sinValue%.3f, cos(45°) = $cosValue%.3f")

// Finding angles
val opposite = 3.0
val adjacent = 4.0
val angleRad = atan2(opposite, adjacent)
val angleDeg = toDegrees(angleRad)
println(f"Angle: $angleDeg%.1f degrees")

// Rounding and precision
val value = 3.14159
println(s"Ceiling: ${ceil(value)}")   // 4.0
println(s"Floor: ${floor(value)}")    // 3.0  
println(s"Rounded: ${round(value)}")  // 3

// Min/max operations
val numbers = List(3.7, 1.2, 8.9, 2.1, 5.5)
val minimum = numbers.reduce(min)
val maximum = numbers.reduce(max)
println(s"Range: $minimum to $maximum")

// Working with limits
println(s"Int range: ${Int.MinValue} to ${Int.MaxValue}")
println(s"Double max: ${Double.MaxValue}")

// Special values
val result1 = 1.0 / 0.0  // Positive infinity
val result2 = -1.0 / 0.0 // Negative infinity  
val result3 = 0.0 / 0.0  // NaN

println(s"Is infinite: ${result1.isInfinite}")
println(s"Is NaN: ${result3.isNaN}")

// BigInt for large integers
val big1 = BigInt("12345678901234567890")
val big2 = BigInt("98765432109876543210")
val bigSum = big1 + big2
val bigProduct = big1 * big2

println(s"Big sum: $bigSum")
println(s"Big product length: ${bigProduct.toString.length} digits")

// BigDecimal for precise decimal arithmetic
val price1 = BigDecimal("19.99")
val price2 = BigDecimal("29.99")  
val tax = BigDecimal("0.08")

val subtotal = price1 + price2
val taxAmount = subtotal * tax
val total = subtotal + taxAmount

println(f"Subtotal: $$${subtotal}")
println(f"Tax: $$${taxAmount.setScale(2, BigDecimal.RoundingMode.HALF_UP)}")
println(f"Total: $$${total.setScale(2, BigDecimal.RoundingMode.HALF_UP)}")

// Mathematical sequences
def factorial(n: Int): BigInt = {
  if (n <= 1) BigInt(1)
  else BigInt(n) * factorial(n - 1)
}

val fact10 = factorial(10)
println(s"10! = $fact10")

// Geometric calculations
def distanceBetweenPoints(x1: Double, y1: Double, x2: Double, y2: Double): Double = {
  sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
}

val dist = distanceBetweenPoints(0, 0, 3, 4)
println(f"Distance between points: $dist%.2f")

// Exponential and logarithmic functions
val growth = exp(0.05 * 10) // 5% growth over 10 periods
val halfLife = log(0.5) / log(0.95) // Half-life with 5% decay rate

println(f"10-period growth: ${growth * 100 - 100}%.1f%%")
println(f"Half-life: $halfLife%.1f periods")

Random Number Generation

Random number utilities integrated with JavaScript's Math.random() and providing additional distributions.

/**
 * Random number generator using JavaScript's Math.random()
 * Provides additional utility methods for common random operations
 */
class Random(seed: Long = System.currentTimeMillis()) {
  /** Generate random boolean */
  def nextBoolean(): Boolean
  
  /** Generate random integer in full range */
  def nextInt(): Int
  
  /** Generate random integer from 0 to n-1 */
  def nextInt(n: Int): Int
  
  /** Generate random long */
  def nextLong(): Long
  
  /** Generate random float from 0.0 to 1.0 */
  def nextFloat(): Float
  
  /** Generate random double from 0.0 to 1.0 */
  def nextDouble(): Double
  
  /** Generate random Gaussian (normal) distribution */
  def nextGaussian(): Double
  
  /** Fill array with random bytes */
  def nextBytes(bytes: Array[Byte]): Unit
  
  /** Shuffle array in place */
  def shuffle[T](array: Array[T]): Unit
}

object Random {
  /** Default random instance */
  def apply(): Random = new Random()
  
  /** Seeded random instance */  
  def apply(seed: Long): Random = new Random(seed)
}

Usage Examples:

import scala.util.Random

val random = new Random()

// Basic random generation
val randomInt = random.nextInt(100)        // 0 to 99
val randomDouble = random.nextDouble()     // 0.0 to 1.0
val randomBoolean = random.nextBoolean()  

println(s"Random int: $randomInt")
println(f"Random double: $randomDouble%.3f")
println(s"Random boolean: $randomBoolean")

// Random selection from collection
val colors = Array("red", "green", "blue", "yellow", "purple")
val randomColor = colors(random.nextInt(colors.length))
println(s"Random color: $randomColor")

// Random range generation
def randomRange(min: Int, max: Int): Int = {
  min + random.nextInt(max - min + 1)
}

val diceRoll = randomRange(1, 6)
println(s"Dice roll: $diceRoll")

// Gaussian distribution for natural variation
val baseValue = 100.0
val variation = random.nextGaussian() * 10  // Standard deviation of 10
val naturalValue = baseValue + variation
println(f"Natural variation: $naturalValue%.1f")

// Shuffling collections
val deck = (1 to 52).toArray
random.shuffle(deck)
println(s"Shuffled deck (first 5): ${deck.take(5).mkString(", ")}")

// Weighted random selection
def weightedChoice[T](items: List[(T, Double)]): T = {
  val totalWeight = items.map(_._2).sum
  val randomValue = random.nextDouble() * totalWeight
  
  var cumulativeWeight = 0.0
  for ((item, weight) <- items) {
    cumulativeWeight += weight
    if (randomValue <= cumulativeWeight) {
      return item
    }
  }
  items.last._1 // Fallback
}

val outcomes = List(
  ("common", 0.7),
  ("uncommon", 0.2),
  ("rare", 0.08),
  ("legendary", 0.02)
)

val result = weightedChoice(outcomes)
println(s"Random outcome: $result")

// Seeded random for reproducible results
val seededRandom = new Random(12345)
val sequence1 = (1 to 5).map(_ => seededRandom.nextInt(100))

val seededRandom2 = new Random(12345) // Same seed
val sequence2 = (1 to 5).map(_ => seededRandom2.nextInt(100))

println(s"Sequence 1: ${sequence1.mkString(", ")}")
println(s"Sequence 2: ${sequence2.mkString(", ")}")
println(s"Sequences match: ${sequence1 == sequence2}") // true

Install with Tessl CLI

npx tessl i tessl/maven-org-scala-js--scalajs-scalalib-2-13

docs

collections.md

concurrent.md

core-features.md

index.md

math.md

runtime.md

utilities.md

tile.json