Skip to content

Commit

Permalink
Merge branch 'master' of github.com:remy/undefsafe
Browse files Browse the repository at this point in the history
* 'master' of github.com:remy/undefsafe:
  feat: * rule returns all matches (#7)
  • Loading branch information
remy committed Feb 21, 2017
2 parents 9a1631a + 2d38e72 commit 29c8d32
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
@@ -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 @@ -69,17 +69,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
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 29c8d32

Please sign in to comment.