Implement a module using the Match/Transform pattern
mainAll modules in REstringer must follow the match/transform pattern to separate concerns and ensure predictable orchestration. This pattern consists of three parts:
- Match function:
moduleNameMatch(arb, candidateFilter = () => true)identifies target nodes within the Abstract Representation (arb). - Transform function:
moduleNameTransform(arb, node)modifies the matched nodes. Crucially, this function must explicitly return thearbobject. - Main function: Orchestrates the process by calling the match function, iterating through matches, and capturing the returned
arbfrom each transformation.
Key Requirement: The main function must use arb = moduleNameTransform(arb, matches[i]) to capture the returned state.
// Match function - identifies target nodes
export function moduleNameMatch(arb, candidateFilter = () => true) {
const matches = [];
const candidates = arb.ast[0].typeMap.TargetNodeType
.concat(arb.ast[0].typeMap.AnotherTargetNodeType);
for (let i = 0; i < candidates.length; i++) {
const node = candidates[i];
if (matchesCriteria(node) && candidateFilter(node)) {
matches.push(node);
}
}
return matches;
}
// Transform function - modifies matched nodes
export function moduleNameTransform(arb, node) {
// Apply transformations
performTransformation(node);
return arb; // Must explicitly return arb
}
// Main function - orchestrates match and transform
export default function moduleName(arb, candidateFilter = () => true) {
let currentArb = moduleNameMatch(arb, candidateFilter);
for (let i = 0; i < currentArb.length; i++) {
arb = moduleNameTransform(arb, currentArb[i]); // Capture returned arb
}
return arb;
}