Add .push for pushing to arrays (and .slice, splice etc?)
Don't think you need pushing or slice/splicing for this library at all. It's pretty easy to use, and using push within a reducer is mutating state iirc.
I think that idea was to expose an immutable push, e.g.
const obj = { names: ['Alice'] }
dotProp.push(obj, 'names', 'Bob')
// => { names: ['Alice', 'Bob'] }
FYI you can do this in two lines:
function push (object, path, value) {
const array = dotProp.get(object, path)
return dotProp.set(object, path, array.concat(value))
}
Push would be convenient, though.
Just a small nit, your function will concatenate the value if it is an array, so you can't use it to push arrays to arrays...
could be solved like this:
function push (object, path, value) {
const array = dotProp.get(object, path)
return dotProp.set(object, path, [...array, value])
}
@LinusU actually, Array.concat handles arrays and single values perfectly.
> [1,2,3].concat([4,5],6)
[ 1, 2, 3, 4, 5, 6 ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
What I meant is that push and concat doesn't do the same thing:
let a = []
a.push([1, 2])
a.push([3, 4])
console.log(a)
// => [[1, 2], [3, 4]]
let a = []
a = a.concat([1, 2])
a = a.concat([3, 4])
console.log(a)
// => [1, 2, 3, 4]
If the function is named push, it should behave like the builtin push (but being immutable instead)
Aha, of course. I see what you mean.
Unshift would be welcome too