-
Notifications
You must be signed in to change notification settings - Fork 640
/
Copy patharray.js
483 lines (453 loc) · 15.7 KB
/
array.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/** section: Language, related to: Array
* $A(iterable) -> Array
*
* Accepts an array-like collection (anything with numeric indices) and returns
* its equivalent as an actual [[Array]] object. This method is a convenience
* alias of [[Array.from]], but is the preferred way of casting to an [[Array]].
*
* The primary use of [[$A]] is to obtain an actual [[Array]] object based on
* anything that could pass as an array (e.g. the `NodeList` or
* `HTMLCollection` objects returned by numerous DOM methods, or the predefined
* `arguments` reference within your functions).
*
* The reason you would want an actual [[Array]] is simple:
* [[Array Prototype extends Array]] to equip it with numerous extra methods,
* and also mixes in the [[Enumerable]] module, which brings in another
* boatload of nifty methods. Therefore, in Prototype, actual [[Array]]s trump
* any other collection type you might otherwise get.
*
* The conversion performed is rather simple: `null`, `undefined` and `false` become
* an empty array; any object featuring an explicit `toArray` method (as many Prototype
* objects do) has it invoked; otherwise, we assume the argument "looks like an array"
* (e.g. features a `length` property and the `[]` operator), and iterate over its components
* in the usual way.
*
* When passed an array, [[$A]] _makes a copy_ of that array and returns it.
*
* ##### Examples
*
* The well-known DOM method [`document.getElementsByTagName()`](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094)
* doesn't return an [[Array]], but a `NodeList` object that implements the basic array
* "interface.":
*
* var paras = $A(document.getElementsByTagName('p'));
* paras.each(Element.hide);
* $(paras.last()).show();
*
* Notice we had to use [[Enumerable#each each]] and [[Element.hide]] because
* [[$A]] doesn't perform DOM extensions, since the array could contain
* anything (not just DOM elements). To use the [[Element#hide]] instance
* method we first must make sure all the target elements are extended:
*
* $A(document.getElementsByTagName('p')).map(Element.extend).invoke('hide');
*
* Want to display your arguments easily? [[Array]] features a `join` method, but the `arguments`
* value that exists in all functions *does not* inherit from [[Array]]. So, the tough
* way, or the easy way?
*
* // The hard way...
* function showArgs() {
* alert(Array.prototype.join.call(arguments, ', '));
* }
*
* // The easy way...
* function showArgs() {
* alert($A(arguments).join(', '));
* }
**/
function $A(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
/** section: Language, related to: Array
* $w(String) -> Array
*
* Splits a string into an [[Array]], treating all whitespace as delimiters. Equivalent
* to Ruby's `%w{foo bar}` or Perl's `qw(foo bar)`.
*
* This is one of those life-savers for people who just hate commas in literal arrays :-)
*
* ### Examples
*
* $w('apples bananas kiwis')
* // -> ['apples', 'bananas', 'kiwis']
*
* This can slightly shorten code when writing simple iterations:
*
* $w('apples bananas kiwis').each(function(fruit){
* var message = 'I like ' + fruit
* // do something with the message
* })
*
* This also becomes sweet when combined with [[Element]] functions:
*
* $w('ads navbar funkyLinks').each(Element.hide);
**/
function $w(string) {
if (!Object.isString(string)) return [];
string = string.strip();
return string ? string.split(/\s+/) : [];
}
/** alias of: $A
* Array.from(iterable) -> Array
**/
Array.from = $A;
/** section: Language
* class Array
* includes Enumerable
*
* Prototype extends all native JavaScript arrays with quite a few powerful
* methods.
*
* This is done in two ways:
*
* * It mixes in the [[Enumerable]] module, which brings in a ton of methods.
* * It adds quite a few extra methods, which are documented in this section.
*
* With Prototype, arrays become much, much more than the trivial objects we
* used to manipulate, limiting ourselves to using their `length` property and
* their `[]` indexing operator. They become very powerful objects that
* greatly simplify the code for 99% of the common use cases involving them.
*
* ##### Why you should stop using for...in to iterate
*
* Many JavaScript authors have been misled into using the `for...in` JavaScript
* construct to loop over array elements. This kind of code just won't work
* with Prototype.
*
* The ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly
* implemented by all major browsers including MSIE, defines ten methods
* on [[Array]] (§15.4.4), including nice methods like `concat`, `join`,
* `pop`, and `push`.
*
* This same standard explicitly defines that the `for...in` construct (§12.6.4)
* exists to enumerate the properties of the object appearing on the right side
* of the `in` keyword. Only properties specifically marked as _non-enumerable_
* are ignored by such a loop. By default, the `prototype` and `length`
* properties are so marked, which prevents you from enumerating over array
* methods when using for...in. This comfort led developers to use `for...in` as a
* shortcut for indexing loops, when it is not its actual purpose.
*
* However, Prototype has no way to mark the methods it adds to
* `Array.prototype` as non-enumerable. Therefore, using `for...in` on arrays
* when using Prototype will enumerate all extended methods as well, such as
* those coming from the [[Enumerable]] module, and those Prototype puts in the
* [[Array]] namespace (listed further below).
*
* ##### What you should use instead
*
* You can revert to vanilla loops:
*
* for (var index = 0; index < myArray.length; ++index) {
* var item = myArray[index];
* // Your code working on item here...
* }
*
* Or you can use iterators, such as [[Array#each]]:
*
* myArray.each(function(item) {
* // Your code working on item here...
* });
*
* The inability to use `for...in` on arrays is not much of a burden: as you'll
* see, most of what you used to loop over arrays for can be concisely done
* using the new methods provided by Array or the mixed-in [[Enumerable]]
* module. So manual loops should be fairly rare.
*
* ##### A note on performance
*
* Should you have a very large array, using iterators with lexical closures
* (anonymous functions that you pass to the iterators and that get invoked at
* every loop iteration) in methods like [[Array#each]] — _or_ relying on
* repetitive array construction (such as uniq), may yield unsatisfactory
* performance. In such cases, you're better off writing manual indexing loops,
* but take care then to cache the length property and use the prefix `++`
* operator:
*
* // Custom loop with cached length property: maximum full-loop
* // performance on very large arrays!
* for (var index = 0, len = myArray.length; index < len; ++index) {
* var item = myArray[index];
* // Your code working on item here...
* }
*
**/
(function() {
var arrayProto = Array.prototype,
slice = arrayProto.slice,
_each = arrayProto.forEach; // use native browser JS 1.6 implementation if available
// Note that #map, #filter, #some, and #every take some extra steps for
// ES5 compliance: the context in which they're called is coerced to an
// object, and that object's `length` property is coerced to a finite
// integer. This makes it easier to use the methods as generics.
//
// This means that they behave a little differently from other methods in
// `Enumerable`/`Array` that don't collide with ES5, but that's OK.
var filter = arrayProto.filter,
map = wrapNative(arrayProto.map),
some = wrapNative(arrayProto.some),
every = wrapNative(arrayProto.every);
/**
* Array#clear() -> Array
*
* Clears the array (makes it empty) and returns the array reference.
*
* ##### Example
*
* var guys = ['Sam', 'Justin', 'Andrew', 'Dan'];
* guys.clear();
* // -> []
* guys
* // -> []
**/
function clear() {
this.length = 0;
return this;
}
/**
* Array#first() -> ?
*
* Returns the array's first item (e.g., `array[0]`).
**/
function first() {
return this[0];
}
/**
* Array#last() -> ?
*
* Returns the array's last item (e.g., `array[array.length - 1]`).
**/
function last() {
return this[this.length - 1];
}
/**
* Array#compact() -> Array
*
* Returns a **copy** of the array without any `null` or `undefined` values.
*
* ##### Example
*
* var orig = [undefined, 'A', undefined, 'B', null, 'C'];
* var copy = orig.compact();
* // orig -> [undefined, 'A', undefined, 'B', null, 'C'];
* // copy -> ['A', 'B', 'C'];
**/
function compact() {
return this.select(function(value) {
return value != null;
});
}
/**
* Array#flatten() -> Array
*
* Returns a flattened (one-dimensional) copy of the array, leaving
* the original array unchanged.
*
* Nested arrays are recursively injected inline. This can prove very
* useful when handling the results of a recursive collection algorithm,
* for instance.
*
* ##### Example
*
* var a = ['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]];
* var b = a.flatten();
* // a -> ['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]]
* // b -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']
**/
function flatten() {
return this.inject([], function(array, value) {
if (Object.isArray(value))
return array.concat(value.flatten());
array.push(value);
return array;
});
}
/**
* Array#without(value[, value...]) -> Array
* - value (?): A value to exclude.
*
* Produces a new version of the array that does not contain any of the
* specified values, leaving the original array unchanged.
*
* ##### Examples
*
* [3, 5, 6].without(3)
* // -> [5, 6]
*
* [3, 5, 6, 20].without(20, 6)
* // -> [3, 5]
**/
function without() {
var values = slice.call(arguments, 0);
return this.select(function(value) {
return !values.include(value);
});
}
/**
* Array#reverse([inline = true]) -> Array
* - inline (Boolean): Whether to modify the array in place. Defaults to `true`.
* Clones the original array when `false`.
*
* Reverses the array's contents, optionally cloning it first.
*
* ##### Examples
*
* // Making a copy
* var nums = [3, 5, 6, 1, 20];
* var rev = nums.reverse(false);
* // nums -> [3, 5, 6, 1, 20]
* // rev -> [20, 1, 6, 5, 3]
*
* // Working inline
* var nums = [3, 5, 6, 1, 20];
* nums.reverse();
* // nums -> [20, 1, 6, 5, 3]
**/
function reverse(inline) {
return (inline === false ? this.toArray() : this)._reverse();
}
/**
* Array#uniq([sorted = false]) -> Array
* - sorted (Boolean): Whether the array has already been sorted. If `true`,
* a less-costly algorithm will be used.
*
* Produces a duplicate-free version of an array. If no duplicates are
* found, the original array is returned.
*
* On large arrays when `sorted` is `false`, this method has a potentially
* large performance cost.
*
* ##### Examples
*
* [1, 3, 2, 1].uniq();
* // -> [1, 2, 3]
*
* ['A', 'a'].uniq();
* // -> ['A', 'a'] (because String comparison is case-sensitive)
**/
function uniq(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
}
/**
* Array#intersect(array) -> Array
* - array (Array): A collection of values.
*
* Returns an array containing every item that is shared between the two
* given arrays.
**/
function intersect(array) {
return this.uniq().findAll(function(item) {
return array.indexOf(item) !== -1;
});
}
/** alias of: Array#clone
* Array#toArray() -> Array
**/
/**
* Array#clone() -> Array
*
* Returns a duplicate of the array, leaving the original array intact.
**/
function clone() {
return slice.call(this, 0);
}
/** related to: Enumerable#size
* Array#size() -> Number
*
* Returns the size of the array (e.g., `array.length`).
*
* This is just a local optimization of the mixed-in [[Enumerable#size]]
* which avoids array cloning and uses the array's native length property.
**/
function size() {
return this.length;
}
/** related to: Object.inspect
* Array#inspect() -> String
*
* Returns the debug-oriented string representation of an array.
*
* ##### Example
*
* ['Apples', {good: 'yes', bad: 'no'}, 3, 34].inspect()
* // -> "['Apples', [object Object], 3, 34]"
**/
function inspect() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
// Certain ES5 array methods have the same names as Prototype array methods
// and perform the same functions.
//
// Prototype's implementations of these methods differ from the ES5 spec in
// the way a missing iterator function is handled. Prototype uses
// `Prototype.K` as a default iterator, while ES5 specifies that a
// `TypeError` must be thrown. Implementing the ES5 spec completely would
// break backward compatibility and would force users to pass `Prototype.K`
// manually.
//
// Instead, if native versions of these methods exist, we wrap the existing
// methods with our own behavior. This has very little performance impact.
// It violates the spec by suppressing `TypeError`s for certain methods,
// but that's an acceptable trade-off.
function wrapNative(method) {
return function() {
if (arguments.length === 0) {
// No iterator was given. Instead of throwing a `TypeError`, use
// `Prototype.K` as the default iterator.
return method.call(this, Prototype.K);
} else if (arguments[0] === undefined) {
// Same as above.
var args = slice.call(arguments, 1);
args.unshift(Prototype.K);
return method.apply(this, args);
} else {
// Pass straight through to the native method.
return method.apply(this, arguments);
}
};
}
// We used to define an `inject` method here that relied on ES5's
// `Array#reduce` (if present), but using `reduce` prevents us from
// catching a thrown `$break`. So arrays now use the standard
// `Enumerable.inject` like they did previously.
Object.extend(arrayProto, Enumerable);
// Enumerable's `entries` method is no longer safe to mixin to arrays, as
// it conflicts with an ES6 method. But it can still be mixed into other
// things.
if (arrayProto.entries === Enumerable.entries) {
delete arrayProto.entries;
}
if (!arrayProto._reverse)
arrayProto._reverse = arrayProto.reverse;
Object.extend(arrayProto, {
_each: _each,
map: map,
collect: map,
select: filter,
findAll: filter,
some: some,
any: some,
every: every,
all: every,
clear: clear,
first: first,
last: last,
compact: compact,
flatten: flatten,
without: without,
reverse: reverse,
uniq: uniq,
intersect: intersect,
clone: clone,
toArray: clone,
size: size,
inspect: inspect
});
})();