Created
November 22, 2014 08:43
-
-
Save alessioalex/e14cf75d7e2badeb9892 to your computer and use it in GitHub Desktop.
0-cache-second-try.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(id, callback) { | |
// here we will first try to grab the result from the cache | |
// in case it doesn't exist -> call the original function | |
getFromCache(id, function(err, result) { | |
// handle error -> if (err) .. | |
if (result !== null && typeof result !== 'undefined') { | |
callback(null, result); | |
} else { | |
originalFn(id, callback); | |
} | |
}); | |
}; | |
}; | |
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