Last active
August 25, 2016 15:39
-
-
Save sairion/34bf3e6353c2faac68273d506affea09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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