Skip to content

Commit

Permalink
refactor: Object keys with dots
Browse files Browse the repository at this point in the history
  • Loading branch information
mradionov committed Jan 29, 2017
1 parent 4b107dc commit bda751f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
8 changes: 7 additions & 1 deletion src/traverse.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,15 @@ function noop() {
return function () {};
}

function pathStartsWith(path, subpath) {
return subpath.every(function (key, index) {
return path[index] === key;
});
}

function isSkipped(path, skippedPaths) {
return skippedPaths.some(function (skippedPath) {
return path.indexOf(skippedPath) === 0;
return pathStartsWith(path, skippedPath);
});
}

Expand Down
15 changes: 7 additions & 8 deletions src/value.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,36 +48,35 @@ Value.prototype.removeParent = function () {
};

Value.prototype.getPath = function () {
var path = this.key;
var path = [this.key];
var parent = this.parent;
while (parent && parent.key) {
path = parent.key + '.' + path;
path.unshift(parent.key);
parent = parent.parent;
}
return path;
};

Value.prototype.getParentPath = function () {
var path = this.getPath();
var parts = path.split('.');
var parentPath = parts.slice(0, parts.length - 1).join('.');
var parentPath = path.slice(0, path.length - 1);
return parentPath;
};

Value.prototype.byPath = function (path) {
if (path === '') {
// Root has empty key
if (!path.length || path[0] === '') {
return this;
}

if (!this.isComplex()) {
return null;
}

var parts = path.split('.');
var result = this;

for (var i = 0; i < parts.length; i++) {
var key = parts[i];
for (var i = 0; i < path.length; i++) {
var key = path[i];
var found = collectionUtils.findBy(result.children, 'key', key);
if (!found) {
return null;
Expand Down
18 changes: 18 additions & 0 deletions test/matcher-to-equal/object.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,21 @@ test('nested object vs different type',
'Expected Object({ foo: <a>Object({ bar: 42 })</a> }) ' +
'to equal Object({ foo: <e>true</e> }).'
);

test('keys with dots same',

'Expected Object({ foo.bar: 42, qux: 43 }) ' +
'to equal Object({ foo.bar: 42, qux: 44 }).',

'Expected Object({ foo.bar: 42, qux: <a>43</a> }) ' +
'to equal Object({ foo.bar: 42, qux: <e>44</e> }).'
);

test('keys with dots different',

'Expected Object({ foo.bar: 42, foo: 43 }) ' +
'to equal Object({ foo.baz: 42, foo: 44 }).',

'Expected Object({ <a>foo.bar: 42</a>, foo: <a>43</a> }) ' +
'to equal Object({ <e>foo.baz: 42</e>, foo: <e>44</e> }).'
);

0 comments on commit bda751f

Please sign in to comment.