Last active
May 9, 2018 02:25
-
-
Save bdav87/cb13f66eb3108c9d9a88e2ccf9797d84 to your computer and use it in GitHub Desktop.
Passing unit tests
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
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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