mixin Enumerable
Description
Enumerable provides a large set of useful methods for enumerations —
objects that act as collections of values. It is a cornerstone of
Prototype.
Enumerable is a mixin: a set of methods intended not for standaone
use, but for incorporation into other objects.
Prototype mixes Enumerable into several classes. The most visible cases
are Array and Hash, but you’ll find it in less obvious spots as
well, such as in ObjectRange and various DOM- or Ajax-related objects.
The context parameter
Every method of Enumerable that takes an iterator also takes the "context
object" as the next (optional) parameter. The context object is what the
iterator will be bound to — what the keyword this will refer to inside
the iterator.
var myObject = {};
['foo', 'bar', 'baz'].each(function(name, index) {
this[name] = index;
}, myObject); // we have specified the context
myObject
//-> { foo: 0, bar: 1, baz: 2}
If there is no context argument, the iterator function will execute in
the scope from which the Enumerable method itself was called.
Mixing Enumerable into your own objects
So, let’s say you’ve created your very own collection-like object (say,
some sort of Set, or perhaps something that dynamically fetches data
ranges from the server side, lazy-loading style). You want to be able to
mix Enumerable in (and we commend you for it). How do you go about this?
The Enumerable module basically makes only one requirement on your object:
it must provide a method named _each (note the leading underscore) that
will accept a function as its unique argument, and will contain the actual
“raw iteration” algorithm, invoking its argument with each element in turn.
As detailed in the documentation for Enumerable#each, Enumerable
provides all the extra layers (handling iteration short-circuits, passing
numeric indices, etc.). You just need to implement the actual iteration,
as fits your internal structure.
If you're still confused, just have a look at the Prototype source code for
Array, Hash, or ObjectRange. They all begin with their own
_each method, which should help you grasp the idea.
Once you’re done with this, you just need to mix Enumerable in, which
you’ll usually do before defining your methods, so as to make sure whatever
overrides you provide for Enumerable methods will indeed prevail. In
short, your code will probably end up looking like this:
var YourObject = Class.create(Enumerable, {
initialize: function() { // with whatever constructor arguments you need
// Your construction code
},
_each: function(iterator) {
// Your iteration code, invoking iterator at every turn
},
// Your other methods here, including Enumerable overrides
});
Then, obviously, your object can be used like this:
var obj = new YourObject();
// Populate the collection somehow
obj.pluck('somePropName');
obj.invoke('someMethodName');
obj.size();
// etc.
Methods
Instance methods
-
all
Enumerable#all([iterator = Prototype.K[, context]]) -> BooleanDetermines whether all the elements are boolean-equivalent to
true, either directly or through computation by the provided iterator.Aliased as:
Enumerable#every -
any
Enumerable#any([iterator = Prototype.K[, context]]) -> BooleanDetermines whether at least one element is boolean-equivalent to
true, either directly or through computation by the provided iterator.Aliased as:
Enumerable#some -
collect
Enumerable#collect([iterator = Prototype.K[, context]]) -> ArrayReturns the results of applying the iterator to each element. Aliased as
Enumerable#map.Aliased as:
Enumerable#map -
detect
Enumerable#detect(iterator[, context]) -> firstElement | undefinedFinds the first element for which the iterator returns a “truthy” value. Aliased by the
Enumerable#findmethod.Aliased as:
Enumerable#find -
each
Enumerable#each(iterator[, context]) -> Enumerable-
iterator(Function) – AFunctionthat expects an item in the collection as the first argument and a numerical index as the second. -
context(Object) – The scope in which to calliterator. Affects what the keywordthismeans insideiterator.
Calls
iteratorfor each item in the collection. -
-
eachSlice
Enumerable#eachSlice(number[, iterator = Prototype.K[, context]]) -> EnumerableGroups items into chunks of the given size. The final "slice" may have fewer than
numberitems; it won't "pad" the last group with empty values. For that behavior, useEnumerable#inGroupsOf. -
entries
Enumerable#entries() -> ArrayAlias of:
Enumerable#toArray -
every
Enumerable#every([iterator = Prototype.K[, context]]) -> BooleanAlias of:
Enumerable#all -
filter
Enumerable#filter(iterator[, context]) -> ArrayAlias of:
Enumerable#findAll -
find
Enumerable#find(iterator[, context]) -> firstElement | undefinedAlias of:
Enumerable#detect -
findAll
Enumerable#findAll(iterator[, context]) -> ArrayReturns all the elements for which the iterator returned “truthy” value. Aliased as
Enumerable#select.Aliased as:
Enumerable#select,Enumerable#filter -
grep
Enumerable#grep(regex[, iterator = Prototype.K[, context]]) -> ArrayReturns all the elements that match the filter. If an iterator is provided, it is used to produce the returned value for each selected element.
-
inGroupsOf
Enumerable#inGroupsOf(size[, filler = null]) -> [group...]Groups items in fixed-size chunks, using a specific value to fill up the last chunk if necessary.
-
include
Enumerable#include(object) -> BooleanDetermines whether a given object is in the Enumerable or not, based on the
==comparison operator. Aliased asEnumerable#member.Aliased as:
Enumerable#member -
inject
Enumerable#inject(accumulator, iterator[, context]) -> accumulatedValueIncrementally builds a result value based on the successive results of the iterator. This can be used for array construction, numerical sums/averages, etc.
-
inspect
Enumerable#inspect() -> StringReturns the debug-oriented string representation of the object.
-
invoke
Enumerable#invoke(methodName[, arg...]) -> ArrayInvokes the same method, with the same arguments, for all items in a collection. Returns the results of the method calls.
-
map
Enumerable#map([iterator = Prototype.K[, context]]) -> ArrayAlias of:
Enumerable#collect -
max
Enumerable#max([iterator = Prototype.K[, context]]) -> maxValueReturns the maximum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values.
-
member
Enumerable#member(object) -> BooleanAlias of:
Enumerable#include -
min
Enumerable#min([iterator = Prototype.K[, context]]) -> minValueReturns the minimum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values.
-
partition
Enumerable#partition([iterator = Prototype.K[, context]]) -> [TrueArray, FalseArray]Partitions the elements in two groups: those regarded as true, and those considered false. By default, regular JavaScript boolean equivalence is used, but an iterator can be provided, that computes a boolean representation of the elements.
-
pluck
Enumerable#pluck(propertyName) -> ArrayOptimization for a common use-case of collect: fetching the same property for all the elements. Returns the property values.
-
reject
Enumerable#reject(iterator[, context]) -> ArrayReturns all the elements for which the iterator returned a “falsy” value.
-
select
Enumerable#select(iterator[, context]) -> ArrayAlias of:
Enumerable#findAll -
size
Enumerable#size() -> NumberReturns the size of the enumeration.
-
some
Enumerable#some([iterator = Prototype.K[, context]]) -> BooleanAlias of:
Enumerable#any -
sortBy
Enumerable#sortBy(iterator[, context]) -> ArrayProvides a custom-sorted view of the elements based on the criteria computed, for each element, by the iterator.
-
toArray
Enumerable#toArray() -> ArrayReturns an Array representation of the enumeration.
Aliased as:
Enumerable#entries -
zip
Enumerable#zip(sequence...[, iterator = Prototype.K]) -> ArrayZips together (think of the zip on a pair of trousers) 2+ sequences, providing an array of tuples. Each tuple contains one value per original sequence. Tuples can be converted to something else by applying the optional iterator on them.
