|
| 1 | +/** |
| 2 | + * Problem: Code a function that takes 2 paths, example: |
| 3 | + * src/route/home.js |
| 4 | + * src/utils/helper.js |
| 5 | + * Then outputs a string of how the first file would import the second one |
| 6 | + * import helper from "../utils/helper" |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * first = .... |
| 11 | + * second = .... |
| 12 | + * first.split("/"); => ["src", "route", "home.js"] |
| 13 | + * second.split("/"); => ["src", "utils", "helper.js"] |
| 14 | + * |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * |
| 20 | + */ |
| 21 | + |
| 22 | +module.exports = importPath = (str1, str2) => { |
| 23 | + if (str1.length === 0 || str2.length === 0) { |
| 24 | + return null; |
| 25 | + } |
| 26 | + |
| 27 | + const str1Splited = str1.split("/"); |
| 28 | + const str2Splited = str2.split("/"); |
| 29 | + let amountOfRoutesToRemove = 0; |
| 30 | + |
| 31 | + for (index in str2Splited) { |
| 32 | + let currEl = str2Splited[index]; |
| 33 | + if (currEl === str1Splited[index]) { |
| 34 | + amountOfRoutesToRemove++; |
| 35 | + } else { |
| 36 | + str1Splited.splice(0, amountOfRoutesToRemove); |
| 37 | + str2Splited.splice(0, amountOfRoutesToRemove); |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + let finalLocation = ""; |
| 43 | + if (str1Splited.length === 1) { |
| 44 | + finalLocation = "./"; |
| 45 | + } else { |
| 46 | + finalLocation = `${finalLocation}../`; |
| 47 | + } |
| 48 | + |
| 49 | + for (let i = 0; i < str2Splited.length - 1; i++) { |
| 50 | + finalLocation = `${finalLocation}${str2Splited[i]}/${ |
| 51 | + str2Splited[str2Splited.length - 1] |
| 52 | + }`; |
| 53 | + } |
| 54 | + |
| 55 | + return finalLocation; |
| 56 | +}; |
| 57 | + |
| 58 | +console.log(importPath("src/route/app/home.js", "src/route/utils/helpers.js")); |
0 commit comments