The Little

JavaScripter - 2



@dhavaltrivedi









What is JavaScript?



Java.
In Browser.



Lisp. 

In C's Clothing.






JavaScript has more in common with functional languages like 
Lisp or Scheme than with C or Java.






Let's Dive Deep




Functional Programming 

Functions are First Class Citizens




1. Functions are values

(so can be passed around)

function printArray(array) {
  for (var i = 0; i < array.length; i++)
    print(array[i]);
}

to

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

forEach(["Wampeter", "Foma", "Granfalloon"], print);





2. Lambdas

function sum(numbers) {
  var total = 0;
  forEach(numbers, function (number) {
    total += number;
  });
  return total;
}
show(sum([1, 10, 100]));




3. Higher order functions

function negate(func) {
  return function(x) {
    return !func(x);
  };
}
var isNotNaN = negate(isNaN);
show(isNotNaN(NaN));




4. Closures

function makeAddFunction(amount) {
  function add(number) {
    return number + amount;
  }
  return add;
}

var addTwo = makeAddFunction(2); var addFive = makeAddFunction(5); show(addTwo(1) + addFive(1));




Putting it together

Map


function map(func, array) {
  var result = [];
  forEach(array, function (element) {
    result.push(func(element));
  });
  return result;
}

show(map(Math.round, [0.01, 2, 9.89, Math.PI]));

Reduce

function reduce(combine, base, array) {
  forEach(array, function (element) {
    base = combine(base, element);
  });
  return base;
}
function add(a, b) {
  return a + b;
}

function sum(numbers) {
  return reduce(add, 0, numbers);
}show(sum([1,2,3,4,5]));

Composition

function compose(func1, func2) {
  return function() {
    return func1(func2.apply(null, arguments));
  };
}function negate(a) {  return !a;}
var isNotNaN = compose(negate, isNaN);show(isNotNaN(NaN));



Being able to write what we want to do instead of how we do it

=

working at higher level of abstraction.




<3λ & HF.

thelittlejavascripter2

By dytrivedi

thelittlejavascripter2

  • 762