Here is an example. I have class WalmartCart
and I can't change it.
class WalmartCart {
static cart = []
putItem(item){
WalmartCart.cart.push(item)
}
}
And I need to have a function func
which accepts the class as input and returns the array with modified items in static cart
in WalmartCart
.
const func = (WalmartCart) => {}
So, the result should look like this
let result = func(WalmartCart) // !!
let wal = new WalmartCart()
wal.putItem( {'1': 1} )
wal.putItem( {'2': 2} )
wal.putItem( {'3': '3'} )
console.log(result)
// result = [
// {'1': 1, 'some new data': 'new data'},
// {'2': 2, 'some new data': 'new data'},
// {'3': '3', 'some new data': 'new data'}
// ]
The whole catch is that the function func
can be called only once before putting the items in the static cart
.
So, how can I do that?
CodePudding user response:
Just const func = (T) => T.cart
live demo:
const func = (T) => T.cart
class WalmartCart {
static cart = []
putItem(item){
WalmartCart.cart.push(item)
}
}
let result = func(WalmartCart)
let wal = new WalmartCart()
wal.putItem( {'1': 1} )
wal.putItem( {'2': 2} )
wal.putItem( {'3': '3'} )
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0 }
CodePudding user response:
You can return WalmartCart.cart
directly in func
Like many other programming languages, Javascript also has call-by-sharing which is using a reference as a medium to the actual values.
class WalmartCart {
static cart = [] //reference value
putItem(item){
WalmartCart.cart.push(item)
}
}
const func = (WalmartCart) => {
return WalmartCart.cart
}
let result = func(WalmartCart) //now `result` and `WalmartCart.cart` have the same reference value
console.log(`Is result and WalmartCart.cart is the same reference value: ${result === WalmartCart.cart}`)
let wal = new WalmartCart()
//`WalmartCart.cart` modification means `result` modification as well
wal.putItem( {'1': 1} )
wal.putItem( {'2': 2} )
wal.putItem( {'3': '3'} )
console.log(result)