mercredi 24 février 2016

Pattern for commonly used Underscore.js iteratees

I'm working on a financial analysis tool using Underscore.js and Underscore-contrib.

I'm often repeating low-level arithmetical primitives. For example, simple summation of an Array:

code-a.js:

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.reduce(arr_a, function(memo, x) { return memo + x; }, 0);
# => 42
_.reduce(arr_b, function(memo, x) { return memo + x; }, 0);
# => 57

I thought about creating a named function to eliminate duplication of the iteratee definition:

code-b.js:

function sum(memo, x) {
  return memo + x;
}

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.reduce(arr_a, sum, 0);
# => 42
_.reduce(arr_b, sum, 0);
# => 57

Then moved on to wrap the reduce call to DRY this out even further:

code-c.js:

function sum(memo, x) {
  return memo + x;
}
function accumulate(vector) {
  _.reduce(vector, sum, 0);
}

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

accumulate(arr_a);
# => 42
accumulate(arr_b);
# => 57

To me, this smells like it's headed for a mixin:

lib-a.js:

_.mixin({
  accumulate: function (vector) {
    _.reduce(vector, function(memo, x) {
      return memo + x;
    }, 0);
  }
});

code-d.js:

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.accumulate(arr_a);
# => 42
_.accumulate(arr_b);
# => 57


Using a mixin gets the job done well. My question is: Are there any other patterns (specific to Underscore.js) for reusing iteratees without using mixins? I don't have an issue using mixins if that's "the" [only] pattern, I'm just asking if there are any other tactics to solve the problem of callback reuse.

For example, code-b.js demonstrates one possible alternative — simply create the iteratee as a named function (perhaps exported from a module to avoid the need for Hungarian-esque naming conventions).

Aucun commentaire:

Enregistrer un commentaire