Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active September 17, 2020 22:03
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rauschma/6f3d7f177e3787f9bc2ee90131153809 to your computer and use it in GitHub Desktop.
Save rauschma/6f3d7f177e3787f9bc2ee90131153809 to your computer and use it in GitHub Desktop.
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 } ]
@tjefferson08
Copy link

Nice gist! Any reason not to include undefined as a "negative" result on line 5?

@georapbox
Copy link

georapbox commented Sep 8, 2020

Nice gist! Any reason not to include undefined as a "negative" result on line 5?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment