Tuesday 1 February 2011

Week 1 Exercise 3.2 Function greaterThan that returns a function

Write a function greaterThan, which takes one argument, a number, and returns a function that represents a test. When this returned function is called with a single number as argument, it returns a boolean: true if the given number is greater than the number that was used to create the test function, and false otherwise.

On my first attempt I was not what the question was trying to get me to do.

function greaterThan (a){
  function test (y){
    if (a < y) {
      return true;
    }else {
      return false;}
  }
    show (test (50));
  }
  show (greaterThan(3));
 
After reading the solution, it was a bit more clear:

function greaterThan (a){
  return function test (y){
    return y > a;
};   
  }

var greaterThanTen = greaterThan(10);
show (greaterThanTen (9));

The last few parts of chapter two of the book that concerns anonymous function and recursion was more complicated. It requires multiple read through.

Week 1 Exercise 3.1 Function to return the absolute value of a number

Ex 3.1

My attempt to create a function that returns an absolute value of a number. I created an if else statement. If the argument is greater than 0, you return the value. Otherwise, multiply the number with -1 and return that value.

function absolute (a) {
  if (a > 0) {
    return a;
  }
  else {
    a = -1*a;
    return a;
  }
}