Certainly! Below is the refactored version of the findMostAncestralElements function. The inlined matches and overlaps logic have been extracted into separate helper functions: isMatch and isOverlap. Additionally, destructuring assignments are used for objects with multiple property accesses to enhance readability and performance.
Refactored Function
/**
* Finds the most ancestral DOM elements enclosed within a specified rectangle in page coordinates
* with an allowed ratio error. Uses BFS for traversal with performance optimizations.
*
* @param {number} x - The X-coordinate of the target rectangle (relative to the viewport).
* @param {number} y - The Y-coordinate of the target rectangle (relative to the viewport).
* @param {number} width - The width of the target rectangle.
* @param {number} height - The height of the target rectangle.
* @param {number} errorRatio - The allowed error ratio (0 to 1) for matching.
* @param {Object} [options] - Optional settings.
* @param {boolean} [options.exhaustive=true] - If true, performs an exhaustive search.
* @param {number} [options.asyncIterations] - Number of iterations per asynchronous batch.
* If null, undefined, or <= 0, executes synchronously.
* @param {Function} [options.onProgress] - Callback function to receive progress updates.
* @returns {Promise<Element[]>|Element[]} A promise that resolves to an array of the most ancestral DOM elements matching the criteria, or the array directly if not asynchronous.
*/
function findMostAncestralElements(
x,
y,
width,
height,
errorRatio,
options = {}
) {
const {
exhaustive = true,
asyncIterations, // Renamed from 'async' to 'asyncIterations'
onProgress,
} = options;
// Determine if the function should execute asynchronously
const isAsync = typeof asyncIterations === 'number' && asyncIterations > 0;
const iterationBatch = isAsync ? asyncIterations : null;
// Clamp errorRatio between 0 and 1
const z = Math.max(0, Math.min(errorRatio, 1));
const target = { x, y, width, height };
const results = new Set();
const queue = [document.body];
let head = 0;
/**
* Checks if a rectangle matches the target within the allowed error ratio.
*
* @param {DOMRect} rect - The bounding rectangle of an element.
* @param {Object} target - The target rectangle with properties x, y, width, height.
* @param {number} z - The clamped error ratio.
* @returns {boolean} True if the rect matches the target within the error ratio, else false.
*/
function isMatch(rect, target, z) {
const { left, top, width: rectWidth, height: rectHeight } = rect;
const { x, y, width: targetWidth, height: targetHeight } = target;
return (
Math.abs(left - x) <= targetWidth * z &&
Math.abs(top - y) <= targetHeight * z &&
Math.abs(rectWidth - targetWidth) <= targetWidth * z &&
Math.abs(rectHeight - targetHeight) <= targetHeight * z
);
}
/**
* Checks if a rectangle overlaps with the target rectangle.
*
* @param {DOMRect} rect - The bounding rectangle of an element.
* @param {Object} target - The target rectangle with properties x, y, width, height.
* @returns {boolean} True if the rect overlaps with the target, else false.
*/
function isOverlap(rect, target) {
const { left, top, width: rectWidth, height: rectHeight } = rect;
const { x, y, width: targetWidth, height: targetHeight } = target;
return (
left < x + targetWidth &&
left + rectWidth > x &&
top < y + targetHeight &&
top + rectHeight > y
);
}
/**
* Processes a batch of elements from the queue asynchronously.
*
* @returns {Promise<void>} Resolves when the batch is processed.
*/
function processBatchAsync() {
return new Promise((resolve) => {
let processed = 0;
while (head < queue.length && processed < iterationBatch) {
const elem = queue[head++];
const rect = elem.getBoundingClientRect();
if (isMatch(rect, target, z)) {
results.add(elem);
// Skip enqueuing children to maintain ancestry
} else if (exhaustive || isOverlap(rect, target)) {
const children = elem.children;
for (let i = 0, len = children.length; i < len; i++) {
queue.push(children[i]);
}
}
processed++;
}
if (onProgress) {
onProgress({
processedElements: head,
totalQueued: queue.length,
uniqueResults: results.size,
});
}
resolve();
});
}
if (isAsync) {
return new Promise((resolve) => {
function iterate() {
processBatchAsync().then(() => {
if (head < queue.length) {
setTimeout(iterate, 0);
} else {
resolve(Array.from(results));
}
});
}
iterate();
});
} else {
// Synchronous Processing
while (head < queue.length) {
const elem = queue[head++];
const rect = elem.getBoundingClientRect();
if (isMatch(rect, target, z)) {
results.add(elem);
continue; // Skip enqueuing children to maintain ancestry
}
if (exhaustive || isOverlap(rect, target)) {
const children = elem.children;
for (let i = 0, len = children.length; i < len; i++) {
queue.push(children[i]);
}
}
}
return Array.from(results);
}
}
Changes and Improvements
-
Extracted Helper Functions:
isMatch: Determines if an element's bounding rectangle matches the target rectangle within the allowed error ratio.
isOverlap: Determines if an element's bounding rectangle overlaps with the target rectangle.
-
Destructuring Assignments:
- Within Helper Functions: Destructured properties from
rect and target to avoid repetitive object property access.
- Main Function: Destructured
options at the beginning for cleaner access to optional parameters.
-
Code Organization:
- The helper functions are defined within the main
findMostAncestralElements function to keep them encapsulated and avoid polluting the global scope.
- Enhanced readability by separating concerns, making the main traversal logic clearer.
-
Preserved Asynchronous Behavior:
- The asynchronous processing remains intact, allowing the function to handle large DOM trees without blocking the main thread.
Benefits of Refactoring
- Readability: By abstracting complex logical conditions into well-named functions, the code becomes easier to understand.
- Maintainability: If the matching or overlapping criteria need to change in the future, they can be updated in a single place.
- Performance: Destructuring reduces the number of property accesses, which can offer minor performance benefits, especially in large loops.
- Reusability: The helper functions can be reused or tested independently if needed.
Feel free to integrate this refactored function into your codebase. It maintains the original functionality while enhancing clarity and maintainability.