Skip to content

Commit 6ff0dbb

Browse files
committed
import part from 2 strings problem
1 parent d6a2add commit 6ff0dbb

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

LeetCode/ImportPath/index.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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"));

LeetCode/ImportPath/index.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const importPath = require("./index");
2+
3+
describe("tets for import path problem", () => {
4+
it("return the import path from str1 to str2", () => {
5+
let expected = "../utils/helpers.js";
6+
let actual = importPath(
7+
"src/route/app/home.js",
8+
"src/route/utils/helpers.js"
9+
);
10+
expect(actual).toEqual(expected);
11+
});
12+
});

0 commit comments

Comments
 (0)