Created
March 3, 2019 20:45
-
-
Save BolajiAyodeji/db6e545dfc434c7402d10cb2a13759a3 to your computer and use it in GitHub Desktop.
Count occurence of a number in an array with Error Handling
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
function countOccurences(array, searchElement) { | |
if (!Array.isArray(array)) { | |
throw new Error('Enter a valid array'); | |
} | |
return array.reduce((accumulator, current) => { | |
const occurence = (current === searchElement) ? 1 : 0; | |
return accumulator + occurence; | |
}, 0) | |
} | |
try { | |
const numbers = null; | |
const count = countOccurences(numbers, 1); | |
console.log(count); | |
} | |
catch(e) { | |
console.log(e.message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment