Last active
August 14, 2025 22:48
-
-
Save candidosales/d4b919f8b096746297f580e9bd880553 to your computer and use it in GitHub Desktop.
refactor
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 operations = { | |
| ",": commaOperation, | |
| "|": pipeOperation, | |
| "?": markQuestionOperation, | |
| "/": backSlashOperation, | |
| } | |
| function add(a, b) { | |
| if (typeof a === 'string') { | |
| for (const [key, operation] of Object.entries(operations)) { | |
| if (a.includes(key)) { | |
| return key === "/" ? operation(a, b) : operation(a); | |
| } | |
| } | |
| } | |
| const parsedA = parseInt(a); | |
| const parsedB = parseInt(b); | |
| return parsedA + parsedB; | |
| } | |
| function commaOperation(a) { | |
| const numbers = a.split(',').map(num => parseInt(num.trim())); | |
| return numbers.reduce((sum, num) => sum + num, 0); | |
| } | |
| function pipeOperation(a) { | |
| const numbers = a.split('|').map(num => parseInt(num.trim())); | |
| return numbers.reduce((sum, num) => sum + num, 0); | |
| } | |
| function markQuestionOperation(a) { | |
| const numbers = a.split('?').map(num => parseInt(num.trim())); | |
| return numbers.reduce((sum, num) => sum + num, 0); | |
| } | |
| function backSlashOperation(a, b) { | |
| const [year, month, day] = a.split('/').map(num => parseInt(num.trim())); | |
| const [year2, month2, day2] = b.split('/').map(num => parseInt(num.trim())); | |
| return (day + day2); | |
| } | |
| console.log(add(1, 2)); | |
| console.log(add("1", "2")); | |
| console.log(add("1,2")); | |
| console.log(add("1|2")); | |
| console.log(add("1?2")); | |
| console.log(add("2025/04/01", "2025/03/22")); // Should give 23 adding the days together | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment