Skip to content

Instantly share code, notes, and snippets.

@grabbeh
Last active January 2, 2016 14:08
Show Gist options
  • Save grabbeh/8314291 to your computer and use it in GitHub Desktop.
Save grabbeh/8314291 to your computer and use it in GitHub Desktop.
Inconsistency with manipulation of dummy data vs db data
// app.js
routes = require('./routes/routes.js')
app.get('/dummydata', routes.test);
app.get('/transformeddummydata', routes.testTwo);
app.get('/dbdata', routes.testThree);
app.get('/transformeddbdata', routes.testFour);
// Routes file
exports.test = function(req, res){
returnData(function(err, data){
res.json(data)
})
}
exports.testTwo = function(req, res){
returnData(function(err, data){
calculatePhotoRanking(data, function(data){
calculateCountryRankings(data, function(data){
res.json(data)
})
})
})
}
exports.testThree = function(req, res){
Photo.find({ country:'RUS', tag: 'cat', isVoted: true}, function(err, data){
res.json(data)
})
}
exports.testFour = function(req, res){
Photo.find({ country:'RUS', tag: 'cat', isVoted: true}, function(err, data){
calculatePhotoRanking(data, function(data){
calculateCountryRankings(data, function(data){
// returned object does not display ranking or countryRanking
console.log(data[0])
// however this does return the calculated countryRanking
console.log(data[0].countryRanking)
res.json(data)
})
})
});
};
// Used functions
function calculatePhotoRanking(photos, fn){
return fn(_.map(photos, function(photo){
photo.ranking = ((photo.votes / photo.appearances) * 100).toFixed(0);
return photo;
}));
}
function calculateCountryRankings(photos, cb){
return cb(_.flatten(_.map(countrySorter(photos), averager('ranking'))));
}
function createArraySorter(key) {
return function (arr) {
var holder = [];
_.each(_.uniq(_.pluck(arr, key)), function (e) {
holder.push(_.where(arr, equalToGiven(key, e)));
});
return holder;
};
}
var countrySorter = createArraySorter('country');
function equalToGiven(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
function averager(key) {
return function (arr) {
_.each(arr, function (e) {
e.countryAverage = _.reduce(_.pluck(arr, key), function (a, b) {
return a + b / arr.length;
}, 0);
});
return arr;
};
}
function returnData(cb){
var data = [{
__v: 0,
_id: "5285cbd164ac14f121000012",
appearances: 1,
country: "RUS",
farm: 5,
id: "4297172189",
isVoted: true,
notTag: false,
secret: "925e90a4d9",
server: "4058",
tag: "cat",
votes: 1,
dateCreated: "2013-11-15T07:22:57.215Z",
location: [
53.1666667,
48.4666667
]
},
{
__v: 0,
_id: "5285cd7364ac14f12100006a",
appearances: 5,
country: "RUS",
farm: 3,
id: "5732677537",
isVoted: true,
notTag: false,
secret: "762e059973",
server: "2714",
tag: "cat",
votes: 2,
dateCreated: "2013-11-15T07:29:55.762Z",
location: [
56.1333333,
47.2333333
]
}]
return cb(null, data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment