Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

新增 countCharacters.js, 计算字符串中每个字符的出现次数 #120

Merged
merged 2 commits into from
Aug 6, 2024
Merged
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 lib/string/countCharacters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 计算字符串中每个字符的出现次数。
* @author penn <https://github.com/penn201500>
* @category string
* @alias yd_string_countCharacters
* @param {String} str - 字符串。
* @returns {Object} - 包含每个字符的出现次数的对象。
*
* @example
* console.log(countCharacters("hello world"))
* // 输出: { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
*/
export default function countCharacters(str) {
const count = {};
for (const char of str) {
count[char] = (count[char] || 0) + 1;
}
return count;
}
24 changes: 24 additions & 0 deletions lib/string/countCharacters.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { it, expect, describe } from 'vitest';
import yd_string_countCharacters from './countCharacters.js';

describe('yd_string_countCharacters', () => {
it('should correctly return counts for each characters in a string', () => {
const result = yd_string_countCharacters('hello');
expect(result).toEqual({ h: 1, e: 1, l: 2, o: 1 });
});

it('should handle a string with numbers', () => {
const result = yd_string_countCharacters('hello42');
expect(result).toEqual({ h: 1, e: 1, l: 2, o: 1, 4: 1, 2: 1 });
});

it('should handle a string with special characters', () => {
const result = yd_string_countCharacters('hello!@');
expect(result).toEqual({ h: 1, e: 1, l: 2, o: 1, '!': 1, '@': 1 });
});

it('should handle an empty string', () => {
const result = yd_string_countCharacters('');
expect(result).toEqual({});
});
});
Loading