Skip to content

Instantly share code, notes, and snippets.

@vandy
Created February 4, 2020 21:39
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 vandy/571e3d2ed085e4783bcc69ca140c7492 to your computer and use it in GitHub Desktop.
Save vandy/571e3d2ed085e4783bcc69ca140c7492 to your computer and use it in GitHub Desktop.
/**
* 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