From bda751f34eb2b7abdbb37f4db65adbaa8d3a7269 Mon Sep 17 00:00:00 2001 From: Michael Radionov Date: Sun, 29 Jan 2017 15:53:42 +0300 Subject: [PATCH] refactor: Object keys with dots --- src/traverse.js | 8 +++++++- src/value.js | 15 +++++++-------- test/matcher-to-equal/object.test.js | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/traverse.js b/src/traverse.js index 9631661..5a529ae 100644 --- a/src/traverse.js +++ b/src/traverse.js @@ -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); }); } diff --git a/src/value.js b/src/value.js index 0b7fe45..d339418 100644 --- a/src/value.js +++ b/src/value.js @@ -48,10 +48,10 @@ 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; @@ -59,13 +59,13 @@ Value.prototype.getPath = function () { 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; } @@ -73,11 +73,10 @@ Value.prototype.byPath = function (path) { 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; diff --git a/test/matcher-to-equal/object.test.js b/test/matcher-to-equal/object.test.js index a8a05f1..e599ea1 100644 --- a/test/matcher-to-equal/object.test.js +++ b/test/matcher-to-equal/object.test.js @@ -60,3 +60,21 @@ test('nested object vs different type', 'Expected Object({ foo: Object({ bar: 42 }) }) ' + 'to equal Object({ foo: true }).' ); + +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: 43 }) ' + + 'to equal Object({ foo.bar: 42, qux: 44 }).' +); + +test('keys with dots different', + + 'Expected Object({ foo.bar: 42, foo: 43 }) ' + + 'to equal Object({ foo.baz: 42, foo: 44 }).', + + 'Expected Object({ foo.bar: 42, foo: 43 }) ' + + 'to equal Object({ foo.baz: 42, foo: 44 }).' +);