Created
November 22, 2014 08:49
-
-
Save alessioalex/55a234a75c5fc32b6971 to your computer and use it in GitHub Desktop.
0-cache-args.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// our own in memory database | |
var users = { | |
'alex': { user: 'alex', age: 27 }, | |
'john': { user: 'johndoe', age: 34 } | |
}; | |
// async function | |
var getUserFromDb = function getUserFromDb(id, callback) { | |
var min = 1000; | |
var max = 2000; | |
var randomTimeout = Math.floor(Math.random() * (max - min + 1)) + min; | |
setTimeout(function() { | |
callback(null, users[id] || null); | |
}, randomTimeout); | |
}; | |
var cachify = function cachify(originalFn, getFromCache) { | |
return function() { | |
var args = Array.prototype.slice.call(arguments); | |
// get callback and remove it from the `args` array | |
var originalCb = args.pop(); | |
var that = this; | |
// put a custom callback instead, so we know to call the original function | |
// on cache miss | |
args.push(function(err, result) { | |
if (err) { return originalCb(err); } | |
if (typeof result === 'undefined' || result === null) { | |
// cache miss | |
// put the original callback where it belongs, as the last argument | |
args[args.length - 1] = originalCb; | |
// args.push(originalCb); | |
originalFn.apply(that, args); | |
} else { | |
// cache hit | |
originalCb(null, result); | |
} | |
}); | |
getFromCache.apply(this, args); | |
}; | |
}; | |
var getResultFromCache = function getResultFromCache(id, cb) { | |
setTimeout(function() { | |
cb(null, users[id] || null); | |
}, 0); | |
}; | |
// Example: | |
// this takes between 1-2 seconds to get the result | |
console.time('database'); | |
getUserFromDb('alex', function(err, user) { | |
if (err) { throw err; } | |
console.log('directly hitting the database:', user); | |
console.timeEnd('database'); | |
}); | |
// this should be much faster | |
console.time('cache'); | |
var cachedAsyncFunction = cachify(getUserFromDb, getResultFromCache); | |
cachedAsyncFunction('alex', function(err, result) { | |
if (err) { throw err; } | |
console.log('from cache:', result); | |
console.timeEnd('cache'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment