Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Data-Structures/Array/CountOccurrences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @function countOccurrences
* @description Counts the number of times a value appears in an array.
* @param {Array} arr - The input array
* @param {*} value - The value to count
* @returns {number} - The number of times value appears in arr
* @see https://en.wikipedia.org/wiki/Frequency_(statistics)
* @example countOccurrences([1, 2, 2, 3, 2], 2) => 3
* @example countOccurrences(['a', 'b', 'a'], 'a') => 2
* @example countOccurrences([1, 2, 3], 4) => 0
*/
const countOccurrences = (arr, value) => {
if (!Array.isArray(arr)) {
throw new TypeError('First argument must be an array')
}
return arr.reduce((count, item) => (item === value ? count + 1 : count), 0)
}

export { countOccurrences }
45 changes: 45 additions & 0 deletions Data-Structures/Array/test/CountOccurrences.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { countOccurrences } from '../CountOccurrences.js'

describe('countOccurrences', () => {
test('countOccurrences([1,2,2,3,2], 2) returns 3', () => {
expect(countOccurrences([1, 2, 2, 3, 2], 2)).toBe(3)
})

test("countOccurrences(['a','b','a'], 'a') returns 2", () => {
expect(countOccurrences(['a', 'b', 'a'], 'a')).toBe(2)
})

test('countOccurrences([1,2,3], 4) returns 0', () => {
expect(countOccurrences([1, 2, 3], 4)).toBe(0)
})

test('countOccurrences empty array returns 0', () => {
expect(countOccurrences([], 1)).toBe(0)
})

test('countOccurrences all same elements', () => {
expect(countOccurrences([2, 2, 2, 2], 2)).toBe(4)
})

test('countOccurrences with boolean values', () => {
expect(countOccurrences([true, false, true, true], true)).toBe(3)
})

test('countOccurrences with null values', () => {
expect(countOccurrences([null, 1, null, 2], null)).toBe(2)
})

test('countOccurrences does not mutate original array', () => {
const arr = [1, 2, 2, 3]
countOccurrences(arr, 2)
expect(arr).toEqual([1, 2, 2, 3])
})

test('throws TypeError for non-array input', () => {
expect(() => countOccurrences('123', 1)).toThrow(TypeError)
})

test('throws TypeError for null input', () => {
expect(() => countOccurrences(null, 1)).toThrow(TypeError)
})
})
Loading