The Importance of Clear Communication
javascript communication collaborationA couple of weeks ago, I was working on two pieces of Javascript code that would apply a test to each item in array. The function every
would return true
if all items in the collection passed the test, while the function some
would return true if one or more of the items passed the test. Writing every
was fairly straightforward using Javascript’s reduce
function, but because I was trying to use my every
function in the some
function to practice functional programming, it took me a while longer to write some
. Worse yet, because both functions deal with many boolean values, they are a bit difficult to discuss. The first time I tried to explain my final version of the some
function to one of my students, it just ended up sounding like gibberish; it sounded something like, “…so if every value is not false, not every returns true, so some is true.” Fortunately the students with whom I was talking is quite bright, so once I showed her how the function worked with an example.
Since I did such a paltry job the first time I tried to explain some
, I’ve decided to try again here. As all teachers know, if you can’t teach it, you don’t really understand it. So, instead of simply providing my solution, here I’m going to try to explain it using pseudocode.
####What the code should do:
every(collection, test)
: Uses javascript’s reduce
function to apply a test to each item, and returns true if all items in the collection pass the test.
some(collection, test)
: Uses every
returns true if at least one item passes the test.
The Logic:
- Use
every
to determine if all of the items fail the test passed intosome
. This means that thisevery
needs to test for the opposite of thesome
test.- If this
every
returnstrue
, none of the items passed the test given tosome
, sosome
should returnfalse
. - If this
every
returns false, at least one item passed the test given tosome
, sosome
should returntrue
.
- If this
Example
var collection1 = {6, 4, 12, 10};
var collection2 = {6, 3, 12, 10};
//Return true if the item is odd.
var isOdd = function(item){
return item % 2 == 1;
}
some(collection1, isOdd);
some
passescollection1
andisOdd
toevery
.every
tests to see if all of the items are not odd (!isOdd
).- All of the items in
collection1
are not odd, soevery
returnstrue
. - When
every
returnstrue
,some
returnsfalse
: none of the items incollection1
are odd.
some
passescollection2
andisOdd
toevery
.every
tests to see if all of the items are not odd (!isOdd
).- Because
collection2[1]
is odd,every
returnsfalse
. - Therefore, at least one item passes the
isOdd
test, sosome
returnstrue
.
Whew! Let me know if this does (or doesn’t!) make sense, and if you have any suggestions for how to improve it!