Last active
September 28, 2016 22:37
-
-
Save dtothefp/c903a1a8e4bb1e334a9f406f1aac2cbd 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
const urls = `/home/anti-depressants/xanax | |
/home/heart/lipitor | |
/home/heart/atorvastatin | |
/home/heart/aspirin | |
/drugs/nasal/flonase | |
/drugs/topical | |
/drugs/routes/oral/tablets | |
/drugs/routes/nasal/flonase`; | |
const parseUrl = (url) => { | |
return url.split('/').filter(part => !!part); | |
}; | |
const parseString = (list) => { | |
return list.split(/\n/).map(parseUrl); | |
}; | |
const reducer = (acc, list) => { | |
if (!list.length) return null; | |
const key = list.slice(0, 1)[0]; | |
const rest = list.slice(1); | |
const reduced = reducer(acc[key] || {}, rest); | |
acc[key] = reduced; | |
return acc; | |
}; | |
const makeJson = (list) => { | |
return parseString(list).reduce(reducer, {}); | |
} | |
const pad = (str, i) => { | |
const tab = ' '; | |
let padding = ''; | |
for (let j = 0; j < i * 2; j++) { | |
padding += tab; | |
} | |
return `${padding}- ${str}\n`; | |
}; | |
const listDrugs = (json, depth = 0) => { | |
return Object.keys(json).reduce((str, drug) => { | |
const child = json[drug]; | |
if (child === null) { | |
str += pad(drug, depth); | |
} else { | |
const drugs = listDrugs(child, depth + 1); | |
str += (pad(drug, depth) + drugs); | |
} | |
return str; | |
}, ''); | |
}; | |
console.log( | |
listDrugs(makeJson(urls)) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment