Last active
February 6, 2020 02:28
-
-
Save aleph-naught2tog/27b9991697e227b42a0e4aa83812b382 to your computer and use it in GitHub Desktop.
A buggy impl of Array.prototype.filterSpliceSort
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
Array.prototype.filterSpliceSort = function(callbackFn) { | |
const returnArray = []; | |
for (let index = 0; index < this.length; index += 1) { | |
const value = this[index]; | |
const result = callbackFn(value, index, this); | |
// -- Return true to keep the element | |
if (true === result) { | |
// nothing to see here, move along | |
continue; | |
} | |
// -- Return false to remove it and put the element in the return array | |
if (false === result) { | |
// splice mutates in place, so we have now removed it | |
const [splicedOutValue] = this.splice(index, 1); | |
returnArray.push(splicedOutValue); | |
index -= 1; | |
continue; | |
} | |
// -- Return undefined to just remove it | |
if (undefined === result) { | |
this.splice(index, 1); | |
index -= 1; | |
continue; | |
} | |
// -- Any other return value puts the element into its sorted position | |
// sounds like time for a super great nested loop | |
const copy = [...returnArray].concat(value); | |
// mmmm, mutates in place deliciousness | |
copy.sort(); | |
const newIndex = copy.findIndex(maybeValue => maybeValue === value); | |
// remove it... | |
returnArray.splice(newIndex, 0, value); | |
}; | |
return returnArray; | |
}; | |
const testData = [ | |
1, | |
2, | |
'quack', | |
3, | |
null, | |
4, | |
5, | |
{}, | |
{ message: 'hello' }, | |
'ducks' | |
]; | |
const splitOutOddNumbersAndRemoveObjectsEntirely = value => { | |
if (typeof value === 'object') { | |
return; | |
} | |
if (value % 2 === 0) { | |
return true; | |
} | |
if (value % 2 === 1) { | |
return false; | |
} | |
return value; | |
}; | |
console.log('testData before:', testData); | |
const output = testData.filterSpliceSort(splitOutOddNumbersAndRemoveObjectsEntirely); | |
console.log('testData after:', testData); | |
console.log('return value:', output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment