Created
November 12, 2017 18:34
-
-
Save timvisee/e32058718fa6c5c7ea2d7d25a69cdf14 to your computer and use it in GitHub Desktop.
Super fast isEven in JavaScript - Reddit meme
This file contains hidden or 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
| var redis = require('redis'); | |
| var redisClient = redis.createClient(); | |
| /** | |
| * Super fast cached magic for determining evenness of a number. | |
| * | |
| * @param {number} x Number to check (integer). | |
| * @param {function} callback Called with the result, or when our magic failed. | |
| */ | |
| function isEven(x, callback) { | |
| if(x == 0) { | |
| callback(null, true); | |
| return; | |
| } | |
| if(x < 0) | |
| x *= -1; | |
| redisClient.get('isEven:' + x, function(err, result) { | |
| if(err || result != null) { | |
| callback(err, result); | |
| return; | |
| } | |
| isEven(x - 1, function(err, odd) { | |
| if(err) { | |
| callback(err); | |
| return; | |
| } | |
| redisClient.set('isEven:' + x, !odd); | |
| callback(null, !odd); | |
| }); | |
| }); | |
| } | |
| module.exports = isEven; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment