Created immutability function `insertAt`
This commit is contained in:
parent
2a1fabc6ac
commit
54788aa593
|
@ -3,7 +3,7 @@
|
|||
* All functions are pure and don't mutate the JSONData.
|
||||
*/
|
||||
|
||||
import { setIn, updateIn, getIn, deleteIn } from './utils/immutabilityHelpers'
|
||||
import { setIn, updateIn, getIn, deleteIn, insertAt } from './utils/immutabilityHelpers'
|
||||
import { isObject } from './utils/typeUtils'
|
||||
import isEqual from 'lodash/isEqual'
|
||||
|
||||
|
@ -336,18 +336,10 @@ export function add (data, path, value, options) {
|
|||
|
||||
let updatedData
|
||||
if (parent.type === 'Array') {
|
||||
// TODO: create an immutable helper function to insert an item in an Array
|
||||
updatedData = updateIn(data, dataPath.concat('items'), (items) => {
|
||||
const index = parseInt(prop)
|
||||
const updatedItems = items.slice(0)
|
||||
|
||||
updatedItems.splice(index, 0, value)
|
||||
|
||||
return updatedItems
|
||||
})
|
||||
updatedData = insertAt(data, dataPath.concat('items', prop), value)
|
||||
}
|
||||
else { // parent.type === 'Object'
|
||||
// TODO: create an immutable helper function to append an item to an Array
|
||||
// TODO: create an immutable helper function to update a property in an Object
|
||||
updatedData = updateIn(data, dataPath.concat('props'), (props) => {
|
||||
const newProp = { name: prop, value }
|
||||
|
||||
|
|
|
@ -150,3 +150,27 @@ export function deleteIn (object, path) {
|
|||
return updatedObject
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a new item in an array
|
||||
* @param {Array} array
|
||||
* @param {Path} path
|
||||
* @param {*} value
|
||||
* @return {Array}
|
||||
*/
|
||||
export function insertAt (array, path, value) {
|
||||
const parentPath = path.slice(0, path.length - 1)
|
||||
const index = path[path.length - 1]
|
||||
|
||||
return updateIn(array, parentPath, (items) => {
|
||||
if (!Array.isArray(items)) {
|
||||
throw new TypeError('Array expected at path ' + JSON.stringify(parentPath))
|
||||
}
|
||||
|
||||
const updatedItems = items.slice(0)
|
||||
|
||||
updatedItems.splice(index, 0, value)
|
||||
|
||||
return updatedItems
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import test from 'ava';
|
||||
import { getIn, setIn, updateIn, deleteIn } from '../src/utils/immutabilityHelpers'
|
||||
import { getIn, setIn, updateIn, deleteIn, insertAt } from '../src/utils/immutabilityHelpers'
|
||||
|
||||
|
||||
test('getIn', t => {
|
||||
|
@ -269,3 +269,10 @@ test('deleteIn non existing path', t => {
|
|||
const updated = deleteIn(obj, ['a', 'b'])
|
||||
t.truthy (updated === obj)
|
||||
})
|
||||
|
||||
test('insertAt', t => {
|
||||
const obj = { a: [1,2,3]}
|
||||
|
||||
const updated = insertAt(obj, ['ab', '2'], 8)
|
||||
t.deepEqual(updated, {a: [1,2,8,3]})
|
||||
})
|
||||
|
|
Loading…
Reference in New Issue