Last active
September 17, 2020 22:03
-
-
Save rauschma/6f3d7f177e3787f9bc2ee90131153809 to your computer and use it in GitHub Desktop.
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
function partition(inputArray, callback) { | |
const result = {}; | |
for (const [indexOfValue, value] of inputArray.entries()) { | |
const propertyKey = callback(value, indexOfValue); | |
if (propertyKey === null || propertyKey === '') { | |
continue; | |
} | |
if (!{}.hasOwnProperty.call(result, propertyKey)) { | |
result[propertyKey] = []; | |
} | |
result[propertyKey].push(value); | |
} | |
return result; | |
} | |
const arr = [1, -5, 4, 5, -2] | |
const {negative, nonNegative} = partition(arr, | |
elem => elem < 0 ? 'negative' : 'nonNegative'); | |
console.log(negative); | |
// [ -5, -2 ] | |
console.log(nonNegative); | |
// [ 1, 4, 5 ] | |
const input = [ | |
{name: 'John', isLocal: true}, | |
{name: 'Jane', isLocal: false}, | |
{name: 'Charlie', isLocal: true} | |
]; | |
const {local, global} = partition(input, | |
(elem) => elem.isLocal ? 'local' : 'global'); | |
console.log(local); | |
// [ { name: 'John', isLocal: true }, { name: 'Charlie', isLocal: true } ] | |
console.log(global); | |
// [ { name: 'Jane', isLocal: false } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think there is a specific reason for this. You could include it as well. At the same time you could also exclude
null
or''
from the check, resulting in an object that could have "null" or "''" as a key. It's a matter of taste I guess. Or maybe there is another reason that I cannot foresee at the moment.