Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@artisanalcode
Created April 28, 2016 16:35
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 artisanalcode/8db760edc483762e91ad04517699025a to your computer and use it in GitHub Desktop.
Save artisanalcode/8db760edc483762e91ad04517699025a to your computer and use it in GitHub Desktop.
A "class"(object) with a method that takes an array and an integer as arguments and returns a new array composed of the bigger number of each of a series of windows on the array defined by the 'n' parameter.E.g. arrayExtender.winMax([1,4,3,1,5], 2); returns [4, 4, 3, 5], an array composed of the bigger number of each of the 2 element size …
// Creates a "class"(object) with 'helper' array methods
var arrayExtender = {
// Creates a method that takes an array and an integer as arguments and returns
// a new array composed of the bigger number of each of a series of windows on the
// array defined by the 'n' parameter
// E.g. arrayExtender.winMax([1,4,3,1,5], 2); returns [4, 4, 3, 5], an array composed of
// the bigger number of each of the 2 element size ('n') 'windows': [1,4],[4,3],[3,1],[1,5]
winMax : function (array, n) {
// Check if parameter passed in 'array' is an array
if (Object.prototype.toString.call(array) === '[object Array]') {
// If no n is passed, return original array, alternatively request 'n'
if (!n) {
return array;
}
var newArray = [];
// Loop thru array, as far a there are enough elements to create a 'window'
for (var i = 0; i < (array.length - n + 1) ; i++) {
// The current method uses slice, but the same result can be achieved with other methods
var max = Math.max.apply(null, array.slice(i, n + i));
// Same result using a for loop, no Math.max, no slice (probably less overhead);
//var max = 0;
//for (var x = i; x < (i + n); x ++) {
// if ( array[x] > max ) {
// max = array[x];
// };
//}
// The result of Math.max (or alternate method) is pushed to the newArray that will be returned
newArray.push(max);
}
// Return the new array
return newArray;
}
// If no array is passed return error message
else {
alert ("Not an array");
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment