Skip to content

Commit

Permalink
Fix setIn
Browse files Browse the repository at this point in the history
  • Loading branch information
zaaack committed Dec 26, 2017
1 parent 82597de commit 9cd6464
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
30 changes: 23 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function lambda2path(accessor: Function) {
return keys
}
let m = setter.match(funRe)
if (!m) {
if (!m || setter.indexOf('(') >= 0) {
throw new Error('Invalid setter:' + setter)
}
let pathStr = m[1]
Expand Down Expand Up @@ -72,14 +72,30 @@ function mutate<T, V>(record: T, accessor: ((obj: T) => V) | string[], type: Mut
: updator
return newRecord
}

/**
* Set a deep child
* @param record The object to update, it can be a plain object or a class instance
* @param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
* @param value The new value to set, if it is ignored it will be set to undefined.
*/
export function setIn<T, V>(record: T, accessor: ((obj: T) => V) | string[], value?: V): T {
if (value === void 0) {
return record
}
return mutate(record, accessor, MutateType.setIn, value)
return mutate(record, accessor, MutateType.setIn, value as V)
}

/**
* Unset a deep child
*
* @param record The object to update, it can be a plain object or a class instance
* @param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
*/
export function unsetIn<T, V>(record: T, accessor: ((obj: T) => V | undefined) | string[]): T {
return mutate(record, accessor, MutateType.setIn, void 0)
}
/**
* Update a deep child by old value
* @param record The object to update, it can be a plain object or a class instance
* @param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
* @param updator A update function that take the old value and return the new value.
*/
export function updateIn<T, V>(record: T, accessor: ((obj: T) => V) | string[], updator?: (v: V) => V): T {
if (!updator) {
return record
Expand Down
1 change: 0 additions & 1 deletion src/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,5 @@ describe('updateIn', () => {
})
})


let newBook = mutator.setIn(book, _ => _.title.en, 'nnn')
newBook = mutator.updateIn(book, _ => _.tags, t => [...t, 'novel'])

0 comments on commit 9cd6464

Please sign in to comment.