Accessor functions

Benchmark created by Neil MacMunn on


Setup

function Accessor(initial, options) {
    
      options = options || {};
    
      var fn = function(newVal) {
        return arguments.length ? fn.set(newVal) : fn.get();
      };
    
      fn._config = {
        read: !options.hasOwnProperty('read') || options.read,
        write: !options.hasOwnProperty('write') || options.read
      };
    
      if (options.safe || Object.prototype.__proto__ === undefined) {
        for (var method in Accessor.prototype) {
          if (Accessor.prototype.hasOwnProperty(method)) {
            fn[method] = this[method].bind(fn);
          }
        }
      } else {
        fn.__proto__ = this.__proto__;
      }
    
      return fn.set(initial, true).update();
    }
    
    Accessor.prototype.set = function(newVal, force) {
      if (this._config.write || force) {
        this._current = newVal;
      }
      return this;
    };
    
    Accessor.prototype.get = function(force) {
      if (this._config.read || force) {
        return this._current;
      }
    };
    
    Accessor.prototype.update = function() {
      this._previous = this._current;
      return this;
    };
    
    Accessor.prototype.reset = function() {
      this._current = this._previous;
      return this;
    };
    
    Accessor.prototype.changed = function() {
      return this._current !== this._previous;
    };
    
    Accessor.prototype.toJSON = function() {
      return this.get(false);
    };
    
    // polyfill
    if (!Function.prototype.bind) {
      Function.prototype.bind = function(oThis) {
        if (typeof this !== 'function') {
          // closest thing possible to the ECMAScript 5
          // internal IsCallable function
          throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }
    
        var aArgs = Array.prototype.slice.call(arguments, 1),
          fToBind = this,
          fNOP = function() {},
          fBound = function() {
            return fToBind.apply(this instanceof fNOP ? this : oThis,
              aArgs.concat(Array.prototype.slice.call(arguments)));
          };
    
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
    
        return fBound;
      };
    }
    
    var test = function(options) {
      var accessor = new Accessor(1, options);
      accessor();
      accessor(2);
      accessor.get();
      accessor.set(3);
      accessor.changed();
      accessor.reset();
      accessor(0);
      accessor.update();
    }

Test runner

Ready to run.

Testing in
TestOps/sec
BoundAccessor
test({safe: true});
ready
MutatedAccessor
test();
ready

Revisions

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

  • Revision 1: published by Neil MacMunn on