I have a specific block of code (the forEach loop) that I use all over the place in my code base, whenever I have an "item".
How can I refactor this into a module or a global function that I can call whenever I need to.
Here's the context:
Item.findById(itemid).populate('wants').exec(function(err, item){
item.wants.forEach(function(person){
person.avatar = gravatar.url(person.email, {size: 80, default: 'mm' });
});
//do some more stuff with item
});
I want to re-use this forEach loop in other places where I have an "item" object. I'm thinking I pass in the item object and return it again.
item.wants.forEach(function(person){
person.avatar = gravatar.url(person.email, {size: 80, default: 'mm' });
});
Something like:
var myLib = require('./lib/myLib');
...
item = myLib.doStuff( item );
Your ./lib/myLib.js
file would look like this:
module.exports.doStuff = function(item) {
item.wants.forEach(function(person){
person.avatar = gravatar.url(person.email, {size: 80, default: 'mm' });
});
return item;
}
You can then require and use like you outlined already:
var myLib = require('./lib/myLib');
item = myLib.doStuff( item );