Snippets: AssemblyScript
These are the AssemblyScript snippets the console offers in a .as module. A module computes and reaches nothing: a script imports it and hands it copies of its arguments.
Sum a list of numbers
An exported function a script imports. A module is handed copies of its arguments and reaches nothing else, so it only computes.
export function sum(values: Float64Array): f64 { let total: f64 = 0; for (let i = 0; i < values.length; i++) total += unchecked(values[i]); return total;}Hash a text
FNV-1a over a string, a fast way to compare large texts. Import it in a script with import { fnv1a } from “./hash.as”.
export function fnv1a(text: string): u32 { let hash: u32 = 0x811c9dc5; for (let i = 0; i < text.length; i++) { hash ^= <u32>text.charCodeAt(i); hash *= 0x01000193; } return hash;}Score how alike two texts are
The edit distance between two strings, for finding near-duplicate summaries. Linear memory, no allocations in the loop.
export function distance(a: string, b: string): i32 { const row = new Int32Array(b.length + 1); for (let j = 0; j <= b.length; j++) row[j] = j; for (let i = 1; i <= a.length; i++) { let previous = row[0]; row[0] = i; for (let j = 1; j <= b.length; j++) { const current = row[j]; const cost = a.charCodeAt(i - 1) == b.charCodeAt(j - 1) ? 0 : 1; row[j] = min(min(row[j] + 1, row[j - 1] + 1), previous + cost); previous = current; } } return row[b.length];}Related
A problem or a question? Write to support@oktul.com or open a request in the Help Center (opens in a new tab). Both reach the same service desk, so either way the request gets a reference and an SLA measuring the response.