Skip to content

Commit 000762a

Browse files
feat: add array count occurrences algorithm
1 parent 5c39e87 commit 000762a

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @function countOccurrences
3+
* @description Counts the number of times a value appears in an array.
4+
* @param {Array} arr - The input array
5+
* @param {*} value - The value to count
6+
* @returns {number} - The number of times value appears in arr
7+
* @see https://en.wikipedia.org/wiki/Frequency_(statistics)
8+
* @example countOccurrences([1, 2, 2, 3, 2], 2) => 3
9+
* @example countOccurrences(['a', 'b', 'a'], 'a') => 2
10+
* @example countOccurrences([1, 2, 3], 4) => 0
11+
*/
12+
const countOccurrences = (arr, value) => {
13+
if (!Array.isArray(arr)) {
14+
throw new TypeError('First argument must be an array')
15+
}
16+
return arr.reduce((count, item) => (item === value ? count + 1 : count), 0)
17+
}
18+
19+
export { countOccurrences }
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { countOccurrences } from '../CountOccurrences.js'
2+
3+
describe('countOccurrences', () => {
4+
test('countOccurrences([1,2,2,3,2], 2) returns 3', () => {
5+
expect(countOccurrences([1, 2, 2, 3, 2], 2)).toBe(3)
6+
})
7+
8+
test("countOccurrences(['a','b','a'], 'a') returns 2", () => {
9+
expect(countOccurrences(['a', 'b', 'a'], 'a')).toBe(2)
10+
})
11+
12+
test('countOccurrences([1,2,3], 4) returns 0', () => {
13+
expect(countOccurrences([1, 2, 3], 4)).toBe(0)
14+
})
15+
16+
test('countOccurrences empty array returns 0', () => {
17+
expect(countOccurrences([], 1)).toBe(0)
18+
})
19+
20+
test('countOccurrences all same elements', () => {
21+
expect(countOccurrences([2, 2, 2, 2], 2)).toBe(4)
22+
})
23+
24+
test('countOccurrences with boolean values', () => {
25+
expect(countOccurrences([true, false, true, true], true)).toBe(3)
26+
})
27+
28+
test('countOccurrences with null values', () => {
29+
expect(countOccurrences([null, 1, null, 2], null)).toBe(2)
30+
})
31+
32+
test('countOccurrences does not mutate original array', () => {
33+
const arr = [1, 2, 2, 3]
34+
countOccurrences(arr, 2)
35+
expect(arr).toEqual([1, 2, 2, 3])
36+
})
37+
38+
test('throws TypeError for non-array input', () => {
39+
expect(() => countOccurrences('123', 1)).toThrow(TypeError)
40+
})
41+
42+
test('throws TypeError for null input', () => {
43+
expect(() => countOccurrences(null, 1)).toThrow(TypeError)
44+
})
45+
})

0 commit comments

Comments
 (0)