Last active
December 17, 2019 01:38
-
-
Save Spraynard/0ac3aaeb2664ee6272f1f4fba5941b62 to your computer and use it in GitHub Desktop.
Tail recursive function to remove specified keys out from object
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
/** | |
* Given a array of keys, filter those keys out of target object. | |
* If the key isn't in the object, that's okay. | |
* | |
* Example: | |
* filterFromObject(['a', 'b', 'c'], { 'a' : true, 'b' : true, 'c' : true, 'd' : true }) => {'d' : true} | |
* @param {array} keys_to_remove - Keys to remove from our object | |
* @param {object} target - Object to remove our keys from | |
*/ | |
export const filterFromObject = ( keys_to_remove, target ) => { | |
if ( ! Array.isArray(keys_to_remove) ) | |
{ | |
throw new Error(`You must supply an array for the keys_to_remove parameter, ${keys_to_remove} given`); | |
} | |
// Base Case | |
if ( ! keys_to_remove.length ) | |
{ | |
return target; | |
} | |
const [ current, ...rest ] = keys_to_remove; | |
// Recursive Case 1 | |
if ( ! ( current in target )) { | |
// Iterate to the next key to remove if there is nothing in our target object | |
return filterFromObject( rest, target ); | |
} | |
// Removing our keyed object property from target by destructuring it out and using the newly made object in sequential iterations | |
let { [key] : deleted, ...other } = target; | |
// Recursive case 2 | |
return filterFromObject( rest, other ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment