Last active
August 16, 2017 11:50
-
-
Save emolr/9dd8ac49f39c1d6bf5872e7955deecd6 to your computer and use it in GitHub Desktop.
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
const data = { | |
title: 'hello world', | |
endTime: 123456, | |
foo: [1, 2, 3] | |
}; | |
const properties = { | |
title: 'string', | |
endTime: 'number', | |
foo: 'array' | |
}; | |
/** | |
* Has prop types checker | |
* Checks if necessary keys and types are present in object. | |
* the object can contain more keys than the ones being checked for. | |
* | |
* @param obj | |
* @param expected - {key: 'string|boolean|object|array|number|symbol|function'} | |
* @return {boolean} | |
*/ | |
const hasPropTypes = (obj, expected) => { | |
if (typeof obj !== 'object' || obj === null) { | |
return false; | |
}; | |
return Object.keys(expected).every(key => { | |
if (!obj.hasOwnProperty(key)) { | |
return false; | |
} | |
switch (expected[key]) { | |
case 'array': | |
return Array.isArray(obj[key]); | |
default: | |
return typeof obj[key] === expected[key] | |
} | |
}); | |
}; | |
console.log(hasPropTypes(data, properties)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment