Skip to content

Commit

Permalink
fix: dont visit non-visitable values in WeakMaps
Browse files Browse the repository at this point in the history
  • Loading branch information
kumavis committed Dec 12, 2023
1 parent 864378d commit 4dd52bb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@ function* walkIterativelyPublic (target, config, maxDepth, visited = new Set(),
// as we discover and walk them, new WeakMaps and references may be discovered
// the weakMapTracker will continue to iterate them until they are exhausted
for (const [childValue, childPath, childMaxDepth] of tracker.flushAll()) {
if (!shouldVisit(childValue, visited, config.shouldWalk)) {
continue;
}
yield [childValue, childPath, childMaxDepth];
tracker.visitValue(childValue, childPath, childMaxDepth);
const weakMapValueSubTree = walkIteratively(childValue, config, childMaxDepth, visited, childPath);
Expand All @@ -230,10 +233,10 @@ const walkIteratively = function*(target, config, maxDepth, visited, path) {
const props = getAllProps(target, config.shouldInvokeGetters, config.getAdditionalProps);
const childMaxDepth = maxDepth - 1;
for (const [key, childValue] of props) {
const childPath = [...path, config.generateKey(key, childValue)];
if (!shouldVisit(childValue, visited, config.shouldWalk)) {
continue;
}
const childPath = [...path, config.generateKey(key, childValue)];
yield [childValue, childPath, childMaxDepth];
const subTreeIterator = walkIteratively(childValue, config, childMaxDepth, visited, childPath);
if (config.depthFirst) {
Expand Down
31 changes: 31 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import test from 'ava';
import LavaTube from '../src/index.js';

test('non-visitable initial value', t => {
const start = 1;
const allValues = getAll({}, start);
t.deepEqual(allValues, []);
})

test('exhaustiveWeakMapSearch', t => {
const map = new WeakMap();
const obj = {};
Expand All @@ -23,6 +29,23 @@ test('exhaustiveWeakMapSearch', t => {
]);
})

test('exhaustiveWeakMapSearch - non-visitable', t => {
const map = new WeakMap();
const obj = {};
const nonVistitable = 'abc'
map.set(obj, nonVistitable);
const start = {
map,
obj,
};
const opts = {
exhaustiveWeakMapSearch: true,
}

const allValues = getAll(opts, start);
t.false(allValues.includes(nonVistitable));
})

test('exhaustiveWeakMapSearch - deep', t => {
const firstWeakMap = new WeakMap()
let lastWeakMap = firstWeakMap
Expand Down Expand Up @@ -62,4 +85,12 @@ function find (opts, start, target) {
}
});
return result;
}

function getAll (opts, start) {
const results = [];
new LavaTube(opts).walk(start, (value, path) => {
results.push(value);
});
return results;
}

0 comments on commit 4dd52bb

Please sign in to comment.