【问题标题】:implement a function which adds a type validation to an object实现一个向对象添加类型验证的函数
【发布时间】:2022-06-17 17:35:15
【问题描述】:

您的函数应该接收一个对象作为其唯一参数,并返回一个具有相同属性但添加了类型验证的对象。应在以下情况下验证类型:

  • 函数创建对象;
  • 有人更新了属性;
  • 有人添加了属性;

类型验证应始终基于属性名称的最后一部分。例如,age_int 属性应始终为整数,并在设置为其他值时抛出错误

以下是可能的类型:

  • 字符串:例如“字符串类型”
  • int:12.00 和 12 都是整数。
  • 浮点数:例如,12.34
  • 数字:任何整数或浮点数
  • bool:例如,true

假设

  • 类型是可选的,如果未指定类型,则应跳过验证。
  • 始终位于类型名称之前。

示例

你的函数应该如下所示:

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

我尝试了下面的代码,但没有成功。

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);

【问题讨论】:

    标签: javascript javascript-objects


    【解决方案1】:

    typeof value == typecheck,应该有括号,以明确它的行为:

    typeof "string" == 33 // false
    typeof ("string" == 33) // 'boolean'
    (typeof "string") == 33 // false
    

    注意split,如果不存在下划线则不会出错:

    "age".split('_').pop(); // "age"
    "age_int".split('_').pop(); // "int"
    "int".split('_').pop(); // "int" <-- this may throw you off
    

    检查每个键的_ 下划线是否具有有效类型("int""string"、任何自定义类型)。如果没有,则跳过迭代。

    如果你想停止程序执行,也许你想使用throw new Error("message")

    如果您解决了split 问题,您的代码似乎确实可以按预期工作。

    以防万一,也许您正在寻找 Typescriptclass-validatoryup(或任何等效项)。


    编辑:我看到您还希望返回一个对象 const validatingbject=typeCheck(obj),但 typecheck 函数不包含返回语句。

    如果你想让 validatingobject.age_int=2.25 出错,你首先需要有一个 setter ......在这里你可以帮助你:

    function validateTypeOrThrow(e, type) {
      if (type === 'int' && !Number.isInteger(e)) {
        throw new Error(`${e} is not a ${type} !`);
      }
    }
    
    const obj = {};
    
    obj._age_int = 33; // initial value
    
    // _age_int starting with underscore is convention for private
    Object.defineProperty(obj, 'age_int', {
      set(value) {
        // this will infinite loop
        // this.age_int = value;
    
        this._age_int = value;
      },
      get () {
        // this will infinite loop
        // return this.age_int;
    
        validateTypeOrThrow(this._age_int , 'int');
    
        return this._age_int;
      },
    });
    
    console.log(obj.age_int);
    
    obj.age_int = 22;
    console.log(obj.age_int)
    
    obj.age_int = 'str'; // no error
    console.log(obj.age_int) // error
    

    【讨论】:

    • 对象中的值会变化,它会动态变化。所以我不能说它会带有“_”
    • @KeerthiReddyYeruva 由你来处理这种情况。只需检查"_".includes("_") 或正则表达式。我认为您拥有使其工作所需的一切:)。
    【解决方案2】:

    这里是解决方案 使用包含()

    function typeCheck(object) {
            for(key in object) {
    
            if(key.includes('string')) {
                console.log(object[key]);
              if(typeof(object[key]) != 'string') {
                throw Error;
              }
            } else if(key.includes('int') || key.includes('float') || key.includes('number')) {
                console.log(object[key]);
               if(typeof(object[key]) != 'number') {
                  throw Error;
               } else if (key.includes('int')) {
                  if(Number.isInteger(object[key])) {console.log("true");} 
                  else {throw Error;}              
               } else if (key.includes('float')) {
                    if(Number.isInteger(object[key])) {throw Error;} 
                  else {console.log("true");}
               }
            } else if(key.includes('bool')) {
               if(typeof(object[key]) != 'boolean') {throw Error;}
            } else if(typeof(object[key] == 'object')) {console.log('object' +" "+ object[key]);}
            else {return object;}
            }
    
            return object;
        }
        
        const obj = {
            age_int: 23,
            name_string: "name",
            age_float: 22.4,
            Job: null,
        }
        
        const validatingbject = typeCheck(obj);
        console.log(validatingbject);
        validatingbject.job="fireman";
        validatingbject.age_int=2.25;
        typeCheck(obj);
    
       const obj_2= {employed_bool: "true",}
       validatingbject = typeCheck(obj_2)

    强文本

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2014-08-09
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多