Skip to content

Instantly share code, notes, and snippets.

@sairion
Last active August 25, 2016 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sairion/34bf3e6353c2faac68273d506affea09 to your computer and use it in GitHub Desktop.
Save sairion/34bf3e6353c2faac68273d506affea09 to your computer and use it in GitHub Desktop.
// This function can be impure in JS context...
function sum(arr) {
var z = 0;
for (var i=0;i<arr.length;i++) {
z += arr[i];
}
return z;
}
// sec 1: valueOf() impureness
let internalVal = 100;
function getRttwVal() {
return {
valueOf: function() { return internalVal += 100; }
};
}
const foo = [getRttwVal(), getRttwVal(), getRttwVal()]
console.debug(sum(foo)); // 900
console.debug(sum(foo)); // 1800
console.debug(sum(foo)); // 2700
// sec 2: getter impureness (wara)
let internalVal2 = 0;
function getRttwVal2() {
return {
get '0'() {
return internalVal2 += 1;
},
get '1'() {
return internalVal2 += 3;
},
get '2'() {
return internalVal2 += 7;
},
length: 3
};
}
const foo2 = getRttwVal2();
console.debug(sum(foo2)) // 16
console.debug(sum(foo2)) // 49
console.debug(sum(foo2)) // 82
// Also note ES2015 Proxy can be used to do similar effect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment