Enumerable

Enumerable provides a large set of useful methods for enumerations, that is, objects that act as collections of values. It is a cornerstone of Prototype.

Enumerable is what we like to call a module: a consistent set of methods intended not for independent use, but for mixin: incorporation into other objects that “fit” with it. This meaning of the term “module” is borrowed from the Ruby world, which is fitting enough, since Enumerable attempts to mimic at least part of its Ruby-world namesake.

Quite a few objects, in Prototype, mix Enumerable in already. 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.

On this page

· | Aliases: It's all about having it your way

· | Using it efficiently

· | Mixing enumerable in your own objects

· | Moduleindex

Aliases: it’s all about having it your way

Just like its Ruby counterpart, Enumerable cares about your comfort enough to provide more than one name for a few behaviors. This is intended to reduce your learning curve when your technical background made you familiar with one name or another. However, the documentation attempts to clearly state when one name is “preferred” over the other (perhaps due to readability, widely accepted intuitiveness, etc.).

Here are the aliases you’ll find in Enumerable:

· | map is the same as collect.

· | find is the preferred way of using detect.

· | findAll is the same as select.

· | include is the same as member.

· | entries is the same as toArray.

Using it efficiently

When using Enumerable, beginners often create sub-par code, performance-wise, by simple lack of familiarity with the API. There are several use cases when one method will be significantly faster (and often make for more readable code!) than another. Here are the two main points about this.

collect, invoke, pluck and each: thinking about the use case

Beginners tend to use each whenever they need to manipulate all elements in the enumeration, and collect whenever they need to yield a value the same way for each element. This is the proper way for the generic case, but there are specific use cases where it can be written way more concisely, more elegantly, and with much better performance.

· | When you need to invoke the same method on all the elements, go with invoke.

· | When you need to fetch the same property on all the elements, go with pluck.

reject and findAll vs. partition

The findAll/select methods retrieve all the elements that match a given predicate. Conversely, the reject method retrieves all the elements that do not match a predicate. In the specific case where you need both sets, you can avoid looping twice: just use partition.

Mixing Enumerable in 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 each, Enumerable provides all the extra layers (handling iteration short-circuits, passing numerical indices, etc.). You just need to implement the actual basic iteration, as fits your internal structure.

If this leaves you goggling, just have a look at Prototype’s Array, Hash or ObjectRange objects’ source code. 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();

Object.extend(YourObject.prototype, Enumerable);

Object.extend(YourObject.prototype, {

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();

// Whatever use here, e.g. to fill it up

obj.pluck('somePropName');

obj.invoke('someMethodName');

obj.size();

// etc.

Moduleindex

all

all([iterator = Prototype.K]) -> Boolean

Determines whether all the elements are boolean-equivalent to true, either directly or through computation by the provided iterator.

any

any([iterator = Prototype.K]) -> Boolean

Determines whether at least one element is boolean-equivalent to true, either directly or through computation by the provided iterator.

collect

collect(iterator) -> Array

Returns the results of applying the iterator to each element. Aliased as map.

detect

detect(iterator) -> firstElement | undefined

Finds the first element for which the iterator returns true. Aliased by the find method, which is considered the more readable way of using it.

each

each(iterator) -> Enumerable

The cornerstone of Enumerable. It lets you iterate over all the elements in a generic fashion, then returns the Enumerable, thereby allowing chain-calling.

entries

entries() -> Array

Alias for the more generic toArray method.

find

find(iterator) -> firstElement | undefined

Finds the first element for which the iterator returns true. Convenience alias for detect, but constitutes the preferred (more readable) syntax.

findAll

findAll(iterator) -> Array

Returns all the elements for which the iterator returned true. Aliased as select.

grep

grep(regex[, iterator = Prototype.K]) -> Array

Returns all the elements whose string representations match the regular expression. If an iterator is provided, it is used to produce the string representation for each selected element.

include

include(object) -> Boolean

Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Aliased as member.

inject

inject(accumulator, iterator) -> accumulatedValue

Incrementally builds a result value based on the successive results of the iterator. This can be used for array construction, numerical sums/averages, etc.

invoke

invoke(methodName[, arg...]) -> Array

Optimization for a common use-case of each or collect: invoking the same method, with the same potential arguments, for all the elements. Returns the results of the method calls.

map

map(iterator) -> Array

Returns the results of applying the iterator to each element. Convenience alias for collect.

max

max([iterator = Prototype.K]) -> maxValue

Returns 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

member(object) -> Boolean

Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Convenience alias for include.

min

min([iterator = Prototype.K]) -> minValue

Returns 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

partition([iterator = Prototype.K]) -> [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

pluck(propertyName) -> Array

Optimization for a common use-case of collect: fetching the same property for all the elements. Returns the property values.

reject

reject(iterator) -> Array

Returns all the elements for which the iterator returned false.

select

select(iterator) -> Array

Alias for the findAll method.

size

size() -> Number

Returns the size of the enumeration.

sortBy

sortBy(iterator) -> Array

Provides a custom-sorted view of the elements based on the criteria computed, for each element, by the iterator.

toArray

toArray() -> Array

Returns an Array representation of the enumeration. Aliased as entries.

zip

zip(Sequence...[, iterator = Prototype.K]) -> Array

Zips 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.

Prototype API 1.5.0 - prototypejs.org