lang_array.js
2.04 KB
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
(function() {
var slice = Array.prototype.slice;
/**
* Invokes method on all items in a given array
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} method Name of a method to invoke
* @return {Array}
*/
function invoke(array, method) {
var args = slice.call(arguments, 2), result = [];
for (var i = 0, len = array.length; i < len; i++) {
result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
}
return result;
}
/**
* Finds maximum value in array (not necessarily "first" one)
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} byProperty
* @return {*}
*/
function max(array, byProperty) {
return find(array, byProperty, function(value1, value2) {
return value1 >= value2;
});
}
/**
* Finds minimum value in array (not necessarily "first" one)
* @memberOf fabric.util.array
* @param {Array} array Array to iterate over
* @param {String} byProperty
* @return {*}
*/
function min(array, byProperty) {
return find(array, byProperty, function(value1, value2) {
return value1 < value2;
});
}
/**
* @private
*/
function fill(array, value) {
var k = array.length;
while (k--) {
array[k] = value;
}
return array;
}
/**
* @private
*/
function find(array, byProperty, condition) {
if (!array || array.length === 0) {
return;
}
var i = array.length - 1,
result = byProperty ? array[i][byProperty] : array[i];
if (byProperty) {
while (i--) {
if (condition(array[i][byProperty], result)) {
result = array[i][byProperty];
}
}
}
else {
while (i--) {
if (condition(array[i], result)) {
result = array[i];
}
}
}
return result;
}
/**
* @namespace fabric.util.array
*/
fabric.util.array = {
fill: fill,
invoke: invoke,
min: min,
max: max
};
})();