The Importance of Clear Communication

javascript communication collaboration

A 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 into some. This means that this every needs to test for the opposite of the some test.
    • If this every returns true, none of the items passed the test given to some, so some should return false.
    • If this every returns false, at least one item passed the test given to some, so some should return true.

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);
  1. some passes collection1 and isOdd to every.
  2. every tests to see if all of the items are not odd (!isOdd).
  3. All of the items in collection1 are not odd, so every returns true.
  4. When every returns true, some returns false: none of the items in collection1 are odd.
some(collection2, isOdd);
  1. some passes collection2 and isOdd to every.
  2. every tests to see if all of the items are not odd (!isOdd).
  3. Because collection2[1] is odd, every returns false.
  4. Therefore, at least one item passes the isOdd test, so some returns true.

Whew! Let me know if this does (or doesn’t!) make sense, and if you have any suggestions for how to improve it!

Written on May 24, 2015