Batman Batman - 1 month ago 5
jQuery Question

Passing object properties as function argument?

I have these three functions that basically do the same thing. They take data coming from the promise and make an object with the same properties for each function.

I would like to DRY this out:

var getFiles = function() {
return wg.getFiles().then(function(data) {
processData(data, {
type: "File",
title: x.filename,
created: x.Created,
path: x.path
})
})
}

var getEvents = function() {
return wg.getEvents().then(function(data) {
processData(data, {
type: "Event",
title: x.Title,
created: x.Created,
path: x.path
})
})
}

var getFeedback = function() {
return wg.getFeedback().then(function(data) {
processData(data, {
type: "Review",
title: "by " + x.Author,
created: x.Created,
path: x.path
})
})
}
var processData = function(data, props) {
var x = _(data)
.map(function(x) {return props})
.value()
.map(function(x) {
activties.push(x)
})
}


I would like to DRY this out by changing the
processData
function to something like this:

var processData = function(data, props) {
var x = _(data)
.map(function(x) {
return {
type: x[props[0]],
title: x[props[1]],
created: x[props[3]],
path: "/" + x[props[4]]
}
})
.value()
.map(function(x) {
activties.push(x)
})
}


Then I could call it like this:

var getFiles = function() {
return wg.getFiles().then(function(data) {
processData(data, ['filename', 'created', ['FileRef']['lookupValue']])

})
}


That's what I have in mind but if anyone has anything better I'm open.

Answer

Don't pass property names, pass functions:

function getFiles() {
    return wg.getFiles().then(processData("File", _.property("filename")));
}

function getEvents() {
    return wg.getEvents().then(processData("Event", _.property("Title")));
}

function getFeedback() {
    return wg.getFeedback().then(processData("Review", function(x) { return "by " + x.Author; })));
}

function processData(type, makeTitle) {
    return function(data) {
        return data.map(function(x) {
            return {
                type: type,
                title: makeTitle(x),
                created: x.Created,
                path: x.path
            };
        });
    };
}

Promise.all([getFiles(), getEvents(), getFeedback()])
.then(function(arrays) {
    var activities = _.flatten(arrays);
    …
});

For convenience I used some underscore/lodash functions, but you can do it without them as well.

Comments