GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(codemode): add Uint8Array callback methods and coerce indexOf st… · Parad0X/opencode@14a3311

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/codemode
    • interpreter-support.md
    • src/stdlib
      • array.ts
      • bytes.ts
    • test
      • stdlib.test.ts
      • test262
        • skipped.txt
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/codemode/interpreter-support.md‎

Copy file name to clipboardExpand all lines: packages/codemode/interpreter-support.md
+9-3Lines changed: 9 additions & 3 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,8 @@ reject }` object.
310310
`(value, index)` arguments and stepwise synchronous iterator consumption.
311311
- [x] Iteration/transformation: `map`, `filter`, `flatMap`, and `forEach`.
312312
- [x] Searching/tests: `find`, `findIndex`, `findLast`, `findLastIndex`, `some`, `every`, `includes`, `indexOf`, and
313-
`lastIndexOf`.
313+
`lastIndexOf`. An explicit `undefined` fromIndex counts as present: `[1, 2, 1].lastIndexOf(1, undefined)` is `0`
314+
while `lastIndexOf(1)` is `2`.
314315
- [x] Aggregation: `reduce` and `reduceRight`.
315316
- [x] Ordering: `sort`, `toSorted`, `reverse`, and `toReversed`.
316317
- [x] Access/copying: `at`, `slice`, `concat`, `flat`, `with`, `join`, and `toLocaleString` (each element's
@@ -495,11 +496,16 @@ with a hint to encode as text first (`TextDecoder`, `toBase64`, `toHex`).
495496
cannot be deleted. `length` is a prototype accessor, so `Object.keys` lists only indexes.
496497
- [x] `at`, `slice`, `subarray` (a view on the same bytes), `set`, `fill`, `reverse`, `indexOf`, `lastIndexOf`,
497498
`includes`, `join`, `toString`, `toBase64`, `toHex`, and live `keys`, `values`, `entries`, and `[Symbol.iterator]`
498-
iterators.
499+
iterators. Start indexes coerce as for arrays, and `lastIndexOf(x, undefined)` searches from index 0 while
500+
`lastIndexOf(x)` searches from the end, as in JS.
499501
- [x] Spread, destructuring, `for...of`, `yield*`, `Array.from`, and `new Set(bytes)`. `Array.isArray` is false.
500502
- [x] String coercion joins with commas; `JSON.stringify` gives `{"0":1,...}`; `console.log` prints
501503
`Uint8Array(n) [...]`.
502-
- [ ] Callback methods (`forEach`, `map`, `filter`, `find`, `reduce`, ...); use `Array.from(bytes, fn)` meanwhile.
504+
- [x] Callback methods `forEach`, `map`, `filter`, `find`, `findIndex`, `findLast`, `findLastIndex`, `some`, `every`,
505+
`reduce`, and `reduceRight`, sharing the Array implementations; the callback receives `(byte, index, bytes)`.
506+
`map` and `filter` return new Uint8Arrays with results clamped like index writes (`map((b) => b * 100)` on
507+
`[1, 2, 3]` is `[100, 200, 44]`); `reduce` on an empty Uint8Array without an initial value is a `TypeError`.
508+
- [x] `sort` in place, numeric ascending by default (`[10, 9, 1]` sorts to `[1, 9, 10]`) or by comparator.
503509
- [ ] `ArrayBuffer`, `DataView`, and other typed arrays.
504510

505511
## Web platform helpers
Collapse file

‎packages/codemode/src/stdlib/array.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/src/stdlib/array.ts
+59-37Lines changed: 59 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -125,24 +125,6 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
125125

126126
const self = (thisValue: Value, name: string) => receiver(Arr, thisValue, `Array.prototype.${name}`)
127127
const optNumber = (value: Value): number | undefined => (value === undefined ? undefined : coerceToInteger(value))
128-
// Callback methods fix the iteration length while reading existing elements live.
129-
const iterate = (
130-
name: string,
131-
length: number,
132-
body: (
133-
target: Array<Value>,
134-
receiver: Arr,
135-
apply: (args: Array<Value>) => Effect.Effect<Value, unknown, R>,
136-
args: Array<Value>,
137-
) => Effect.Effect<Value, unknown, R>,
138-
): Method => [
139-
name,
140-
length,
141-
(thisValue, args) => {
142-
const target = self(thisValue, name)
143-
return body(target.items, target, applyCollectionCallback(ctx, args[0], `Array.${name}`), args)
144-
},
145-
]
146128

147129
methods(builtins, proto, [
148130
[
@@ -177,7 +159,8 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
177159
1,
178160
(thisValue, args) => {
179161
const target = self(thisValue, "lastIndexOf").items
180-
return args[1] === undefined ? target.lastIndexOf(args[0]) : target.lastIndexOf(args[0], optNumber(args[1]))
162+
// An explicit undefined is a fromIndex of 0, unlike omitting it.
163+
return args.length < 2 ? target.lastIndexOf(args[0]) : target.lastIndexOf(args[0], optNumber(args[1]))
181164
},
182165
],
183166
["at", 1, (thisValue, args) => self(thisValue, "at").items.at(optNumber(args[0]) ?? 0)],
@@ -349,6 +332,60 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
349332
.map(([index, item]) => wrap([index, item])),
350333
),
351334
],
335+
[
336+
"flatMap",
337+
1,
338+
(thisValue, args) => {
339+
const target = self(thisValue, "flatMap")
340+
const apply = applyCollectionCallback(ctx, args[0], "Array.flatMap")
341+
return Effect.gen(function* () {
342+
const length = target.items.length
343+
const values: Array<Value> = []
344+
for (let index = 0; index < length; index += 1) {
345+
if (!(index in target.items)) continue
346+
const mapped = yield* apply([target.items[index], index, target])
347+
if (mapped instanceof Arr) values.push(...mapped.items)
348+
else values.push(mapped)
349+
}
350+
return wrap(values)
351+
})
352+
},
353+
],
354+
...callbackMethods(ctx, "Array", self, (target) => target.items, wrap),
355+
])
356+
define(proto, IteratorSymbol, get(proto, "values"), hidden)
357+
return array
358+
}
359+
360+
/**
361+
* The callback methods Array and Uint8Array share. They fix the iteration length while reading existing elements
362+
* live; `wrap` builds the collection `map` and `filter` return.
363+
*/
364+
export const callbackMethods = <R, T extends Obj>(
365+
ctx: Interpreter<R>,
366+
label: string,
367+
self: (thisValue: Value, name: string) => T,
368+
elements: (target: T) => ArrayLike<Value>,
369+
wrap: (values: Array<Value>) => Value,
370+
): Array<Method> => {
371+
const iterate = (
372+
name: string,
373+
length: number,
374+
body: (
375+
target: ArrayLike<Value>,
376+
receiver: T,
377+
apply: (args: Array<Value>) => Effect.Effect<Value, unknown, R>,
378+
args: Array<Value>,
379+
) => Effect.Effect<Value, unknown, R>,
380+
): Method => [
381+
name,
382+
length,
383+
(thisValue, args) => {
384+
const target = self(thisValue, name)
385+
return body(elements(target), target, applyCollectionCallback(ctx, args[0], `${label}.${name}`), args)
386+
},
387+
]
388+
return [
352389
iterate("map", 1, (target, receiver, apply) =>
353390
Effect.gen(function* () {
354391
const length = target.length
@@ -361,19 +398,6 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
361398
return wrap(values)
362399
}),
363400
),
364-
iterate("flatMap", 1, (target, receiver, apply) =>
365-
Effect.gen(function* () {
366-
const length = target.length
367-
const values: Array<Value> = []
368-
for (let index = 0; index < length; index += 1) {
369-
if (!(index in target)) continue
370-
const mapped = yield* apply([target[index], index, receiver])
371-
if (mapped instanceof Arr) values.push(...mapped.items)
372-
else values.push(mapped)
373-
}
374-
return wrap(values)
375-
}),
376-
),
377401
iterate("filter", 1, (target, receiver, apply) =>
378402
Effect.gen(function* () {
379403
const length = target.length
@@ -459,7 +483,7 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
459483
if (args.length < 2) {
460484
while (start < length && !(start in target)) start += 1
461485
if (start === length) {
462-
throw typeError("Array.reduce of an empty array with no initial value.")
486+
throw typeError(`${label}.reduce of an empty array with no initial value.`)
463487
}
464488
accumulator = target[start]
465489
start += 1
@@ -478,7 +502,7 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
478502
if (args.length < 2) {
479503
while (start >= 0 && !(start in target)) start -= 1
480504
if (start < 0) {
481-
throw typeError("Array.reduceRight of an empty array with no initial value.")
505+
throw typeError(`${label}.reduceRight of an empty array with no initial value.`)
482506
}
483507
accumulator = target[start]
484508
start -= 1
@@ -490,7 +514,5 @@ export const arrayGlobal = <R>(ctx: Interpreter<R>) => {
490514
return accumulator
491515
}),
492516
),
493-
])
494-
define(proto, IteratorSymbol, get(proto, "values"), hidden)
495-
return array
517+
]
496518
}
Collapse file

‎packages/codemode/src/stdlib/bytes.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/src/stdlib/bytes.ts
+25-1Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../interpreter/objects.js"
1919
import { describeValue } from "../interpreter/references.js"
2020
import type { Interpreter } from "../interpreter/interpreter.js"
21+
import { callbackMethods, sortArray } from "./array.js"
2122

2223
/** The bytes a Uint8Array, array, or other iterable of numbers describes; the host array clamps each value. */
2324
const collectBytes = <R>(ctx: Interpreter<R>, source: Value, name: string): Effect.Effect<Uint8Array, unknown, R> => {
@@ -125,6 +126,22 @@ export const uint8ArrayGlobal = <R>(ctx: Interpreter<R>) => {
125126
return target
126127
},
127128
],
129+
[
130+
"sort",
131+
1,
132+
(thisValue, args) => {
133+
const target = self(thisValue, "sort")
134+
// Without a comparator, typed arrays sort numerically rather than by string.
135+
if (args[0] === undefined) {
136+
target.bytes.sort()
137+
return target
138+
}
139+
return Effect.map(sortArray(ctx, [...target.bytes], args[0], "Uint8Array.sort"), (sorted) => {
140+
target.bytes.set(Uint8Array.from(sorted, coerceToNumber))
141+
return target
142+
})
143+
},
144+
],
128145
[
129146
"indexOf",
130147
1,
@@ -135,7 +152,7 @@ export const uint8ArrayGlobal = <R>(ctx: Interpreter<R>) => {
135152
1,
136153
(thisValue, args) => {
137154
const target = self(thisValue, "lastIndexOf").bytes
138-
return args[1] === undefined
155+
return args.length < 2
139156
? target.lastIndexOf(coerceToNumber(args[0]))
140157
: target.lastIndexOf(coerceToNumber(args[0]), optNumber(args[1]))
141158
},
@@ -170,6 +187,13 @@ export const uint8ArrayGlobal = <R>(ctx: Interpreter<R>) => {
170187
.map(([index, byte]) => wrapAll([index, byte])),
171188
),
172189
],
190+
...callbackMethods(
191+
ctx,
192+
"Uint8Array",
193+
self,
194+
(target) => target.bytes,
195+
(values) => wrap(Uint8Array.from(values, coerceToNumber)),
196+
),
173197
])
174198
define(proto, IteratorSymbol, get(proto, "values"), hidden)
175199
return uint8Array
Collapse file

‎packages/codemode/test/stdlib.test.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/test/stdlib.test.ts
+95-1Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1173,7 +1173,7 @@ describe("TextEncoder and TextDecoder", () => {
11731173
test("crypto.getRandomValues fills the given bytes in place", async () => {
11741174
expect(
11751175
await value(
1176-
`const b = new Uint8Array(16); const same = crypto.getRandomValues(b) === b; return [same, b.length, b.some ? 0 : Array.from(b).some((n) => n !== 0)]`,
1176+
`const b = new Uint8Array(16); const same = crypto.getRandomValues(b) === b; return [same, b.length, b.some((n) => n !== 0)]`,
11771177
),
11781178
).toEqual([true, 16, true])
11791179
expect((await error(`crypto.getRandomValues([1])`)).message).toContain("expects a Uint8Array, received an array")
@@ -1923,3 +1923,97 @@ describe("CodeMode values at intra-CodeMode checkpoints", () => {
19231923
expect(observed).toStrictEqual([{ when: "1970-01-01T00:00:00.000Z", tags: {} }])
19241924
})
19251925
})
1926+
1927+
describe("Uint8Array callback methods", () => {
1928+
test("map and filter return new Uint8Arrays with clamped bytes", async () => {
1929+
expect(
1930+
await value(`
1931+
const b = new Uint8Array([1, 2, 3])
1932+
const mapped = b.map((byte) => byte * 100)
1933+
const filtered = b.filter((byte) => byte > 1)
1934+
mapped[0] = 9
1935+
return [
1936+
[...mapped], mapped instanceof Uint8Array, Array.isArray(mapped), [...b], [...filtered],
1937+
[...b.map(() => "7")], b.map((byte) => byte, {}).length, [...new Uint8Array().map((byte) => byte)],
1938+
]
1939+
`),
1940+
).toEqual([[9, 200, 44], true, false, [1, 2, 3], [2, 3], [7, 7, 7], 3, []])
1941+
})
1942+
1943+
test("find, findIndex, findLast, findLastIndex, some, every, and forEach", async () => {
1944+
expect(
1945+
await value(`
1946+
const b = new Uint8Array([1, 2, 3])
1947+
const seen = []
1948+
b.forEach((byte, index, array) => seen.push([byte, index, array === b]))
1949+
return [
1950+
b.find((byte) => byte > 1), b.find((byte) => byte > 5) === undefined, b.findIndex((byte) => byte > 1),
1951+
b.findIndex((byte) => byte > 5), b.findLast((byte) => byte < 3), b.findLastIndex((byte) => byte < 3),
1952+
b.findLastIndex((byte) => byte > 9), b.some((byte) => byte > 2), b.every((byte) => byte > 2),
1953+
new Uint8Array().some(() => true), new Uint8Array().every(() => false),
1954+
b.every((byte, index, array) => array === b), seen,
1955+
]
1956+
`),
1957+
).toEqual([
1958+
2,
1959+
true,
1960+
1,
1961+
-1,
1962+
2,
1963+
1,
1964+
-1,
1965+
true,
1966+
false,
1967+
false,
1968+
true,
1969+
true,
1970+
[
1971+
[1, 0, true],
1972+
[2, 1, true],
1973+
[3, 2, true],
1974+
],
1975+
])
1976+
})
1977+
1978+
test("reduce and reduceRight", async () => {
1979+
expect(
1980+
await value(`
1981+
const b = new Uint8Array([1, 2, 3])
1982+
return [
1983+
b.reduce((sum, byte) => sum + byte), b.reduce((sum, byte) => sum + byte, 10),
1984+
b.reduceRight((text, byte) => text + byte, ""), new Uint8Array().reduce((sum, byte) => sum + byte, 5),
1985+
b.reduce((_, byte, index, array) => array === b && index, 0),
1986+
]
1987+
`),
1988+
).toEqual([6, 16, "321", 5, 2])
1989+
expect((await error(`new Uint8Array().reduce((sum, byte) => sum + byte)`)).message).toContain(
1990+
"Uint8Array.reduce of an empty array with no initial value",
1991+
)
1992+
expect((await error(`new Uint8Array().reduceRight((sum, byte) => sum + byte)`)).message).toContain(
1993+
"Uint8Array.reduceRight of an empty array with no initial value",
1994+
)
1995+
expect((await error(`new Uint8Array([1]).map(null)`)).message).toContain("Uint8Array.map expects a function")
1996+
})
1997+
1998+
test("sort is numeric by default and in place, with an optional comparator", async () => {
1999+
expect(
2000+
await value(`
2001+
const b = new Uint8Array([10, 9, 1])
2002+
const same = b.sort() === b
2003+
const desc = new Uint8Array([3, 1, 2]).sort((x, y) => y - x)
2004+
return [same, [...b], [...desc], desc instanceof Uint8Array, [...new Uint8Array([2, 1]).sort(() => NaN)]]
2005+
`),
2006+
).toEqual([true, [1, 9, 10], [3, 2, 1], true, [2, 1]])
2007+
expect((await error(`new Uint8Array([2, 1]).sort(null)`)).message).toContain("Uint8Array.sort expects a function")
2008+
})
2009+
2010+
test("lastIndexOf treats an explicit undefined fromIndex as 0", async () => {
2011+
expect(
2012+
await value(`
2013+
const a = [1, 2, 1]
2014+
const b = new Uint8Array([1, 2, 1])
2015+
return [a.lastIndexOf(1, undefined), a.lastIndexOf(1), a.lastIndexOf(2, undefined), b.lastIndexOf(1, undefined), b.lastIndexOf(1)]
2016+
`),
2017+
).toEqual([0, 2, -1, 0, 2])
2018+
})
2019+
})
Collapse file

‎packages/codemode/test/test262/skipped.txt‎

Copy file name to clipboardExpand all lines: packages/codemode/test/test262/skipped.txt
-1Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-22.js # Array.lastIndexOf exp
6464
built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-23.js # Array.lastIndexOf expects start index to be a number.
6565
built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-24.js # toStringAccessed
6666
built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-25.js # … cannot be constructed: user-defined constructors and classes are not supported. Call it as a funct
67-
built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-4.js # a.lastIndexOf(2,undefined) Expected SameValue(«1», «-1») to be true
6867
built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-7.js # Array assignment result contains a circular value.
6968
built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-3.js # Array.lastIndexOf expects start index to be a number.
7069
built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-7.js # [, , , ].lastIndexOf(true) Expected SameValue(«-1», «0») to be true

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.