Skip to content

Commit

Permalink
feat: * rule returns all matches (#7)
Browse files Browse the repository at this point in the history
BREAKING CHANGE:

Instead of * rule returning the first, it now returns all the matches in a flattened array.
  • Loading branch information
remy authored Feb 12, 2017
1 parent 9c7867e commit 2d38e72
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
23 changes: 16 additions & 7 deletions lib/undefsafe.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

function undefsafe(obj, path, value) {
function undefsafe(obj, path, value, __res) {

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

for (prop in parent) {
var shallowObj = undefsafe(obj[prop], parts.slice(i + 1).join('.'), value);
if (shallowObj) {
if ((value && shallowObj === value) || (!value)) {
return shallowObj;
var shallowObj = undefsafe(obj[prop], parts.slice(i + 1).join('.'), value, res);
if (shallowObj && shallowObj !== res) {
if ((value && shallowObj === value) || (value === undefined)) {
if (value !== undefined) {
return shallowObj;
}

res.push(shallowObj);
}
}
}
return undefined;
key = prop;

if (res.length === 0) {
return undefined;
}

return res;
}

obj = obj[key];
Expand Down
20 changes: 17 additions & 3 deletions test/star-rule.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,23 @@ var fixture = {
]
};

test('2.0.0: match all.*', function (t) {
var res = undefsafe(fixture, '*.*.*.1');
t.deepEqual(res, ['two', 'four']);
t.end();
});


test('2.0.0: match all.*', function (t) {
var res = undefsafe(fixture, 'commits.*.modified.*.b');
t.deepEqual(res, ['one', 'two', 'two', 'four']);
t.end();
});


test('get value on first * selector', function (t) {
var res = undefsafe(fixture, 'commits.*.modified.*');
t.equal(res, 'one');
var res = undefsafe(fixture, 'commits.*.modified.0');
t.deepEqual(res, ['one', 'two']);
t.end();
});

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

test('match * selector works on objects', function (t) {
var res = undefsafe(fixture, '*.*.modified.*');
var res = undefsafe(fixture, '*.*.modified.*', 'one');
t.equal(res, 'one');
t.end();
});

0 comments on commit 2d38e72

Please sign in to comment.