当前位置: 首页 > 文档资料 > Lazy.js 英文文档 >

define

优质
小牛编辑
140浏览
2023-12-01

Create a new constructor function for a type inheriting from ObjectLikeSequence.

Signature

ObjectLikeSequence.define = function(methodName, overrides) { /*...*/ }
ObjectLikeSequence.define = function define(methodName, overrides) {
  if (!overrides || typeof overrides.each !== 'function') {
throw new Error("A custom object-like sequence must implement *at least* each!");
  }

  return defineSequenceType(ObjectLikeSequence, methodName, overrides);
}
NameType(s)Description
methodNamestring|Array.<string>

The name(s) of the method(s) to be used for constructing the new sequence. The method will be attached to the ObjectLikeSequence prototype so that it can be chained with any other methods that return object-like sequences.

overridesObject

An object containing function overrides for this new sequence type. Must include each. May include init and get (for looking up an element by key).

returnsFunction

A constructor for a new type inheriting from ObjectLikeSequence.

Examples

function downcaseKey(value, key) {
  return [key.toLowerCase(), value];
}

Lazy.ObjectLikeSequence.define("caseInsensitive", {
  init: function() {
var downcased = this.parent
  .map(downcaseKey)
  .toObject();
this.downcased = Lazy(downcased);
  },

  get: function(key) {
return this.downcased.get(key.toLowerCase());
  },

  each: function(fn) {
return this.downcased.each(fn);
  }
});

Lazy({ Foo: 'bar' }).caseInsensitive()            // sequence: { foo: 'bar' }
Lazy({ FOO: 'bar' }).caseInsensitive().get('foo') // => 'bar'
Lazy({ FOO: 'bar' }).caseInsensitive().get('FOO') // => 'bar'