Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function which returns a new object be considered "pure"?

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
like image 719
Marcin Kowal Avatar asked Sep 13 '25 12:09

Marcin Kowal


1 Answers

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.:

  • if they are strings with equal characters ("HELLO" and "HELLO")
  • if they are simple object with equal attribute names and values ({x:0,y:1} and {y:1,x:0})
  • if they are arrays with equal elements in the same order ([1,2,3] and [1,2,3])
  • ...
like image 180
Damiano Avatar answered Sep 16 '25 05:09

Damiano