Currying Up More Examples

A few weeks ago, I wrote an example page on jPaq.org for using the curry function to easily add prototypal functions to the String object. As I was playing around with jPaq, I thought of a few more examples:

// Returns an array of all of the characters in the string.
String.prototype.toCharArray = String.prototype.split.curry("");

// Returns an array of all of the lines in the string.
String.prototype.splitLines = String.prototype.split.curry(/\r?\n|\r/);

// Sorts the array so that numbers are correctly ordered.
Array.prototype.sortNumbers = Array.prototype.sort.curry(function(a, b) {
  return a - b;
});

All of those examples will work with jPaq 1.0 or higher. If you think of other cool examples, let me know.

String.prototype.expandTabs()

I personally love both JavaScript and Python. For this reason, from time to time I like to port functions that are available in Python, over to JavaScript. The following is a port of the expandTabs function.

String.prototype.expandTabs = function(tabSize) {
  tabSize = Math.min(Math.max(parseInt(+tabSize || 8), 1), 32);
  return this.replace(/^.*\t.*$/gm, function(line) {
    var allBefore = "";
    return line.replace(/(.*?)(\t+)/g, function(match, before, tabs) {
      allBefore += before;
      tabs = new Array(1 + tabSize * tabs.length - allBefore.length % tabSize).join(" ");
      allBefore += tabs;
      return before + tabs;
    });
  });
};

The biggest difference between this JavaScript version and the Python version is the limitation of a 32 character tab size. If you want to increase the maximum tab size, simply change 32 to something else.

String.protototype.toCharCodes()

One of the functions that didn’t make the cut for jPaq is String.prototype.toCharCodes().  The reason is I don’t feel that it is a function that many people are looking for.  Still, if you are looking for a good implementation for it, you can use this:

String.prototype.toCharCodes = function() {
  for(var arr = this.split(""), i = this.length - 1; i >= 0; i--)
    arr[i] = arr[i].charCodeAt(0);
  return arr;
};