feat(join): Add join function (#423)
Some checks failed
CI / codecov (push) Has been cancelled
Release / release (push) Has been cancelled

* feat: add join function

* fix: update testcase
This commit is contained in:
xiaoluo 2024-08-31 18:39:27 +08:00 committed by GitHub
parent a84ffa9aed
commit 3a6cb36538
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 50 additions and 0 deletions

View File

@ -0,0 +1,13 @@
import { bench, describe } from 'vitest';
import { join as joinToolkit } from 'es-toolkit';
import { join as joinLodash } from 'lodash';
describe('join', () => {
bench('es-toolkit', () => {
joinToolkit([1, 2, 3], ',');
});
bench('lodash', () => {
joinLodash([1, 2, 3], ',');
});
});

View File

@ -18,6 +18,7 @@ export { groupBy } from './groupBy.ts';
export { intersection } from './intersection.ts';
export { intersectionBy } from './intersectionBy.ts';
export { intersectionWith } from './intersectionWith.ts';
export { join } from './join.ts';
export { keyBy } from './keyBy.ts';
export { maxBy } from './maxBy.ts';
export { minBy } from './minBy.ts';

16
src/array/join.spec.ts Normal file
View File

@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import { join } from './join.js';
describe('join', () => {
it('should join elements of an array into a string', () => {
const arr = ['a', 'b', 'c'];
const result = join(arr);
expect(result).toBe('a,b,c');
});
it('should join elements of an array into a string with a custom separator', () => {
const arr = ['a', 'b', 'c'];
const result = join(arr, '~');
expect(result).toBe('a~b~c');
});
});

20
src/array/join.ts Normal file
View File

@ -0,0 +1,20 @@
/**
*
* Join elements of an array into a string.
*
* @template T - The type of elements in the array.
* @param {readonly T[]} array - The array to join.
* @param {string} separator - The separator used to join the elements, default is common separator `,`.
* @returns {string} - Returns a string containing all elements of the array joined by the specified separator.
*
* @example
* ```typescript
* const arr = ["a","b","c"];
* const result = join(arr, "~");
* console.log(result); // Output: "a~b~c"
* ```
*
*/
export function join<T>(array: readonly T[], separator = ','): string {
return array.join(separator);
}