Rook
РусскийRU

bigint and typed arrays

bigint holds whole numbers of any size: 10n, 0xffn, 2n ** 64n. As in JS, a bigint and a number do not mix in arithmetic, where JS would throw: the compiler asks to convert one of them with BigInt(n) or Number(b). They compare with <, and == between them is an error, since it is always false. For the board, use bigint for IDs or a counter only if they may exceedNumber.MAX_SAFE_INTEGER: it keeps integer values exact, but does not by itself make an ID stable or unique. Otherwise, number is enough.

// bigint: whole numbers of any size, written with n
let factorial = 1n
for let i = 1n; i <= 25n; i++ {
    factorial *= i
}
console.log("25! =", factorial)

// A number loses digits beyond 2^53; a bigint keeps them
console.log(2 ** 64 + 1, 2n ** 64n + 1n)

// bigint and number do not mix in arithmetic: convert one of them
const people = 4
console.log(factorial / BigInt(people), Number(7n) / 2)

byte[] is a Uint8Array, as a byte slice is in Go, and byte is a number from 0 to 255. A list of numbers where a byte[] is expected becomes one, byte[]("text") gives the UTF-8 bytes of a string, and string(bytes) reads them back.

// byte[] is a Uint8Array; byte[]("...") gives the UTF-8 bytes of a string
const bytes = byte[]("rook ♜")
console.log(bytes.length, "bytes:", bytes.join(" "))

// string(bytes) reads them back as text
console.log(string(bytes))

// Numbers where a byte[] is expected make a Uint8Array
let header byte[] = [0x89, 0x50, 0x4e, 0x47]
console.log(string(header.subarray(1)))

// It goes to a goroutine without a copy, with transfer
func checksum(data byte[]) number {
    return data.reduce((sum, b) => (sum + b) % 256, 0)
}
console.log("checksum:", await go checksum(transfer(bytes)), "left here:", bytes.length)

The other typed arrays are written the same way, with the number types of Go: float64[] is a Float64Array, int32[] an Int32Array, and int64[] a BigInt64Array of bigints. make(float64[], n) makes one of n zeros, and make(float64[], n, shared) puts it on a SharedArrayBuffer, which the goroutines of go for write into without copies.

// typed arrays are arrays of the number types of Go: float64[] is a Float64Array,
// and make(float64[], n) makes one of n zeros
const samples = make(float64[], 8)
for i, _ in samples {
    samples[i] = Math.sin(i / 2)
}

let weights float32[] = [0.25, 0.5, 0.25]
let total float64 = 0
for i, w in weights {
    total += w * samples[i]
}
console.log("weighted:", total.toFixed(3))

// int64[] holds bigints
const counts = make(int64[], 3)
counts[0] = 2n ** 62n
console.log("counts:", counts.join(", "))