Last active
March 17, 2018 02:30
-
-
Save jschwarty/acfa6f8f933b0e094ed6c0006362f201 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('doit', () => { | |
it('should build graph', () => { | |
const t = { | |
cart: ['saved'], | |
saved: ['items'], | |
items: [] | |
}; | |
const r = { | |
cart: 'cart', | |
saved: 'cart.saved', | |
items: 'cart.saved.items' | |
}; | |
const actual = doit(t); | |
expect(actual).toEqual(r); | |
}); | |
it('order should not matter', () => { | |
const t = { | |
saved: ['items'], | |
items: [], | |
cart: ['saved'] | |
}; | |
const r = { | |
cart: 'cart', | |
saved: 'cart.saved', | |
items: 'cart.saved.items' | |
}; | |
const actual = doit(t); | |
expect(actual).toEqual(r); | |
}); | |
}); | |
function findFullParentPath(obj, keyToFind) { | |
for (const key in obj) { | |
if (obj.hasOwnProperty(key) && obj[key].indexOf(keyToFind) >= 0) { | |
const parent = findFullParentPath(obj, key); | |
return parent !== null ? `${parent}.${key}` : key; | |
} | |
} | |
return null; | |
} | |
function doit(obj, newObj = {}) { | |
for (const key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
const parent = findFullParentPath(obj, key); | |
newObj[key] = parent ? `${parent}.${key}` : key; | |
} | |
} | |
return newObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment