Monday, October 7, 2013

Overload

The last week or two has been a lot to take in and definitely too much for me to write about. I am reading script much more fluidly and I understand jquery (and other libraries), click handlers and the how to traverse the DOM. Functional programming is easy to grasp, but more difficult to master and consistently apply to all of your code. Often times there is an easy solution that involves impure functions, but the quest for purity pays dividends in the long run when your functions are contained and their side effects are easily trackable.

Here is an example from an exercise this week that illustrates the beauty and challenge of functional programming. The assignment was to alter the javascript .splice(arr) method so that it does not modify the array that is passed as an argument. What splice currently does:

arr.splice(indexToStartRemove, numToRemove, insert, insert, insert)
Splice starts removing values out of an array at "indexToStartRemove" and removes "numToRemove" values upwards through the array. It then inserts any values listed in the 3rd, 4th...nth parameters listed in the method. Below is a concrete example. An array with values ordered through the array is modified so that the 0th index is removed and replaced by the number value 99.

var array = [1,2,3,4,5,6,7,8,9,10] 
array.splice(0,1,99)
console.log(array) // returns [99,2,3,4,5,6,7,8,9,10]
The following is an example of a splice function that behaves in the same way while remaining pure and not modifying the existing array:


var array = [1,2,3,4,5,6,7,8,9,10]
var splice = function(indexToRemove, numToRemove, insert){
  newArray = []
  for(i=0; i<indexToRemove; i++){
    newArray.push(array[i]); 
  }
  for(i=3; i<arguments.length; i++){
    newArray.push(arguments[i]);
  }
  for(i=indexToRemove+numToRemove; i<array.length; i++){
    newArray.push(array[i]);
  }
  return newArray
} 

One line wonder. A few hacks involved. Array.prototype applies the .slice() method to the arguments "array-like object". For whatever reason JS decided that all functions should contain a native arguments property for all parameters, should look like array, but not have all the properties of an array, or for that matter be one. Mystifying.
var splice = function(){
  [].concat(array.slice(0,indexToRemove)).Array.prototype.apply().slice().concat(arguments.slice(3,arguments.length)).concat(array.slice(indexToRemove+numToRemove, array.length));
}