Last active
June 30, 2019 17:59
-
-
Save CalisaP/eaa791f0496d0f225f71a83a03bc5f3d to your computer and use it in GitHub Desktop.
fCC: Intermediate Algorithm Scripting: Everything Be True
This file contains hidden or 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
//Check if the predicate (second argument) is truthy on all elements of a collection (first argument). | |
function truthCheck(collection, pre) { | |
// .every returns one value if EVERY object statifies the test. | |
// !! (double bang) typecasts the property value to a boolean value. | |
// It will return true if the property value is truthy & false if the property doesn't exist/has a falsy value. | |
return collection.every(obj => !!obj[pre]); | |
} | |
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"); | |
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't have to do too much research on this one because I've encountered truthy and falsy values before.
I started out with
.forEach()
and nestedif
statements using.hasOwnProperty()
and then bracket notation (obj[pre]
)to access the value of the relevant property, but that obviously returned many boolean values and what I wanted was one to indicate whether ALL elements satisfied the condition.Enter
.every()
and the little bit of research I did do to find out whether there was a better way to evaluate the truthiness of a property value thanobj[pre] === true
. It turns out there are multiple ways and they all have their pros and cons. It looked like the double bang (gotta love that name) property lookup is what I was looking for.(I bookmarked the article that introduced me to my new fave because I have a feeling I'll be needing it again.)