1 Introducing Functional JavaScript

The Case for JavaScript

[1, 2, 3].forEach(alert);
function splat(fun) {
  return function(array) {
    return fun.apply(null, array);
  };
}
var addArrayElements = splat(function(x, y) {return x + y});

addArrayElements([1, 2]);
function unsplat(fun) {
 return function() {
 return fun.call(null, _.toArray(arguments));
 };
}
var joinElements = unsplat(function(array) { return array.join(' ') });
joinElements(1, 2);
//=> "1 2"
joinElements('-', '$', '/', '!', ':');
//=> "- $ / ! :"

Some Limitations of JavaScript

Getting Started with Functional Programming

Why Functional Programming Matters

Functions as Units of Abstraction

function fail(thing) {
  throw new Error(thing);
}

function warn(thing) {
  console.log(["WARNING:", thing].join(' ') );
}

function note(thing) {
  console.log(["NOTE:", thing].join(' '));
}
function parseAge(age) {
  if(!_.isString(age)) fail("Expecting a string");
  var a;

  note("Attempting to parse an age");
  a = parseInt(age, 10);

  if(_.isNaN(a)) {
    warn(["Could not parse age:", age].join(' '));
    a = 0;
  }
  return a;
}
parseAge("frob");
// (console) NOTE: Attempting to parse an age
// (console) WARNING: Could not parse age: frob
//=> 0

Encapsulation and Hiding

functional encapsulation - closures

Functions as Units of Behavior

function naiveNth(a, index) {
  return a[index];
}

naiveNth(letters, 1);
//=> "b"

naiveNth({}, 1);
//=> undefined
function isIndexed(data) {
  return _.isArray(data) || _,isString(data);
}
function nth(a, index) {
  if(!_.isNumber(index)) fail("Expected a number as the index");
  if(!isIndexed(a)) fail("Not supported on non-indexed type");
  if((index < 0) || (index > a.lenght - 1))
    fail("Index value is out of bounds");
  return a[index];
}
nth(letters, 1);
//=> 'b'

nth("abc", 0);
//=> "a"

nth({}, 2);
// Error: Not supported on non-indexed type

nth(letters, 4000);
// Error: Index value is out of bounds

nth(letters, 'aaaaa');
// Error: Expected a number as the index
function second(a) {
  return nth(a, 1);
}

Another unit of basic behavior in JavaScript is the idea of a comparator.

[0, -1, -2].sort();
//=> [-1, -2, 0]
[2, 3, -1, -6, 0, -108, 42, 10].sort();
//=> [-1, -108, -6, 0, 10, 2, 3, 42]
[2, 3, -1, -6, 0, -108, 42, 10].sort(function(x,y) {
 if (x < y) return -1;
 if (y < x) return 1;
 return 0;
});

function compareLessThanOrEqual(x, y) {
  if(x < y) return -1;
  if(y < x) return 1;
  return 0;
}

[2, 3, -1, -6, 0, -108, 42, 10].sort(compareLessThanOrEqual);
//=> [-108, -6, -1, 0, 2, 3, 10, 42]
function lessOrEqual(x, y) {
  return x<= y;
}

[2, 3, -1, -6, 0, -108, 42, 10].sort(lessOrEqual);
//=> [100, 10, 1, 0, -1, -1, -2]

Data as Abstraction

function lameCSV(str) {
 return _.reduce(str.split("\n"), function(table, row) {
 table.push(_.map(row.split(","), function(c) { return c.trim()}));
 return table;
 }, []);
};

A Taste of Functional JavaScript

function existy(x) {return x != null};
existy(null);
//=> false
existy(undefined);
//=> false
existy({}.notHere);
//=> false
existy((function(){})());
//=> false
existy(0);
//=> true
existy(false);
//=> true
function truthy(x) {return (x !== false) && existy(x)};
truthy(false);
//=> false
truthy(undefined);
//=> false
truthy(0);
//=> true
truthy('');
//=> true

On Speed

The Case for Underscore

Summary

  • Identifying an abstraction and building a function for it
  • Using existing functions to build more complex abstractions
  • Passing existing functions to other functions to build even more complex abstractions

你可能感兴趣的:(1 Introducing Functional JavaScript)