Skip to content

Instantly share code, notes, and snippets.

@willread
Created August 2, 2012 21:34
Show Gist options
  • Save willread/3240861 to your computer and use it in GitHub Desktop.
Save willread/3240861 to your computer and use it in GitHub Desktop.
Array iteration problem
/*
Solution to the Array Iteration Problem @ http://blog.jazzychad.net/2012/08/01/array-iteration-problem.html
---
add1 - increments items in an array matching specified value
param: arr - array of integers to manipulate
param: val - integer, value to increment
param: n - integer, control value specifying behavior of manipulation
n == 0 means increment all occurrences of val
n > 0 means increment up to n occurrences of val
from left-to-right (forward)
n < 0 means increment up to n occurrences of val
from right-to-left (backward)
return: arr with proper values incremented
*/
var add1 = function(arr, val, n){
for(var ii = n >= 0 ? 0 : arr.length - 1, jj = n >= 0 ? arr.length : 0, count = 0; ii != jj && (count < Math.abs(n) || n == 0); ii += n >= 0 ? 1 : -1){
if(arr[ii] == val){
arr[ii]++;
count++;
}
}
return arr;
}
var arr = [1, 4, 1, 5, 1];
add1(arr, 1, 2);
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment