refactor: improve setup of type declaration files (#5914)

This commit is contained in:
Joshua Chen 2021-11-13 00:47:27 +08:00 committed by GitHub
parent 334470b5d4
commit d1308a8736
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 872 additions and 868 deletions

View file

@ -63,7 +63,7 @@ export {
useDocsPreferredVersionByPluginId,
} from './utils/docsPreferredVersion/useDocsPreferredVersion';
export {duplicates} from './utils/jsUtils';
export {duplicates, uniq} from './utils/jsUtils';
export {DocsPreferredVersionContextProvider} from './utils/docsPreferredVersion/DocsPreferredVersionProvider';

View file

@ -0,0 +1,33 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {uniq} from '../jsUtils';
describe('uniq', () => {
test('remove duplicate primitives', () => {
expect(uniq(['A', 'B', 'C', 'B', 'A', 'D'])).toEqual(['A', 'B', 'C', 'D']);
expect(uniq([3, 3, 5, 1, 6, 3, 5])).toEqual([3, 5, 1, 6]);
expect(uniq([null, undefined, 3, null, 4, 3])).toEqual([
null,
undefined,
3,
4,
]);
});
test('remove duplicate objects/arrays by identity', () => {
const obj1 = {};
const obj2 = {};
const obj3 = {};
const array1: unknown[] = [];
const array2: unknown[] = [];
const array3: unknown[] = [];
expect(
uniq([obj1, obj1, obj2, array1, obj2, array3, array2, array1, obj3]),
).toEqual([obj1, obj2, array1, array3, array2, obj3]);
});
});

View file

@ -21,3 +21,13 @@ export function duplicates<T>(
(v, vIndex) => arr.findIndex((u) => comparator(u, v)) !== vIndex,
);
}
/**
* Remove duplicate array items (similar to _.uniq)
* @param arr The array.
* @returns An array with duplicate elements removed by reference comparison.
*/
export function uniq<T>(arr: T[]): T[] {
// Note: had problems with [...new Set()]: https://github.com/facebook/docusaurus/issues/4972#issuecomment-863895061
return Array.from(new Set(arr));
}