I have this impure code that prints two equal messages
class P {
constructor() {
this.x = 0
this.y = []
}
}
const incrX = (p) => { p.x = p.x + 1 ; return p }
const incrY = (p,q) => ( p.y.push(q) ; return p }
const ps = [ new P() , new P() ]
const result = ps.map( (_,i) => i === 0 ? incrY(ps[i],ps[i+1]) : incrX(ps[i]) )
console.log( result[0].y[0] )
console.log( result[1] )
But using pure functions, the prints are not equal, because ps[0].y[0] keeps an old reference
class P {
constructor() {
this.x = 0
this.y = []
}
}
const incrX = (p) => ({ ...p , x : p.x + 1 })
const incrY = (p,q) => ({ ...p , y: [ ...p.y , q ] })
const ps = [ new P() , new P() ]
const result = ps.map( (_,i) => i === 0 ? incrY(ps[i],ps[i+1]) : incrX(ps[i]) )
console.log( result[0].y[0] )
console.log( result[1] )
Is there an way to keep references using something similar to the pure version ? Maybe using an array that stores references to references, is this even possible in javascript ?