Skip to content

Commit f2faba1

Browse files
committed
Updated find-path.
1 parent 6fd1479 commit f2faba1

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

find-path/index.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* @author: Chisimdi Damian Ezeanieto
3+
* @date: 16/03/2023
4+
- Should take two params:
5+
- object
6+
- keys separated by dots as string
7+
- Return value if it exists at that path inside the object, else return undefined
8+
*/
9+
10+
// const findPath = (obj, path) => {
11+
// if (!path) return undefined;
12+
13+
// const keys = path.split('.');
14+
// let value = obj;
15+
// for (let key of keys) {
16+
// if (!value.hasOwnProperty(key)) {
17+
// return undefined;
18+
// }
19+
// value = value[key];
20+
// }
21+
// return value;
22+
// };
23+
24+
// const findPath = (obj, path) => {
25+
// return path.split('.').reduce((value, key) => value && value[key], obj);
26+
// };
27+
28+
// Using Recursion
29+
const findPath = (obj, path) => {
30+
const keys = path.split('.');
31+
if (keys.length === 1) {
32+
return obj[path];
33+
} else {
34+
const nextKey = keys.shift();
35+
const nextObj = obj[nextKey];
36+
if (nextObj === undefined) {
37+
return undefined;
38+
}
39+
return findPath(nextObj, keys.join('.'));
40+
}
41+
}
42+
43+
module.exports = findPath;

find-path/test.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* @author: Chisimdi Damian Ezeanieto
3+
* @date: 16/03/2023
4+
*/
5+
const findPath = require('./index');
6+
7+
const obj = {
8+
a: {
9+
b: {
10+
c: 12,
11+
j: false
12+
},
13+
k: null
14+
}
15+
};
16+
17+
describe('Phone key pad match', () => {
18+
test('findPath function is defined', () => {
19+
expect(typeof findPath).toEqual('function');
20+
});
21+
test('Find Path for "a.b.d" === undefined', () => {
22+
expect(findPath(obj, 'a.b.d')).toEqual(undefined);
23+
});
24+
test('Find Path for "a.b.c" === 12', () => {
25+
expect(findPath(obj, 'a.b.c')).toEqual(12);
26+
});
27+
test('Find Path for "a.b.j" === false', () => {
28+
expect(findPath(obj, 'a.b.j')).toEqual(false);
29+
});
30+
test('Find Path for "a.b.j.k" === undefined', () => {
31+
expect(findPath(obj, 'a.b.j.k')).toEqual(undefined);
32+
});
33+
test('Find Path for "a.c" === undefined', () => {
34+
expect(findPath(obj, 'a.c')).toEqual(undefined);
35+
});
36+
test('Find Path for "a.b.c.d.e" === undefined', () => {
37+
expect(findPath(obj, 'a.b.c.d.e')).toEqual(undefined);
38+
});
39+
test('Find Path for "a.k" === null', () => {
40+
expect(findPath(obj, 'a.k')).toEqual(null);
41+
});
42+
});

0 commit comments

Comments
 (0)