Skip to content

Commit 2d38e72

Browse files
authored
feat: * rule returns all matches (#7)
BREAKING CHANGE: Instead of * rule returning the first, it now returns all the matches in a flattened array.
1 parent 9c7867e commit 2d38e72

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

lib/undefsafe.js

+16-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
function undefsafe(obj, path, value) {
3+
function undefsafe(obj, path, value, __res) {
44

55
// I'm not super keen on this private function, but it's because
66
// it'll also be use in the browser and I wont *one* function exposed
@@ -64,17 +64,26 @@ function undefsafe(obj, path, value) {
6464
if (key === '*') {
6565
// loop through each property
6666
var prop = '';
67+
var res = __res || [];
6768

6869
for (prop in parent) {
69-
var shallowObj = undefsafe(obj[prop], parts.slice(i + 1).join('.'), value);
70-
if (shallowObj) {
71-
if ((value && shallowObj === value) || (!value)) {
72-
return shallowObj;
70+
var shallowObj = undefsafe(obj[prop], parts.slice(i + 1).join('.'), value, res);
71+
if (shallowObj && shallowObj !== res) {
72+
if ((value && shallowObj === value) || (value === undefined)) {
73+
if (value !== undefined) {
74+
return shallowObj;
75+
}
76+
77+
res.push(shallowObj);
7378
}
7479
}
7580
}
76-
return undefined;
77-
key = prop;
81+
82+
if (res.length === 0) {
83+
return undefined;
84+
}
85+
86+
return res;
7887
}
7988

8089
obj = obj[key];

test/star-rule.test.js

+17-3
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,23 @@ var fixture = {
1818
]
1919
};
2020

21+
test('2.0.0: match all.*', function (t) {
22+
var res = undefsafe(fixture, '*.*.*.1');
23+
t.deepEqual(res, ['two', 'four']);
24+
t.end();
25+
});
26+
27+
28+
test('2.0.0: match all.*', function (t) {
29+
var res = undefsafe(fixture, 'commits.*.modified.*.b');
30+
t.deepEqual(res, ['one', 'two', 'two', 'four']);
31+
t.end();
32+
});
33+
34+
2135
test('get value on first * selector', function (t) {
22-
var res = undefsafe(fixture, 'commits.*.modified.*');
23-
t.equal(res, 'one');
36+
var res = undefsafe(fixture, 'commits.*.modified.0');
37+
t.deepEqual(res, ['one', 'two']);
2438
t.end();
2539
});
2640

@@ -44,7 +58,7 @@ test('match * selector returns undefined', function (t) {
4458
});
4559

4660
test('match * selector works on objects', function (t) {
47-
var res = undefsafe(fixture, '*.*.modified.*');
61+
var res = undefsafe(fixture, '*.*.modified.*', 'one');
4862
t.equal(res, 'one');
4963
t.end();
5064
});

0 commit comments

Comments
 (0)