Last active
April 19, 2021 14:26
-
-
Save AbdQaadir/f69e677b34f9c69c809f7d02c355f8cc to your computer and use it in GitHub Desktop.
This file contains 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 removeInstances = ({arr, val}) => { | |
const arrLength = arr.length; | |
if(arrLength === 0) throw new Error("Array cannot be empty"); | |
//Return the orginal length of array if no number is passed in. | |
if(!val) return arrLength; | |
const filteredArray = arr.filter((num) => num !== val); | |
return filteredArray.length; | |
}; | |
const arr = [5,2,2,5,3]; | |
const val = 5; | |
console.log(removeInstances({arr, val})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @AbdQaadir, thank you for participating in Week 2 of Algorithm Fridays.
Your solution works for most of the test cases; however it assumes that the input array
arr
cannot have anull
orundefined
value because if I runremoveInstances({ arr: null, val})
, your code will break on line 3. Ideally you want to write robust code that can handle unexpected input and fail gracefully without causing runtime errors.Also I like that you used JavaScript's in-built
filter
function. What do you think are the trade-offs with using thefilter
function?I've posted my solution here. Do let me know what you think.