diff --git a/logic-exercises/jest.config.js b/logic-exercises/jest.config.js new file mode 100644 index 0000000..320eb15 --- /dev/null +++ b/logic-exercises/jest.config.js @@ -0,0 +1,8 @@ +module.exports = { + roots: ["/tests"], + transform: { + "^.+\\.tsx?$": "ts-jest", + }, + testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$", + moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], + } \ No newline at end of file diff --git a/logic-exercises/package.json b/logic-exercises/package.json index eb6d6ea..0b5ce97 100644 --- a/logic-exercises/package.json +++ b/logic-exercises/package.json @@ -5,7 +5,8 @@ "main": "index.js", "scripts": { "ex1": "clear && tsnd --transpile-only --ignore-watch node_modules src/exc1.ts", - "ex2": "clear && tsnd --transpile-only --ignore-watch node_modules src/exc2.ts" + "ex2": "clear && tsnd --transpile-only --ignore-watch node_modules src/exc2.ts", + "test": "clear && echo && jest" }, "keywords": [], "author": "Daniel Ratti", diff --git a/logic-exercises/src/twosum.ts b/logic-exercises/src/twosum.ts new file mode 100644 index 0000000..200fd9f --- /dev/null +++ b/logic-exercises/src/twosum.ts @@ -0,0 +1,14 @@ +interface hashTable { + [index: number]: number; +} + +export const twoSum = (arr: number[], target: number) => { + let hash: hashTable = {}; + for (let i = 0; i < arr.length; i++) { + let current = arr[i]; + let next = target - current; + const indexNext = hash[next]; + if (indexNext !== undefined) return [indexNext, i]; + hash[current] = i; + } +}; diff --git a/logic-exercises/tests/TwoSum.test.ts b/logic-exercises/tests/TwoSum.test.ts new file mode 100644 index 0000000..f124557 --- /dev/null +++ b/logic-exercises/tests/TwoSum.test.ts @@ -0,0 +1,10 @@ +import {twoSum} from "../src/twosum" +describe("Testing twoSum", () => { + it("Should return [0,1]", () => { + expect(twoSum([2, 7, 11, 15], 9)).toStrictEqual([0, 1]); + }); + + it("Should return [1,3]", () => { + expect(twoSum([4, 5, 10, 12, 21], 17)).toStrictEqual([1, 3]); + }); +});