Add destructuring examples

This commit is contained in:
Andrew Morris
2023-03-02 20:56:21 +11:00
parent 7ea97ad22b
commit 6903f9d49f

View File

@@ -108,6 +108,32 @@ const files: Record<string, string | nil> = {
}
`),
"examples/reverse.ts": blockTrim(`
export default function main() {
const values = ['a', 'b', 'c'];
return [values, reverse(values)];
}
function reverse<T>(arr: T[]) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr;
// This version also works:
// arr.reverse();
// return arr;
}
`),
"examples/binaryTree.ts": blockTrim(`
export default function main() {
let tree = new BinaryTree<number>();
@@ -218,6 +244,78 @@ const files: Record<string, string | nil> = {
}
`),
"examples/quickSort.ts": blockTrim(`
export default function main() {
const x = [7, 18, 9, 11, 16, 3, 8, 2, 5, 4, 6, 14, 15, 17, 10, 12, 1, 13];
return quickSort(x, (a, b) => a - b);
}
function quickSort<T>(vals: T[], cmp: (a: T, b: T) => number) {
// Demonstrates the ability to do in-place updates in ValueScript.
//
// There's only one reference to \`vals\`, so we can mutate it in-place
// without violating value semantics.
//
// (At the time of writing the internals aren't very careful about
// minimizing ref counters so this might not be happening, but the logic
// to mutate in-place when the ref count is one is already there. This
// will be optimized/fixed in the future.)
//
// More on quickSort:
// https://www.youtube.com/watch?v=Hoixgm4-P4M
const len = vals.length;
let ranges: [number, number][] = [[0, len - 1]];
while (true) {
const range = ranges.shift();
if (!range) {
return vals;
}
const [start, end] = range;
if (end - start <= 0) {
continue;
}
let i = start;
let j = end;
let pivotIndex = Math.floor((i + j) / 2);
[vals[pivotIndex], vals[j]] = [vals[j], vals[pivotIndex]];
const pivot = vals[j];
j--;
while (true) {
while (cmp(vals[i], pivot) < 0) {
i++;
}
while (cmp(vals[j], pivot) > 0) {
j--;
}
if (i < j) {
[vals[i], vals[j]] = [vals[j], vals[i]];
i++;
j--;
continue;
}
[vals[i], vals[end]] = [vals[end], vals[i]];
ranges.push([start, i - 1]);
ranges.push([i + 1, end]);
break;
}
}
}
`),
"examples/idGenerationError.ts": blockTrim(`
export default function main() {
let nextId = 1;