SidekickJS's blog

takeThis() - unite JS's APIs

I’d like to introduce the takeThis() function, which immediately reminds me of fights in old movies:

“Oh really pal, well… TAKE THIS!! WHAM

takeThis() usefully marries the two halves of JS’s schizophrenic object-oriented/functional character. Functions like join() and split() live as prototype methods, which take their main argument from their call-site: this. This makes using them with higher-order functions, like map(), a pain. The pain is obvious when even a simple job like splitting all the strings in a list require an extra function literal:

var strings = ["a b c","d e f"];
var split = strings.map(function(s) {
  return s.split(" ")
});

It also precludes using the methods in pipelines created via functional composition - and anywhere of the other standard functional tricks.

takeThis() solves this by taking the arguments first, and returning a function that applies them when it receives the value of this:

Function.prototype.takeThis = function() {
  var fn = this;
  var args = arguments;
  return function(thisVal) {
    return fn.apply(thisVal,args)
  }
}

Here I’ve defined it on the Function.prototype as I live on the edge (only in programming, I’m in bed by 11). I’m not very worried about clashes - if you are, I’d recommend agave.js.

var lists = [
  [1,2,3],
  ["a","b","c"]
];
var lyrics = [
  "five to one baby",
  "scaring the nation with their"
];
var needTrimming = [
  " i have lots of whitespace ",
  " so do i      "
];

lists.map([].join.takeThis(","));
lyrics.map("".split.takeThis(" "));
needTrimming.map("".trim.takeThis());

As you can see, we can now easily use the prototype methods like any other function!

See it in action. I’ll be sharing more JS tools and tricks, follow me to hear about them!