Created
September 11, 2014 17:05
-
-
Save meandmax/13f8130d9830de45d559 to your computer and use it in GitHub Desktop.
Try to find a generic way of incrementing a value without new assignments
This file contains hidden or 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 doesn`t work, as val is a completly different value then count with own scope | |
var count = 0; | |
var increment = function(val){ | |
val += 1; | |
} | |
increment(count); | |
console.log(count); | |
// doesn`t work because first assignment then incrementation | |
var value = 0; | |
var increment = function(otherValue){ | |
value = otherValue++; | |
}; | |
increment(value); | |
console.log(value); | |
// works but now I increment just value and if I pass something else to the function it is broke | |
var value = 0; | |
var increment = function(otherValue){ | |
value = ++otherValue; | |
}; | |
increment(value); | |
console.log(value); | |
// Best suited for the generic case, works fine for me, and I can pass what ever I want | |
var obj = {value: 0}; | |
var increment = function(obj){ | |
obj.value++; | |
}; | |
increment(obj); | |
console.log(obj.value); | |
// Optimisation of the example above, without increment operator | |
var obj = {value: 0}; | |
var increment = function(obj){ | |
obj.value += 1; | |
}; | |
increment(obj); | |
console.log(obj.value); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment