Skip to content

Commit

Permalink
Merge pull request #2 from arunoda/add-update
Browse files Browse the repository at this point in the history
Add an update API to update the multiple entries in the store
  • Loading branch information
arunoda authored Nov 12, 2016
2 parents 9fc3820 + 875d1eb commit 43e7b5e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,19 @@ Get a value by the give key.
store.get('key');
```

### update

Update multiple entries of the store at once. While updating, you could accept the current state of the store as well.

```js
store.update(function(state) {
return {
newField: 10,
existingField: !Boolean(existingField)
};
});
```

### getAll

Get all the key values pairs in the store as a map.
Expand Down
12 changes: 12 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ export default class Podda {
this.fire(key, value);
}

update(fn) {
const currentState = this.data.toJS();
const newFields = fn(currentState);
if (newFields === null || newFields === undefined) {
throw new Error('You must provide an object with updated values for Podda.set(fn)');
}

Object.keys(newFields).forEach((key) => {
this.set(key, newFields[key]);
});
}

get(key) {
const value = this.data.get(key);
if (value === null || value === undefined) {
Expand Down
35 changes: 35 additions & 0 deletions src/tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,41 @@ describe('Podda', () => {
expect(store.get('abc')).to.be.equal('ppc');
});

it('should support to update with a function', () => {
const store = new Podda({
abc: 10,
bbc: 20,
});

store.update((state) => {
expect(state).to.deep.equal({ abc: 10, bbc: 20 });
// this is not going to add to the store.
state.someItem = 1000; // eslint-disable-line

return { bbc: 50, cnn: 100 };
});

expect(store.getAll()).to.deep.equal({
abc: 10,
bbc: 50,
cnn: 100,
});
});

it('should throw an error if update function returns nothing', () => {
const store = new Podda();
const run1 = () => {
store.update(() => null);
};

const run2 = () => {
store.update(() => {});
};

expect(run1).to.throw(/an object with updated values/);
expect(run2).to.throw(/an object with updated values/);
});

it('should support getting all the values', () => {
const store = new Podda();
store.set('abc', 'kkr');
Expand Down

0 comments on commit 43e7b5e

Please sign in to comment.