Skip to content

Commit 5cf9741

Browse files
committed
Fix for array_search() and new ability to pass in regexp; not like PHP, but won't interfere with PHP
1 parent 4fe42cd commit 5cf9741

2 files changed

Lines changed: 37 additions & 4 deletions

File tree

functions/array/array.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,24 @@ function array () {
120120
};
121121
// Return non-object, non-array values, since most sensible
122122
e.search = function (needle, argStrict) {var _ = __.method(this);
123-
var strict = !!argStrict;
124-
for (var i=0, vl = _.values.length; i < vl; i++) {
125-
var val = _.values[i];
123+
var strict = !!argStrict, haystack = _.values, i, vl, val;
124+
if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp
125+
if (!strict) { // Let's consider case sensitive searches as strict
126+
var flags = 'i' + (needle.global ? 'g' : '') +
127+
(needle.multiline ? 'm' : '') +
128+
(needle.sticky ? 'y' : ''); // sticky is FF only
129+
needle = new RegExp(needle.source, flags);
130+
}
131+
for (i=0, vl = haystack.length; i < vl; i++) {
132+
val = haystack[i];
133+
if (needle.test(val)) {
134+
return _.keys[i];
135+
}
136+
}
137+
return false;
138+
}
139+
for (i=0, vl = haystack.length; i < vl; i++) {
140+
val = haystack[i];
126141
if ((strict && val === needle) || (!strict && val == needle)) {
127142
return _.keys[i];
128143
}

functions/array/array_search.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,30 @@ function array_search (needle, haystack, argStrict) {
55
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
66
// * example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
77
// * returns 1: 'surname'
8+
// * example 2: ini_set('phpjs.return_phpjs_arrays', 'on');
9+
// * example 2: var ordered_arr = array({3:'value'}, {2:'value'}, {'a':'value'}, {'b':'value'});
10+
// * example 2: var key = array_search(/val/g, ordered_arr); // or var key = ordered_arr.search(/val/g);
11+
// * returns 2: '3'
812

913
var strict = !!argStrict,
1014
key = '';
1115

1216
if (haystack && typeof haystack === 'object' && haystack.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
13-
return haystack.search(needle, haystack, argStrict);
17+
return haystack.search(needle, argStrict);
18+
}
19+
if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp
20+
if (!strict) { // Let's consider case sensitive searches as strict
21+
var flags = 'i' + (needle.global ? 'g' : '') +
22+
(needle.multiline ? 'm' : '') +
23+
(needle.sticky ? 'y' : ''); // sticky is FF only
24+
needle = new RegExp(needle.source, flags);
25+
}
26+
for (key in haystack) {
27+
if (needle.test(haystack[key])) {
28+
return key;
29+
}
30+
}
31+
return false;
1432
}
1533

1634
for (key in haystack) {

0 commit comments

Comments
 (0)