Skip to content

Commit

Permalink
Update safe utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
petamoriken committed Jan 10, 2022
1 parent 207f65b commit bf939ad
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions src/_util/arrayIterator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,24 @@ import {
WeakMapPrototypeSet,
} from "./primordials.mjs";

/** @type {WeakMap<{}, IterableIterator<any>>} */
const arrayIterators = new NativeWeakMap();

const SafeIteratorPrototype = ObjectCreate(null, {
next: {
value: function next() {
const arrayIterator = WeakMapPrototypeGet(arrayIterators, this);
return ArrayIteratorPrototypeNext(arrayIterator);
},
},

[SymbolIterator]: {
value: function values() {
return this;
},
},
});

/**
* Wrap ArrayIterator If Array.prototype [@@iterator] has been modified
*
Expand All @@ -25,20 +43,9 @@ export function safe(array) {
return array;
}

const arrayIterator = ArrayPrototypeSymbolIterator(array);
return ObjectCreate(null, {
next: {
value: function next() {
return ArrayIteratorPrototypeNext(arrayIterator);
},
},

[SymbolIterator]: {
value: function values() {
return this;
},
},
});
const safe = ObjectCreate(SafeIteratorPrototype);
WeakMapPrototypeSet(arrayIterators, safe, ArrayPrototypeSymbolIterator(array));
return safe;
}

/** @type {WeakMap<{}, Generator<any>>} */
Expand Down

0 comments on commit bf939ad

Please sign in to comment.