From 4a9481e2f160001822c808c1c667d29aeb1700c0 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 17 Sep 2013 09:17:47 +0200 Subject: [PATCH] Added a basic solution based on level-sublevel. --- problems/queue/setup.js | 7 ++++++ problems/queue/solution.js | 45 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/problems/queue/setup.js b/problems/queue/setup.js index e69de29..ddeb2fa 100644 --- a/problems/queue/setup.js +++ b/problems/queue/setup.js @@ -0,0 +1,7 @@ + +function setup(run, callback) { + console.log(arguments) +} + +module.exports = setup +module.exports.async = true diff --git a/problems/queue/solution.js b/problems/queue/solution.js index e69de29..b85741e 100644 --- a/problems/queue/solution.js +++ b/problems/queue/solution.js @@ -0,0 +1,45 @@ +var sublevel = require('level-sublevel') + +function Queue(db, name) { + if (!(this instanceof Queue)) return new Queue(db, name) + + this._db = sublevel(db).sublevel(name) +} + +module.exports = Queue + +Queue.prototype.push = function(element, callback) { + var key = (new Date()).toISOString() + + this._db.put(key, element, callback) + + return this; +} + +Queue.prototype.shift = function(callback) { + var stream = this._db.createReadStream({ + limit: 1 + }) + + , db = this._db + + stream.once('data', function(data) { + db.del(data.key, function(err) { + callback(err, data.value) + }) + }) + + stream.once('error', callback) + + return this; +} + +Queue.prototype.clear = function(callback) { + this._db.createReadStream() + .pipe(this._db.createWriteStream({ + type: 'del' + })) + .on('close', callback) + + return this; +}