Last active
May 16, 2017 07:51
-
-
Save dennissterzenbach/d0968b62142ac8e4ce69dc5c9e3633ce to your computer and use it in GitHub Desktop.
A list of helpers for handling copying, clearing arrays quickly and easily.
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
/* Array.isArray polyfill - taken from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray */ | |
if (!Array.isArray) { | |
Array.isArray = function (arg) { | |
return Object.prototype.toString.call(arg) === '[object Array]' | |
} | |
} | |
function ArrayHelpers() { | |
} | |
/** | |
* copies all entries from array given as the second argument into the array | |
* given as first argument. | |
* | |
* Please Note: This will keep all the entries already existing! | |
* If you do not wish this behavior, use "fastFillArray" | |
* | |
* @param {Array} arrayToFill the array to copy entries into | |
* @param {Array} arrayWithEntriesToFillIn the array to copy over | |
*/ | |
ArrayHelpers.copyBetweenArrays = function copyBetweenArrays(arrayToFill, arrayWithEntriesToFillIn) { | |
if (ArrayHelpers.isArrayLike(arrayToFill) && ArrayHelpers.isArrayLike(arrayWithEntriesToFillIn)) { | |
Array.prototype.push.apply(arrayToFill, arrayWithEntriesToFillIn); | |
} | |
return arrayToFill; | |
}; | |
ArrayHelpers.isArrayLike = function isArrayLike(subject) { | |
return !!(subject && (Array.isArray(subject)) && ('push' in subject)); | |
}; | |
/** | |
* clears the first argument's array and fills all entries from array given as | |
* the second argument. | |
* | |
* Please Note: This will remove all entries from the first argument array! | |
* | |
* @param {Array} arrayToFill the array to clear and fill into | |
* @param {Array} arrayWithEntriesToFillIn the array to copy over | |
*/ | |
ArrayHelpers.fastFillArray = function fastFillArray(arrayToFill, arrayWithEntriesToFillIn) { | |
if (ArrayHelpers.isArrayLike(arrayToFill) && ArrayHelpers.isArrayLike(arrayWithEntriesToFillIn)) { | |
arrayToFill.length = 0; | |
ArrayHelpers.copyBetweenArrays(arrayToFill, arrayWithEntriesToFillIn); | |
} | |
return arrayToFill; | |
} | |
/** | |
* clears the first argument's array. This will remove all entries from it. | |
* | |
* @param {Array} array the array to clear | |
*/ | |
ArrayHelpers.clearArray = function clearArray(array) { | |
if (ArrayHelpers.isArrayLike(array)) { | |
array.length = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment