A while back I encountered a bunch of code. The code was built to handle either a single element or an array of those elements. Several functions had this code to handle one or multiple elements. This is a good example of violating the Single Responsibility Principle aka a function should do one thing. These functions were doing two things. They were handling a one versus many situation and then doing their primary task.
Decorative combinators are a great way to separate out this kind of logic. Here is some code I wrote to solve such a situation. The code has been written to handle being used with "this" being involved, but right now it only handles single argument functions. I also haven't put in type information or done the converion to TypeScript decorator. I included the test code to show how it is used, but the interesting part os just the handleElementOrArray function.
var handleElementOrArray = (fn) => {
return function (thing) {
var self = this;
if (Array.isArray(thing)) {
return thing.map(function(x) {
return fn.call(self,x)
})
} else {
return fn.call(self,thing)
}
}
}
function MyObject(adding) {
this.number = adding;
}
MyObject.prototype.addSome = handleElementOrArray(function(num) {
return num+this.number;
})
var myInstance = new MyObject(5);
myInstance.addSome(1); // 6
myInstance.addSome([2,3,4]) // [7,8,9]
Note that I usually use fat arrow, and when I do use the function keyword I am doing so intentionally to control the this keyword.
No comments:
Post a Comment