Prototype Enumerable Object Learning 1th/2 page _prototype

Source: Internet
Author: User
Tags abstract arrays extend hash

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

Enumerable is what we are module:a consistent set of methods intended not for independent with but for Mixin: Incorporation into the other objects that ' fit ' with it.

Quite a few objects, in Prototype, mixes enumerable in already. The most visible cases are Array and Hash, but you'll find it in less obvious spots as very, such as in Objectrange and VA Rious dom-or ajax-related objects.

The meaning of this short remark is probably to say that enumerable is the cornerstone of the prototype framework, and enumerable not used alone, the other objects in prototype mix enumerable inside the method, This allows you to apply enumerable methods on these objects, such as Array,hash,objectrange, and some dom,ajax-related objects.
Personal understanding enumerable is equivalent to the concept of abstract classes in C + +, and other classes can inherit from this class and implement the abstract method "_each" within enumerable, and can override other methods, and enumerable itself cannot be instantiated, Only subclasses of it can be instantiated.
Let's look at how to write your own class by enumerable:

Copy Code code as follows:

var yourobject = Class.create ();
Object.extend (Yourobject.prototype, enumerable); Object.extend (Yourobject.prototype, {
Initialize:function () {
With whatever constructor arguments for you need
Your Construction Code
},
_each:function (iterator) {
Your iteration code, invoking iterator at every turn
},
Your other methods here, including Enumerable overrides
});

It can be seen that the most important thing is to implement the _each method, the Initialize method is equivalent to the constructor, if you do not need to pass in any parameters, can be omitted completely. Below I wrote a random number of arrays of classes, very simple, there are many imperfect places, here only to do demo:
Copy Code code as follows:

Create Randomarray Class
var Randomarray = Class.create ();
Mixin Enumerable
Object.extend (Randomarray.prototype, enumerable);
Implementing _each and the required methods
Object.extend (Randomarray.prototype, {
Initialize:function (Min,max,count) {
This.min=min;
This.max=max;
This.count=count;
This._numbers=[];
This._createrandomarray ();
},
_each:function (iterator) {
var Index=this.count;
while (index-->0) {
Iterator (This._numbers[index]);
}
},
Generating an array of random numbers
_createrandomarray:function () {
var index=0;
while (Index<this.count) {
var random=math.round (Math.random () * (this.max-this.min) +this.min);
if (This.include (random)) {
Continue
}
This._numbers[index++]=random;
}
},
Include:function (number) {
return This._numbers.indexof (number)!=-1;
}
});

var obj = new Randomarray (4,19,5);
Alert (Obj.size ());
Alert (Obj.entries ());

Take a look at enumerable's source code, and then learn each of these methods in detail:
Copy Code code as follows:

var $break = {};

