Skip to content

Commit

Permalink
feat(paths): add exists() path checker & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Sep 1, 2018
1 parent e66a492 commit f018353
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
27 changes: 27 additions & 0 deletions packages/paths/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,33 @@ export function toPath(path: Path) {
return isArray(path) ? path : isString(path) ? path.length > 0 ? path.split(".") : [] : path != null ? [path] : [];
}

/**
* Takes an arbitrary object and lookup path. Descends into object along
* path and returns true if the full path exists (even if final leaf
* value is `null` or `undefined`). Checks are performed using
* `hasOwnProperty()`.
*
* @param obj
* @param path
*/
export const exists = (obj: any, path: Path) => {
if (obj == null) {
return false;
}
path = toPath(path);
for (let n = path.length - 1, i = 0; i <= n; i++) {
const k = path[i];
if (!obj.hasOwnProperty(k)) {
return false;
}
obj = obj[k];
if (obj == null && i < n) {
return false;
}
}
return true;
};

/**
* Composes a getter function for given nested lookup path. Optimized
* fast execution paths are provided for path lengths less than 5.
Expand Down
19 changes: 18 additions & 1 deletion packages/paths/test/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as assert from "assert";
import { setIn } from "../src/index";
import { exists, setIn } from "../src/index";

describe("paths", () => {
it("setIn (len = 0)", () => {
Expand Down Expand Up @@ -150,4 +150,21 @@ describe("paths", () => {
assert(a.x.y === b.x.y);
assert(a.u === b.u);
});

it("exists", () => {
const a = { a: { b: null } };
const b = { x: { y: { z: [1, 2, { u: 3, v: undefined }] } } };
assert(!exists(null, "x.y.z"), "x.y.z");
assert(!exists(0, "x.y.z"), "x.y.z");
assert(exists("", "length"), "length");
assert(exists(a, "a.b"), "a.b");
assert(!exists(a, "a.b.c"), "a.b.c");
assert(exists(b, "x"), "x");
assert(exists(b, "x.y.z"), "x.y.z");
assert(exists(b, "x.y.z.2.u"), "x.y.z.2.u");
assert(exists(b, "x.y.z.2.v"), "x.y.z.2.v");
assert(!exists(b, "x.y.z.3"), "x.y.z.3");
assert(!exists(b, "x.y.z.3.u"), "x.y.z.3.u");
assert(!exists(b, "x.z.y.2.u"), "x.z.y.2.u");
})
});

0 comments on commit f018353

Please sign in to comment.