const obj = {
age_int: 2,
name_string: '1',
job: null,
}
function isInt(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
function validate(type,value){
if (type === "bool" && typeof value !== 'boolean') {
throw new Error('The value must be boolean')
}
else if (type === "string" && !(typeof value === 'string' || target[property] instanceof String)) {
throw new Error('The value must be String')
}
else if (type === "int" && !isInt(value)) {
throw new Error('The value must be int')
}
else if (type === "float" && !isFloat(value)) {
throw new Error('The value must be float')
}
else if (type === "number" && !(isFloat(value) || isInt(value) )) {
throw new Error('The value must be number')
}
}
const handler = {
get(target, property) {
let propertyArr = property.split('_');
let propType = propertyArr[1];
console.log('inside GET', propType, target[property]);
validate(propType,target[property]);
return target[property];
},
set(target, property, value) {
let propertyArr = property.split('_');
let propType = propertyArr[1];
console.log('inside SET', propType, target[property]);
validate(propType,value);
console.log('setting vlaue',target,property, value)
target[property] = value;
return true;
}
}
function typeCheck(object) {
const d = new Proxy(object, handler);
for (const property in d) {
console.log(`${property}: ${d[property]}`);
}
return d;
}
let validatingObject = typeCheck(obj);
validatingObject.nn_bool = true;
console.log('--------',validatingObject)