Reputation: 73
Given the definition:
A pure function is a function which given the same input, will always return the same output and produces no side effects.
Can we consider function AmIPure
as pure function? According to definition no, but I want to make sure.
function Amount(value, currency) {
this.value = value;
this.currency = currency;
}
function AmIPure(value, currency) {
return new Amount(value, currency);
}
var foo = AmIPure(5, "SEK");
var baz = AmIPure(5, "SEK");
console.log(foo === baz); //false
Upvotes: 4
Views: 577
Reputation: 811
It depends on the definition of "same".
If you expect strict object equality, then only functions returning scalars (e.g. numbers, booleans, ...) could ever be considered "pure".
In general, though, that's not what you really mean: you don't usually care if you get the exact same instance of an object, only if it is equal to another according to some definition, e.g.:
"HELLO"
and "HELLO"
){x:0,y:1}
and {y:1,x:0}
)[1,2,3]
and [1,2,3]
)Upvotes: 5
Reputation: 3782
Here the result you are returning from the function is an object
. If you compare the objects it won't give true. Instead you can compare the values
var foo = AmIPure(5, "SEK");
var baz = AmIPure(5, "SEK");
console.log(foo.value === baz.value && foo.currency === baz.currency );
This should give true.
Upvotes: -1