transform-implementations

Benchmark created by James Kyle on


Preparation HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>


<script>
var optimizeCb = function(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {
        return func.call(context, value);
      };
      case 2: return function(value, other) {
        return func.call(context, value, other);
      };
      case 3: return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
      case 4: return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  };

var transform1 = function(obj, iteratee, accumulator, context) {
    iteratee = optimizeCb(iteratee, context, 4);
    var isArr = _.isArray(obj),
        keys = obj.length !== +obj.length && _.keys(obj),
        length = (keys || obj).length,
        index = 0;
    if (accumulator == null) {
      if (isArr) {
        accumulator = [];
      } else {
        accumulator = {};
      }
    }
    for (; index < length; index++) {
      currentKey = keys ? keys[index] : index;
      iteratee(accumulator, obj[currentKey], currentKey, obj);
    }
    return accumulator;
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
transform1: object
transform1({ a: 1, b: 2, c: 3}, function(accumulator, value, key) {
  accumulator[key] = value;
}, {});
ready
transform1: array
transform1([1, 2, 3], function(accumulator, value, key) {
  accumulator[key] = value;
}, []);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by James Kyle on