-
-
Save behnamazimi/1d2c35f4649fa04e7c89dacc2bed73c4 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
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