Skip to content

Instantly share code, notes, and snippets.

@mrowa44
Last active March 13, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrowa44/dfc384aa5a31716de2d0a11ae9a423ba to your computer and use it in GitHub Desktop.
Save mrowa44/dfc384aa5a31716de2d0a11ae9a423ba to your computer and use it in GitHub Desktop.
function checkType(item, test) {
const parsedTest = Array.isArray(test) ? test[0] : test;
return item.constructor === parsedTest;
}
function checkArrayType(value, test) {
const result = [];
value.forEach((item, i) => {
if (typeof item === 'object') {
result.push(checkObjectType(item, test[i]));
} else if (checkType(item, test)) {
result.push(item);
}
});
return result;
}
function checkObjectType(value, test) {
const keys = Object.keys(value);
const result = {};
keys.forEach((key) => {
const newValue = value[key];
debugger;
if (Array.isArray(newValue) && test) {
result[key] = checkArrayType(newValue, test[key]);
} else if (typeof newValue === 'object' && test) {
result[key] = checkObjectType(newValue, test[key]);
} else if (test && test[key] && checkType(newValue, test[key])) {
result[key] = newValue;
}
});
return result;
}
function nestedTypeFilter(value, test) {
if (value === null) {
return undefined;
}
if (Array.isArray(test) || Array.isArray(value)) {
return checkArrayType(value, test);
}
if (typeof value === 'object') {
return checkObjectType(value, test);
}
if (checkType(value, test)) {
return value;
}
return undefined;
}
module.exports = nestedTypeFilter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment