美文网首页
Everything Be True | Free Code C

Everything Be True | Free Code C

作者: Marks | 来源:发表于2017-05-08 09:55 被阅读109次

    Check if the predicate (second argument) is truthy on all elements of a collection (first argument).
    truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") should return true.
    truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") should return false.
    truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age") should return false.
    truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat") should return false
    truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat") should return true
    truthCheck([{"single": "yes"}], "single") should return true
    truthCheck([{"single": ""}, {"single": "double"}], "single") should return false
    truthCheck([{"single": "double"}, {"single": undefined}], "single") should return false
    truthCheck([{"single": "double"}, {"single": NaN}], "single") should return false

    //Wrong
    function truthCheck(collection, pre) {
      // Is everyone being true?
      var args = collection.prototype.slice.call(arguments);
      for(var i=0;i<args.length;i++){
        return args.indexOf(pre) !== -1 && Boolean(args[pre]);
      }
      
    }
    
    truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");```
    
    ![Wrong](https://img.haomeiwen.com/i316258/efda8a67f74a2ed8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
    

    function truthCheck(collection, pre) {
    // Is everyone being true?
    return collection.every(function(elements){
    return elements.hasOwnProperty(pre) && Boolean(elements[pre]);
    });

    }

    truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");```

    相关文章

      网友评论

          本文标题:Everything Be True | Free Code C

          本文链接:https://www.haomeiwen.com/subject/yacmtxtx.html