docusaurus/website/src/utils/jsUtils.ts
Joshua Chen d85cee576d
test: improve test coverage; properly test core client APIs (#6905)
* test: improve test coverage

* fix
2022-03-12 23:15:45 +08:00

30 lines
840 B
TypeScript

/**
* 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.
*/
// Inspired by https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_sortby-and-_orderby
export function sortBy<T>(
array: T[],
getter: (item: T) => string | number | boolean,
): T[] {
const sortedArray = [...array];
sortedArray.sort((a, b) =>
// eslint-disable-next-line no-nested-ternary
getter(a) > getter(b) ? 1 : getter(b) > getter(a) ? -1 : 0,
);
return sortedArray;
}
export function toggleListItem<T>(list: T[], item: T): T[] {
const itemIndex = list.indexOf(item);
if (itemIndex === -1) {
return list.concat(item);
}
const newList = [...list];
newList.splice(itemIndex, 1);
return newList;
}