Created
February 10, 2020 05:16
-
-
Save deanacus/759f6fe011fd126e9cbf52a413f6d06c to your computer and use it in GitHub Desktop.
Object Recursion exploration stuff
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 deep clone implementation, with immutability. | |
*/ | |
const cloneObject = input => { | |
if ( | |
!Array.isArray(input) && | |
Object.getPrototypeOf(input).toString.call(input) !== "[object Object]" | |
) { | |
return input; | |
} | |
if (Array.isArray(input)) { | |
return input.map(item => cloneObject(item)); | |
} | |
return Object.keys(input).reduce((acc, curr) => { | |
acc[curr] = cloneObject(input[curr]); | |
return acc; | |
}, {}); | |
}; | |
/** | |
* A kind of object reduce implementation that allows arbitrary transformation of primitive values | |
*/ | |
const reduceObject = function(input, transformer) { | |
if ( | |
!Array.isArray(input) && | |
Object.getPrototypeOf(input).toString.call(input) !== "[object Object]" | |
) { | |
return transformer(input); | |
} | |
if (Array.isArray(input)) { | |
return input.map(item => reduceObject(item, transformer)); | |
} | |
return Object.keys(input).reduce((acc, curr) => { | |
acc[curr] = reduceObject(input[curr], transformer); | |
return acc; | |
}, {}); | |
}; | |
/** | |
* My "whiteboard" test | |
*/ | |
const stripRaw = function(input) { | |
if ( | |
!Array.isArray(input) && | |
Object.getPrototypeOf(input).toString.call(input) !== "[object Object]" | |
) { | |
return input; | |
} | |
if (Array.isArray(input)) { | |
return input.map(item => stripRaw(item)); | |
} | |
const data = {} | |
Object.keys(input).map(key => { | |
if(key !== 'raw') { | |
data[key] = stripRaw(input[key]) | |
} | |
}) | |
return data | |
}; | |
/** | |
* A slightly modified version of my "whiteboard" test | |
*/ | |
const stripRawModified = function(input) { | |
if ( | |
!Array.isArray(input) && | |
Object.getPrototypeOf(input).toString.call(input) !== "[object Object]" | |
) { | |
return input; | |
} | |
if (Array.isArray(input)) { | |
return input.map(item => stripRawModified(item)); | |
} | |
return Object.keys(input).reduce((acc, curr) => { | |
if(curr === 'raw') return acc; | |
acc[curr] = stripRawModified(input[curr]); | |
return acc; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment