Skip to content

Commit

Permalink
implement HashMap.update
Browse files Browse the repository at this point in the history
  • Loading branch information
thk2b committed Apr 16, 2018
1 parent b223ac0 commit ecb97aa
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/HashMap/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ Adds all values from the data to the hashMap. Each key:value pair in the object

Removes the key and value from the hashMap.

### `update(key, updateFn)`

Updates the key with the return value of `updateFn(state[key])`.

`updateFn` recieves the current value at `key` or null if undefined.

## Example

```js
Expand Down
12 changes: 12 additions & 0 deletions src/HashMap/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ export default function HashMap (name, initialState = {}){
type: createActionType('delete'),
key
})
},
update(key, updateFn){
return ({
type: createActionType('update'),
key, updateFn
})
}
}

Expand All @@ -47,6 +53,12 @@ export default function HashMap (name, initialState = {}){
? { ...nextState, [key]: state[key] }
: nextState
, {})
} else if(action.type.endsWith('update')){
const { key, updateFn } = action
return {
...state,
[key]: updateFn(state[key] || null)
}
} else return state
}

Expand Down
15 changes: 14 additions & 1 deletion src/HashMap/test/hashmap.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,20 @@ test('HashMap', main => {
const state0 = reducer({ 1: 'a', 2: 'b' }, actions.delete(1))
t.deepEqual(state0, { 2: 'b' }, 'should have deleted the element at key')
const state1 = reducer(state0, actions.delete(1))
t.deepEqual(state0, { 2: 'b' }, 'should have done nothing when the key does not exist')
t.deepEqual(state1, { 2: 'b' }, 'should have done nothing when the key does not exist')
t.end()
})
main.test('`update` action', t => {
const { actions, reducer } = HashMap('test-name-5')
const state0 = reducer({ 1: 'a', 2: 'b' }, actions.update(1, value => {
t.equal(value, 'a', 'should be given the current value')
return 'z'
}))
t.deepEqual(state0, { 1: 'z', 2: 'b' }, 'should have updated the element at key with the return value')
const state1 = reducer(state0, actions.update(3, value => {
t.equal(value, null, 'value should be null when it does not exist')
}))
t.deepEqual(state1, {...state0, 3: undefined}, 'should have set to undefined')
t.end()
})
main.test('multiple instances', t => {
Expand Down

0 comments on commit ecb97aa

Please sign in to comment.