Skip to content

Instantly share code, notes, and snippets.

@bdav87
Last active May 9, 2018 02:25
Show Gist options
  • Save bdav87/cb13f66eb3108c9d9a88e2ccf9797d84 to your computer and use it in GitHub Desktop.
Save bdav87/cb13f66eb3108c9d9a88e2ccf9797d84 to your computer and use it in GitHub Desktop.
Passing unit tests
module.exports = {
nestedTypeFilter: function(inputObject, typeSpec) {
//Immediately passes basic filter tests
//Runs through chain of filters otherwise
if ((typeof typeSpec == 'function') && (typeof inputObject != 'object')) {
return basicFilter(inputObject, typeSpec);
} else {
return cycleFilter(inputObject, typeSpec);
}
//A way to organize the process
function cycleFilter(input, spec) {
if (checkArrays(input, spec) == false) {
return checkObjects(input, spec)
} else {
return checkArrays(input, spec)
}
}
//Needed to determine if a typespec, nested or otherwise, is a function
function check_function_type(data) {
if (typeof data == 'function'){
return data();
}
return data;
}
//Compares input directly to spec
function basicFilter(input, spec) {
if (typeof input == typeof check_function_type(spec)){
return(input);
}
if (typeof input != typeof check_function_type(spec)){
return(undefined);
}
}
function checkArrays(input, spec) {
if (Array.isArray(input)) {
const output = input.filter(item => {
if (typeof item == typeof check_function_type(spec[0])) {
if (item == 0) {
return '0';
}
return item;
}
});
return(output);
}
else {
return(false);
}
}
function checkObjects(input, spec) {
if (input == null) {
return undefined
}
if (typeof input == 'object' && input != null){
const newObj = {}
for (i in input) {
if (typeof input[i] == typeof check_function_type(spec[i])) {
newObj[i] = input[i];
}
}
return(newObj);
} else {
return(false);
}
}
}
}
@bdav87
Copy link
Author

bdav87 commented May 5, 2018

Revision 1 is the official version created during exercise time limit
Revision 2 passes additional tests for arrays and objects
Revision 3 code is more modular and handles arbitrarily deep object

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