How can I count number of steps between different numbers.
I have a method that takes a number and runs a code snippet with the number. I need to see if the number is the number right next to the other or two steps, three steps, four steps over or below etc.
Ex. I send a number of 1 to the method. The next number sent is 4. I then need to find out how many steps over one it is etc in this case 3 steps over 1 should be the result.
Any clues?
How can I count number of steps between different numbers.
I have a method that takes a number and runs a code snippet with the number. I need to see if the number is the number right next to the other or two steps, three steps, four steps over or below etc.
Ex. I send a number of 1 to the method. The next number sent is 4. I then need to find out how many steps over one it is etc in this case 3 steps over 1 should be the result.
Any clues?
Share Improve this question edited Jun 20, 2011 at 14:50 MacMac 35.4k55 gold badges153 silver badges224 bronze badges asked Jun 20, 2011 at 13:10 TobiasTobias 4943 gold badges14 silver badges31 bronze badges 1-
4
I think
4 - 1
is what you're after. – pimvdb Commented Jun 20, 2011 at 13:13
4 Answers
Reset to default 7You can use a function with a closure:
var value = (function() {
var previousValue = null;
return function(id) {
if (previousValue !== null) {
if(previousValue >= id) {
alert("Difference: -" + (previousValue - id));
}
else alert("Difference: +" + (id - previousValue));
}
previousValue = id;
};
})();
See an example fiddle here.
A simple subtraction!
var stepx = 1
var stepy = 4
var diff = stepy - stepx
alert (diff)
added fix for negative steps
var previousNumber = 0;
function countSteps(number) {
var result = (number - previousNumber);
previousNumber = number;
return (result<0) ? result*-1 : result;
}
Sorry got interrupted
<html>
<head>
<script>
var cnt="";
function countAndSave(num) {
var text = (cnt==="")?num:num+":"+Math.abs(num-cnt)+"/"+cnt
cnt=num;
return text
}
window.onload=function() {
document.getElementById("output").innerHTML +="<br />"+countAndSave(1);
document.getElementById("output").innerHTML +="<br />"+countAndSave(3);
document.getElementById("output").innerHTML +="<br />"+countAndSave(4);
document.getElementById("output").innerHTML +="<br />"+countAndSave(1);
document.getElementById("output").innerHTML +="<br />"+countAndSave(2);
document.getElementById("output").innerHTML +="<br />"+countAndSave(3);
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>