-
-
Save tobie/5643236 to your computer and use it in GitHub Desktop.
function sortBy(prop) { | |
return function(a, b) { | |
return a[prop].localeCompare(b[prop]); | |
} | |
} | |
[ | |
{ foo: "some text", bar: "other text" }, | |
{ foo: "hello", bar: "world" }, | |
{ foo: "More text", bar: "MOAR" } | |
].sort(sortBy('foo')); |
If you find a better name, I'm all for it. Another place where I use this heavily is in async functions that return continuables that take callback/continuations.
function readFile(path, mode) {
return function (callback) {
fs.readFile(path, mode, callback);
};
}
Though in that case, it's really just manual partial-application. (aka currying)
Closure factory sounds explicit enough. How do you name the actual function, though?
This looks very similar to partial application, without partial flexibility on the number of arguments you set before hand. Underscore probably has something like that.
This could give you an idea about naming your own version.
Yeah, it is similar to partial application, except you never intend to use the original function without partial application first, so there's no need to expose it.
You've got some state and a function which makes use of it... how about calling it lower-case version of whatever you'd name a similar constructor which took the same thing as state and had a method which made use of it?
e.g. sorter
for this one?
When I'm making a closure or object factory, I often name it newConstructor
where Constructor
is what I would have called it in constructor form. Then calling newConstructor(args)
vs new Constructor(args)
is close in syntax.
In the case of the async functions returning a continuable, I just name it what it does like readFile
. In this case, the returned closure is like a light-weight future/promise.
For my stream filter functions, I just name them what they do, but in the generator tense (decoder vs decode).
function decoder(emit) {
return function (err, item) {
// something was written to us
};
}
var decode = decoder(function (err, item) {
// it emitted something
});
// Write to the filter
decode(null, data);
Yeah I didn't mean to replace it with partial, just that it's a word that could be part of the name of such a fn. But the other suggestions seem more appropriate and maybe less confusing too.
It's just a higher-order function. Being a closure would imply some context to be captured, but here you're passing it to the function so it's not happening.
About naming the function, I believe that sortBy
conveys the right information and would not change it.
I've always called them closure factories when they return a function directly and object factories when they return an object with functions on it.
Also, my min-stream stuff I've been working on has tons of these. https://github.com/creationix/min-stream/blob/master/README.md#the-interface