-
Notifications
You must be signed in to change notification settings - Fork 3
/
leta.array.js
113 lines (95 loc) · 3.06 KB
/
leta.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
/**
* leta.array.js
* @require [leta.core]
*/
;(function (Leta, undefined) {
var $A = {};
var arrayProto = Array.prototype,
objectProto = Object.prototype,
slice = arrayProto.slice,
toString = objectProto.toString,
hasOwnProperty = objectProto.hasOwnProperty,
nativeForEach = arrayProto.forEach,
nativeMap = arrayProto.map,
nativeReduce = arrayProto.reduce,
nativeFilter = arrayProto.filter,
nativeEvery = arrayProto.every,
nativeSome = arrayProto.some,
nativeIndexOf = arrayProto.indexOf,
nativeLastIndexOf = arrayProto.lastIndexOf;
$A.each = $A.forEach = function (obj, iterator, context) {
if (Leta.isNull(obj)) {return ;}
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
// array like
for (var i = 0, l = obj.length; i < l; i ++) {
if (iterator.call(context, obj[i], i, obj) === false) {
return ;
}
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === false) {
return ;
}
}
}
}
};
$A.map = function (obj, iterator, context) {
var ret = [];
if (nativeMap && obj.map === nativeMap) {
return obj.map(iterator, context);
}
$A.each(obj, function (value, index, arr) {
ret[ret.length] = iterator.call(context, value, index, arr);
});
return ret;
}
/**
* 判断一个list里面所有元素是否满足某iterator
* @return {Boolean}
*/
$A.every = $A.all = function (obj, iterator, context) {
var ret = true;
if (nativeEvery && obj.every === nativeEvery) {
return obj.every(iterator, context);
}
$A.each(obj, function (value, index, arr) {
if (!iterator.call(context, value, index, arr)) {
return false;
}
})
return ret;
}
/**
* 判断是否存在一个元素满足iterator
*/
$A.some = $A.any = function (obj, iterator, context) {
var ret = false;
if (nativeSome && obj.some === nativeSome) {
return obj.some(iterator, context);
}
$A.each(obj, function (value, index, arr) {
if (ret |= iterator.call(context, value, index, arr)) {
return ret;
}
})
return ret;
}
$A.contains = $A.include = function (obj, target) {
var ret = false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
return (obj.indexOf(target) != -1);
}
$A.any(obj, function (value) {
if (ret = value === target) {
return true;
}
});
return ret;
}
Leta.extend({array: $A});
})(Leta);