var enumerable = (function () {
Traverse each data
function each (iterator, context) {
var index = 0;
try {
This._each (function (value) {
Iterator.call (context, value, index++);
});
catch (e) {
if (e!= $break) throw e;
}
return this;
}

Divide the data into n groups, where each group has number, and the last group may be less than number
function Eachslice (number, iterator, context) {
var index =-number, slices = [], array = This.toarray ();
if (number < 1) return array;
while (index + = number) < Array.Length)
Slices.push (Array.slice (index, index+number));
Return Slices.collect (iterator, context);
}

Test whether all data satisfies a condition
function All (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var result = true;
This.each (function (value, index) {
result = Result &&!! Iterator.call (context, value, index);
if (!result) throw $break;
});
return result;
}

Check if any one of the data satisfies a condition
function any (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var result = false;
This.each (function (value, index) {
if (result =!!) Iterator.call (context, value, index))
Throw $break;
});
return result;
}

You can do anything with all the data and return an array of results
function collect (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var results = [];
This.each (function (value, index) {
Results.push (Iterator.call (context, value, index));
});
return results;
}

Finds the first data that satisfies a condition, and returns an alias equivalent to the Find method
function detect (iterator, context) {
var result;
This.each (function (value, index) {
if (Iterator.call (context, value, index)) {
result = value;
Throw $break;
}
});
return result;
}

Finds all data that satisfies a condition and returns the result
function FindAll (iterator, context) {
var results = [];
This.each (function (value, index) {
if (Iterator.call (context, value, index))
Results.push (value);
});
return results;
}

Filter all data according to filter conditions, find the data that satisfies the filter condition, and return the result
Filter is a string or regular expression
function grep (filter, iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var results = [];

if (object.isstring (filter))
Filter = new RegExp (Regexp.escape (filter));

This.each (function (value, index) {
if (Filter.match (value))
Results.push (Iterator.call (context, value, index));
});
return results;
}

Check to see if a data is included
function include (object) {
if (Object.isfunction (This.indexof))
if (This.indexof (object)!=-1) return true;

var found = false;
This.each (function (value) {
if (value = = object) {
Found = true;
Throw $break;
}
});
return found;
}

Similar to the Eachslice method, if the last set of elements is less than number, fill with the Fillwith parameter
function ingroupsof (number, fillwith) {
Fillwith = object.isundefined (fillwith)? Null:fillwith;
Return This.eachslice (number, function (slice) {
while (Slice.length < number) Slice.push (fillwith);
return slice;
});
}

Continuous operation of all data to achieve cumulative or tiring operation
function inject (memo, iterator, context) {
This.each (function (value, index) {
Memo = Iterator.call (context, Memo, value, index);
});
return memo;
}

To execute a method on all data
function Invoke (method) {
var args = $A (arguments). Slice (1);
Return This.map (function (value) {
return value[method].apply (value, args);
});
}

Find the maximum value in the data
function Max (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var result;
This.each (function (value, index) {
Value = Iterator.call (context, value, index);
if (result = = NULL | | Value >= result)
result = value;
});
return result;
}

Find the minimum value in the data
function min (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var result;
This.each (function (value, index) {
Value = Iterator.call (context, value, index);
if (result = = NULL | | Value < result)
result = value;
});
return result;
}

Divide all the data into two, the first group is the data that satisfies a condition, and the second group is the data that does not meet the condition
function partition (iterator, context) {
iterator = Iterator | | PROTOTYPE.K;
var trues = [], falses = [];
This.each (function (value, index) {
(Iterator.call (context, value, index)?
trues:falses). push (value);
});
return [Trues, falses];
}

Remove the value of the property of all data and return the result
Function Pluck (property) {
var results = [];
This.each (function (value) {
Results.push (Value[property]);
});
return results;
}

Find data that does not meet a condition
function reject (iterator, context) {
var results = [];
This.each (function (value, index) {
if (!iterator.call (context, value, index))
Results.push (value);
});
return results;
}

Sort all data according to a condition
function SortBy (iterator, context) {
Return This.map (function (value, index) {
return {
Value:value,
Criteria:iterator.call (context, value, index)
};
}. Sort (function (left, right) {
var a = Left.criteria, B = Right.criteria;
Return a < b? -1:a > B? 1:0;
}). Pluck (' value ');
}

Returns an array representation of the data
function ToArray () {
return This.map ();
}

The basic thing is to put two sets of data together for some action
function Zip () {
var iterator = prototype.k, args = $A (arguments);
if (Object.isfunction (Args.last ()))
iterator = Args.pop ();

var collections = [This].concat (args). Map ($A);
Return This.map (function (value, index) {
Return iterator (Collections.pluck (index));
});
}

function size () {
Return This.toarray (). length;
}

Returns a string representation of a enumerable object
function Inspect () {
Return ' #<enumerable: ' + this.toarray (). Inspect () + ' > ';
}

return {
Each:each,
Eachslice:eachslice,
All:all,
Every:all,
Any:any,
Some:any,
Collect:collect,
Map:collect,
Detect:detect,
Findall:findall,
Select:findall,
Filter:findall,
Grep:grep,
Include:include,
Member:include,
Ingroupsof:ingroupsof,
Inject:inject,
Invoke:invoke,
Max:max,
Min:min,
Partition:partition,
Pluck:pluck,
Reject:reject,
Sortby:sortby,
Toarray:toarray,
Entries:toarray,
Zip:zip,
Size:size,
Inspect:inspect,
Find:detect
};
})();

Here's how to learn enumerable:

All
Any
Collect
Detect
each
Eachslice
Entries
Find
FindAll
Grep
Ingroupsof
Include
Inject
Invoke
Map
Max
Member
Min
Partition
Pluck
Reject
Select
Size
SortBy
ToArray
Zip
All method:

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

Basically, you call each method to check whether each data satisfies the iterator condition, and one of them throws a $break exception if it is not satisfied, and then the exception is caught in each method. Here, pay attention to '!! ' , you can convert some objects to the corresponding bool values:

!! {} true

!! [] True

!!'' False

!!' String ' True

!! 0 false

Here's a look at the example:

Copy Code code as follows:

[].all ()
-> true (empty arrays have no elements that could to be false-equivalent)

$R (1, 5). All ()
-> true (all values in [1..5] are true-equivalent)

[0, 1, 2].all ()
-> false (with only one loop cycle:0 is false-equivalent)

[9, 15].all (function (n) {return n >= 10;})
-> False (the iterator return false on 9)

$H ({name: ' John ', age:29, Oops:false}). All (function (pair) {return pair.value;})
-> False (the Oops/false pair yields a value of false)

Current 1/2 page 12 Next read the full text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.