Skip to content

Commit

Permalink
Function responsibility and a lot of fixes on call, apply,bind courte…
Browse files Browse the repository at this point in the history
…sy Joy again
  • Loading branch information
srijayanth committed Oct 2, 2017
1 parent 5322e08 commit fc866cd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
22 changes: 20 additions & 2 deletions docs/call_apply_bind.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ Turns out it does.
Consider a series of tests on `isOdd`

```javascript
const isOdd=function(number) {
return number%2!=0;
}

const testEvenPositiveNumbers=function() {
assert.equal(false,isOdd(2))
}
Expand All @@ -209,6 +213,10 @@ This is fine, but it is too involved. All the functions are simply asserting aga
What if we write a generic function that can test anything?

```javascript
const isOdd=function(number) {
return number%2!=0;
}

const testAnything=function(msg,expectation,fnName,argument) {
console.log(msg);
assert.equal(expectation,fnName(argument));
Expand Down Expand Up @@ -242,7 +250,7 @@ Which one though? Will `call` work? Let us see.
```javascript
const testAnything=function(msg,expectation,fnName,arg1,arg2) {
console.log(msg);
let actual=fnName.call(arg1,arg2);
let actual=fnName.call(null,arg1,arg2);
assert.equal(expectation,actual);
}
```
Expand All @@ -255,9 +263,17 @@ Read about [how this is done](varargs) if you don't know it already.

Let us see.
```javascript
const isOdd=function(number) {
return number%2!=0;
}

const greaterThan=function(first,second) {
return first>second;
}

const testAnything=function(msg,expectation,fnName,...args) {
console.log(msg);
let actual=fnName.apply(args);
let actual=fnName.apply(null,args);
assert.equal(expectation,actual);
}

Expand All @@ -269,9 +285,11 @@ testAnything("even positive numbers",false,isOdd,2);
testAnything("first number greater",2,greaterOf,2,1);
testAnything("second number greater",2,greaterOf,1,2);
```
> _We have used `null` as the first argument to `apply` because we don't really have a calling context here._
We now truly have a `testAnything`. In fact, now our `testAnything` can be improved to have more `console.log` statements that outline the arguments passed and we will have a lot more informative framework.


----
#### `bind`

Expand Down
4 changes: 4 additions & 0 deletions docs/function_guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Here are some guidelines that will help you write better functions. If you follo

----

**Responsibility**
* A function should do only one thing and do it well :star: :star: :star:


**Naming your functions**
* Write the usage first, define later.
* Verbs make better names than nouns.
Expand Down

0 comments on commit fc866cd

Please sign in to comment.