Your function should receive an object as its only argument and return an object with the same properties, but with type validation added. Types should be validated when:
- the function creates the object;
- Someone updates a property;
- Someone adds a property;
The type validation should always be based on the last part of the property name. For example,
age_intproperty should always be an integer and throw an error when set to something elseHere are possible types:
- string: for example, "string type"
- int: 12.00 and 12 are both integers.
- float: for example, 12.34
- number: any int or float
- bool: for example, true
Assumptions
- Types are optional and validation should be skipped if the type isn't specified.
- always precedes the type name.
Examples
Your function should behave as shown below:
const obj= { age_int: 2, name_string:"John", Job: null, } const validatingbject=typeCheck(obj) validatingobject.age_int=2.25 // Throws error validatingbject.age.int= 2 validatingoject.job="fireman" validatingbject.address_string= 20 // Throws error const obj_2= {employed_bool: "true",} const validatingobject = typeCheck(obj_2) // Throws error
I tried the code below but was unsuccessful.
function typeCheck(object) {
console.log(Object.entries(object));
Object.entries(object).forEach(([key, value]) => {
let type = key.split('_').pop();
let typecheck;
console.log("type:", type);
if (type === "float" || type === "int" || type === "number") {
typecheck = "number";
} else if (type === "bool") {
typecheck = "boolean";
} else if (type === "string") {
typecheck = "string";
}
if (typeof value == typecheck) {
return true;
} else {
console.error("error")
}
});
}
const obj = {
age_int: 2,
name_string: "John",
Job: null,
}
const validatingbject = typeCheck(obj);