Skip to content

Commit

Permalink
perf(primordials): Check the need for SafeArrayIterator each time
Browse files Browse the repository at this point in the history
  • Loading branch information
petamoriken committed Sep 1, 2023
1 parent 8d25c67 commit c6a5c1d
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions core/00_primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,8 @@
});

const {
ArrayIteratorPrototype,
ArrayPrototype,
ArrayPrototypeForEach,
ArrayPrototypeJoin,
ArrayPrototypeMap,
Expand All @@ -305,15 +307,21 @@
PromisePrototype,
PromisePrototypeThen,
SymbolIterator,
TypedArrayPrototype,
TypedArrayPrototypeJoin,
} = primordials;

// Because these functions are used by `makeSafe`, which is exposed
// on the `primordials` object, it's important to use const references
// to the primordials that they use:
const createSafeIterator = (factory, next) => {
const createSafeIterator = (factory, next, check) => {
class SafeIterator {
constructor(iterable) {
// https://github.com/denoland/deno_core/issues/6
if (check?.(iterable) === true) {
return iterable;
}

this._iterator = factory(iterable);
}
next() {
Expand All @@ -329,11 +337,19 @@
return SafeIterator;
};

const SafeArrayIterator = createSafeIterator(
const OriginalArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
const OriginalTypedArrayPrototypeSymbolIterator =
TypedArrayPrototype[SymbolIterator];
const OriginalArrayIteratorPrototypeNext = ArrayIteratorPrototype.next;
const SafeArrayIterator = primordials.SafeArrayIterator = createSafeIterator(
primordials.ArrayPrototypeSymbolIterator,
primordials.ArrayIteratorPrototypeNext,
(iterable) =>
(iterable[SymbolIterator] === OriginalArrayPrototypeSymbolIterator ||
iterable[SymbolIterator] ===
OriginalTypedArrayPrototypeSymbolIterator) &&
ArrayIteratorPrototype.next === OriginalArrayIteratorPrototypeNext,
);
primordials.SafeArrayIterator = SafeArrayIterator;
primordials.SafeSetIterator = createSafeIterator(
primordials.SetPrototypeSymbolIterator,
primordials.SetIteratorPrototypeNext,
Expand Down

0 comments on commit c6a5c1d

Please sign in to comment.