Skip to content

Commit

Permalink
Add update(key, updater, cb)
Browse files Browse the repository at this point in the history
  • Loading branch information
Havvy committed Mar 15, 2016
1 parent 141f4ab commit d79d9fb
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -87,6 +87,13 @@ Retrieves the value for the given `key`.
Removes the record with the given `key`. This is identical to setting the `key`'s value
to `undefined`.

### dirty.update(key, updater, [cb])

Updates the record of the given `key` with the given `updater` which is a function
that is passed the current value of the key.

The optional `cb` callback is passed to `dirty.set`.

### dirty.forEach(fn)

Calls the given `fn` function for every document in the database. The passed
Expand Down
11 changes: 10 additions & 1 deletion lib/dirty/dirty.js
Expand Up @@ -36,7 +36,7 @@ module.exports = Dirty;
/**
* set() stores a JSON object in the database at key
* cb is fired when the data is persisted.
* In memory, this is immediate- on disk, it will take some time.
* In memory, this is immediate - on disk, it will take some time.
*/
Dirty.prototype.set = function(key, val, cb) {
if (val === undefined) {
Expand Down Expand Up @@ -95,6 +95,15 @@ Dirty.prototype.forEach = function(fn) {

};

/**
* Update the value stored at a key in the database.
* This is synchronous since a cache is maintained in-memory
* cb is passed as per Dirty.prototype.set
*/
Dirty.prototype.update = function(key, updater, cb) {
this.set(key, updater(this.get(key)), cb);
};

/**
* Close dirty db file stream, release file handle
*/
Expand Down
12 changes: 12 additions & 0 deletions test/test-system.js
Expand Up @@ -116,3 +116,15 @@ describe('test-chaining-of-constructor', function() {
});
});
});

describe('test-update', function () {
it('should give the updater the value and then set the value to what updater returns', function() {
var db = dirty();
db.set("foo", "bar");
db.update("foo", function (bar) {
assert.strictEqual(bar, "bar");
return "baz";
});
assert.strictEqual(db.get("foo"), "baz");
});
});

0 comments on commit d79d9fb

Please sign in to comment.