Created
September 7, 2020 17:19
-
-
Save rajatjain-21/d0b2986d3626adae9b8d5219660286b5 to your computer and use it in GitHub Desktop.
This is a custom method to partition any array based on the logic provided
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
/** | |
* A function that partitions an array based on the passed logic | |
* @param arr The array to be partitioned | |
* @param callback The logic function to base the partition on | |
*/ | |
const partition = (arr, callback) => { | |
// The result object which will ultimately have two properties | |
// positive and negative | |
const result = {}; | |
arr.forEach((item, index) => { | |
// Here the callback will return either positive or negative string | |
const key = callback(item, index); | |
// If any key is coming for the first time | |
if(!result.hasOwnProperty(key)) { | |
result[key] = []; | |
} | |
result[key].push(item); | |
}) | |
//result will have {"positive": [1, 3, 5], "negative": [-4, -2, -6]} | |
return result; | |
} | |
// The array to be partitioned | |
const arr = [1, 3, -4, 5, -2, -6]; | |
//partition function in action | |
const {positive, negative} = partition(arr, (item, index) => { | |
return item > 0 ? "positive" : "negative"; | |
}); | |
console.log(positive); | |
// [1, 3, 5] | |
console.log(negative); | |
// [-4, -2, -6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment