Created
February 4, 2020 21:39
-
-
Save vandy/571e3d2ed085e4783bcc69ca140c7492 to your computer and use it in GitHub Desktop.
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
/** | |
* Moves to the end all "falsy" items within the array (this). | |
* | |
* Could be used for extending Array.prototype: | |
* Array.prototype.separate = separate; | |
* | |
* @param [test] {Function} - function to determine whether an item is falsy | |
* if not provided, "falsy" is Boolean(value) except zero. | |
* @returns {number} - first "falsy" item index | |
*/ | |
export function separate(test) { | |
test = typeof test === 'function' ? test : value => Boolean(value) || value === 0; | |
let i = 0; | |
let last = 0; | |
const {length} = this; | |
while (i < length) { | |
if (!test(this[i])) { | |
i++; | |
continue; | |
} | |
let j = i; | |
while (j > last) { | |
[this[j], this[j - 1]] = [this[j - 1], this[j]]; | |
j--; | |
} | |
i++; | |
last++; | |
} | |
return last; | |
} | |
/** | |
* Moves to the end all "falsy" items within the passed array. | |
* | |
* @param array | |
* @param [test] {Function} - function to determine whether an item is falsy | |
* if not provided, "falsy" is Boolean(value) except zero. | |
* @returns {number} - first "falsy" item index | |
*/ | |
export function separate_array(array, test) { | |
return separate.call(array, test); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment