dot-prop-immutable icon indicating copy to clipboard operation
dot-prop-immutable copied to clipboard

Add .push for pushing to arrays (and .slice, splice etc?)

Open ebdrup opened this issue 10 years ago • 8 comments

ebdrup avatar Nov 27 '15 12:11 ebdrup

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.

laere avatar Apr 21 '16 17:04 laere

I think that idea was to expose an immutable push, e.g.

const obj = { names: ['Alice'] }

dotProp.push(obj, 'names', 'Bob')
// => { names: ['Alice', 'Bob'] }

LinusU avatar Jan 21 '17 16:01 LinusU

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.

ajoslin avatar Feb 05 '17 17:02 ajoslin

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 avatar Feb 06 '17 08:02 LinusU

@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

ajoslin avatar Feb 06 '17 15:02 ajoslin

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)

LinusU avatar Feb 06 '17 16:02 LinusU

Aha, of course. I see what you mean.

ajoslin avatar Feb 06 '17 23:02 ajoslin

Unshift would be welcome too

wellguimaraes avatar Sep 14 '17 22:09 wellguimaraes