Can a function returning a new object be considered "clean"?

Given the definition:

A pure function is a function that gives the same input, will always return the same result, and will not cause side effects.

Can a function be considered AmIPure

as a pure function? By definition, no, but I want to be 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

      

+3


source to share


2 answers


It depends on the definition of "same".

If you expect strict equality of objects, then only functions that return scalars (eg numbers, booleans, ...) can be considered "pure".



In general, this is not what you really mean: usually you are not interested if you get the same instance of an object only if it is equal to another according to some definition, for example:

  • if they are strings with the same characters ( "HELLO"

    and "HELLO"

    )
  • if they are simple objects with the same name and attribute values ​​( {x:0,y:1}

    and {y:1,x:0}

    )
  • if they are arrays with the same elements in the same order ( [1,2,3]

    and [1,2,3]

    )
  • ...
+3


source


Here, the result returned by the function is object

. If you compare objects it will not be true. Instead, you can compare values

var foo = AmIPure(5, "SEK");
var baz = AmIPure(5, "SEK");
console.log(foo.value === baz.value && foo.currency === baz.currency ); 

      



This should be true.

0


source







All Articles