Replace body with callback removes duplication by separating a repeated before-and-after structure from the code that varies between them. The varying behavior becomes a function argument—a callback—so the surrounding function can be reused. section 10.1 section 10.15
Apply the refactoring in three steps:
- Identify the before, body, and after sections. The before and after remain stable; the body changes. section 10.11
- Extract the complete before-body-after structure into a function. section 10.1
- Extract the body into a callback parameter and invoke it between the unchanged sections. section 11.1
Reusable array copying
Repeated copy-on-write functions make a copy, modify it, and return it. Extracting the modification produces: function withArrayCopy(array, modify) { var copy = array.slice(); modify(copy); return copy; } A setter can then call withArrayCopy(array, function(copy) { copy[idx] = value; }); The same helper supports pushing, removing elements, or sorting. section 11.3
Wrapping try/catch once
When many operations share identical error handling, pass the operation as a callback: function tryCatch(f, errorHandler) { try { return f(); } catch(error) { return errorHandler(error); } } A call such as tryCatch(sendEmail, logToSnapErrors) reuses the surrounding syntax while varying the operation. section 11.3 section 10.11
function arraySet(array, idx, value) {
return withArrayCopy(array, function(copy) {
copy[idx] = value;
});
}
function withArrayCopy(array, modify) { #1
var copy = array.slice();
modify(copy);
return copy;
}
Inspect the compact JavaScript transformation from a specialized array setter to a reusable copy helper with a modify callback. section 11.3
