Skip to content

Commit

Permalink
refactor: ensure lodash is default-imported
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena committed Feb 19, 2022
1 parent 47c9a37 commit 53fa129
Show file tree
Hide file tree
Showing 44 changed files with 240 additions and 222 deletions.
61 changes: 37 additions & 24 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,31 +69,44 @@ module.exports = {
'no-param-reassign': [WARNING, {props: false}],
'no-prototype-builtins': WARNING,
'no-restricted-exports': OFF,
'no-restricted-imports': [
'no-restricted-properties': [
ERROR,
{
paths: [
{
name: 'lodash',
importNames: [
// TODO: TS doesn't make Boolean a narrowing function yet,
// so filter(Boolean) is problematic type-wise
// 'compact',
'filter',
'flatten',
'flatMap',
'map',
'reduce',
'take',
'takeRight',
'head',
'tail',
'initial',
],
message: 'These APIs have their ES counterparts.',
},
],
},
...[
// TODO: TS doesn't make Boolean a narrowing function yet,
// so filter(Boolean) is problematic type-wise
// ['compact', 'Array#filter(Boolean)'],
['concat', 'Array#concat'],
['drop', 'Array#slice(n)'],
['dropRight', 'Array#slice(0, -n)'],
['fill', 'Array#fill'],
['filter', 'Array#filter'],
['find', 'Array#find'],
['findIndex', 'Array#findIndex'],
['first', 'foo[0]'],
['flatten', 'Array#flat'],
['flattenDeep', 'Array#flat(Infinity)'],
['flatMap', 'Array#flatMap'],
['fromPairs', 'Object.fromEntries'],
['head', 'foo[0]'],
['indexOf', 'Array#indexOf'],
['initial', 'Array#slice(0, -1)'],
['join', 'Array#join'],
// Unfortunately there's no great alternative to _.last yet
// Candidates: foo.slice(-1)[0]; foo[foo.length - 1]
// Array#at is ES2022; could replace _.nth as well
// ['last'],
['map', 'Array#map'],
['reduce', 'Array#reduce'],
['reverse', 'Array#reverse'],
['slice', 'Array#slice'],
['take', 'Array#slice(0, n)'],
['takeRight', 'Array#slice(-n)'],
['tail', 'Array#slice(1)'],
].map(([property, alternative]) => ({
object: '_',
property,
message: `Use ${alternative} instead.`,
})),
],
'no-restricted-syntax': [
WARNING,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {uniqBy, difference, groupBy} from 'lodash';
import _ from 'lodash';
import type {
PluginOptions,
RedirectOption,
Expand Down Expand Up @@ -79,7 +79,7 @@ function validateCollectedRedirects(

const allowedToPaths = pluginContext.relativeRoutesPaths;
const toPaths = redirects.map((redirect) => redirect.to);
const illegalToPaths = difference(toPaths, allowedToPaths);
const illegalToPaths = _.difference(toPaths, allowedToPaths);
if (illegalToPaths.length > 0) {
throw new Error(
`You are trying to create client-side redirections to paths that do not exist:
Expand All @@ -98,7 +98,7 @@ function filterUnwantedRedirects(
): RedirectMetadata[] {
// we don't want to create twice the same redirect
// that would lead to writing twice the same html redirection file
Object.entries(groupBy(redirects, (redirect) => redirect.from)).forEach(
Object.entries(_.groupBy(redirects, (redirect) => redirect.from)).forEach(
([from, groupedFromRedirects]) => {
if (groupedFromRedirects.length > 1) {
logger.error`name=${'@docusaurus/plugin-client-redirects'}: multiple redirects are created with the same "from" pathname: path=${from}
Expand All @@ -108,7 +108,7 @@ It is not possible to redirect the same pathname to multiple destinations: ${gro
}
},
);
const collectedRedirects = uniqBy(redirects, (redirect) => redirect.from);
const collectedRedirects = _.uniqBy(redirects, (redirect) => redirect.from);

// We don't want to override an already existing route with a redirect file!
const redirectsOverridingExistingPath = collectedRedirects.filter(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@

import * as eta from 'eta';
import redirectPageTemplate from './templates/redirectPage.template.html';
import {memoize} from 'lodash';
import _ from 'lodash';

type CreateRedirectPageOptions = {
toUrl: string;
};

const getCompiledRedirectPageTemplate = memoize(() =>
const getCompiledRedirectPageTemplate = _.memoize(() =>
eta.compile(redirectPageTemplate.trim()),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import fs from 'fs-extra';
import path from 'path';
import {memoize} from 'lodash';
import _ from 'lodash';

import type {PluginContext, RedirectMetadata} from './types';
import createRedirectPageContent from './createRedirectPageContent';
Expand Down Expand Up @@ -63,7 +63,7 @@ export function toRedirectFilesMetadata(
// Perf: avoid rendering the template twice with the exact same "props"
// We might create multiple redirect pages for the same destination url
// note: the first fn arg is the cache key!
const createPageContentMemoized = memoize((toUrl: string) =>
const createPageContentMemoized = _.memoize((toUrl: string) =>
createRedirectPageContent({toUrl}),
);

Expand Down
30 changes: 13 additions & 17 deletions packages/docusaurus-plugin-content-blog/src/blogUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import fs from 'fs-extra';
import path from 'path';
import readingTime from 'reading-time';
import {keyBy, mapValues} from 'lodash';
import _ from 'lodash';
import type {
BlogPost,
BlogContentPaths,
Expand Down Expand Up @@ -46,9 +46,8 @@ export function truncate(fileString: string, truncateMarker: RegExp): string {
export function getSourceToPermalink(
blogPosts: BlogPost[],
): Record<string, string> {
return mapValues(
keyBy(blogPosts, (item) => item.metadata.source),
(v) => v.metadata.permalink,
return Object.fromEntries(
blogPosts.map(({metadata: {source, permalink}}) => [source, permalink]),
);
}

Expand Down Expand Up @@ -112,19 +111,16 @@ export function getBlogTags({
(blogPost) => blogPost.metadata.tags,
);

return mapValues(groups, (group) => {
const {tag, items: tagBlogPosts} = group;
return {
name: tag.label,
items: tagBlogPosts.map((item) => item.id),
permalink: tag.permalink,
pages: paginateBlogPosts({
blogPosts: tagBlogPosts,
basePageUrl: group.tag.permalink,
...params,
}),
};
});
return _.mapValues(groups, ({tag, items: tagBlogPosts}) => ({
name: tag.label,
items: tagBlogPosts.map((item) => item.id),
permalink: tag.permalink,
pages: paginateBlogPosts({
blogPosts: tagBlogPosts,
basePageUrl: tag.permalink,
...params,
}),
}));
}

const DATE_FILENAME_REGEX =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import path from 'path';
import {isMatch} from 'picomatch';
import commander from 'commander';
import {kebabCase, orderBy} from 'lodash';
import _ from 'lodash';

import fs from 'fs-extra';
import pluginContentDocs from '../index';
Expand Down Expand Up @@ -89,7 +89,7 @@ Entries created:

checkVersionMetadataPropCreated: (version: LoadedVersion) => {
const versionMetadataProp = getCreatedDataByPrefix(
`version-${kebabCase(version.versionName)}-metadata-prop`,
`version-${_.kebabCase(version.versionName)}-metadata-prop`,
);
expect(versionMetadataProp.docsSidebars).toEqual(toSidebarsProp(version));
},
Expand Down Expand Up @@ -815,7 +815,7 @@ describe('site with custom sidebar items generator', () => {
): SidebarItemsGeneratorOptionArgs {
return {
...arg,
docs: orderBy(arg.docs, 'id'),
docs: _.orderBy(arg.docs, 'id'),
version: {
...arg.version,
contentPath: path.relative(siteDir, arg.version.contentPath),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import type {
GlobalVersion,
ActivePlugin,
} from '@docusaurus/plugin-content-docs/client';
import {shuffle} from 'lodash';
import _ from 'lodash';

describe('docsClientUtils', () => {
test('getActivePlugin', () => {
Expand Down Expand Up @@ -227,7 +227,7 @@ describe('docsClientUtils', () => {
};

// shuffle, because order shouldn't matter
const versions: GlobalVersion[] = shuffle([
const versions: GlobalVersion[] = _.shuffle([
versionNext,
version2,
version1,
Expand Down Expand Up @@ -356,7 +356,7 @@ describe('docsClientUtils', () => {
};

// shuffle, because order shouldn't matter
const versions: GlobalVersion[] = shuffle([
const versions: GlobalVersion[] = _.shuffle([
versionNext,
version2,
version1,
Expand Down
11 changes: 6 additions & 5 deletions packages/docusaurus-plugin-content-docs/src/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import path from 'path';
import fs from 'fs-extra';
import logger from '@docusaurus/logger';
import {keyBy} from 'lodash';
import {
aliasedSitePath,
getEditUrl,
Expand Down Expand Up @@ -444,8 +443,10 @@ export function getDocIds(doc: DocMetadataBase): [string, string] {
export function createDocsByIdIndex<
Doc extends {id: string; unversionedId: string},
>(docs: Doc[]): Record<string, Doc> {
return {
...keyBy(docs, (doc) => doc.unversionedId),
...keyBy(docs, (doc) => doc.id),
};
return Object.fromEntries(
docs.flatMap((doc) => [
[doc.unversionedId, doc],
[doc.id, doc],
]),
);
}
4 changes: 2 additions & 2 deletions packages/docusaurus-plugin-content-docs/src/globalData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {mapValues} from 'lodash';
import _ from 'lodash';
import {normalizeUrl} from '@docusaurus/utils';
import type {Sidebars} from './sidebars/types';
import {createSidebarsUtils} from './sidebars/utils';
Expand Down Expand Up @@ -43,7 +43,7 @@ export function toGlobalSidebars(
version: LoadedVersion,
): Record<string, GlobalSidebar> {
const {getFirstLink} = createSidebarsUtils(sidebars);
return mapValues(sidebars, (sidebar, sidebarId) => {
return _.mapValues(sidebars, (sidebar, sidebarId) => {
const firstLink = getFirstLink(sidebarId);
if (!firstLink) {
return {};
Expand Down
6 changes: 2 additions & 4 deletions packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ import type {
import type {RuleSetRule} from 'webpack';
import {cliDocsVersionCommand} from './cli';
import {VERSIONS_JSON_FILE} from './constants';
import {keyBy, mapValues} from 'lodash';
import {toGlobalDataVersion} from './globalData';
import {toTagDocListProp} from './props';
import {
Expand Down Expand Up @@ -311,9 +310,8 @@ export default async function pluginContentDocs(

function getSourceToPermalink(): SourceToPermalink {
const allDocs = content.loadedVersions.flatMap((v) => v.docs);
return mapValues(
keyBy(allDocs, (d) => d.source),
(d) => d.permalink,
return Object.fromEntries(
allDocs.map(({source, permalink}) => [source, permalink]),
);
}

Expand Down
26 changes: 15 additions & 11 deletions packages/docusaurus-plugin-content-docs/src/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type {
PropTagDocListDoc,
PropSidebarItemLink,
} from '@docusaurus/plugin-content-docs';
import {compact, keyBy, mapValues} from 'lodash';
import _ from 'lodash';
import {createDocsByIdIndex} from './docs';

export function toSidebarsProp(loadedVersion: LoadedVersion): PropSidebars {
Expand Down Expand Up @@ -93,18 +93,22 @@ Available document ids are:
// Transform the sidebar so that all sidebar item will be in the
// form of 'link' or 'category' only.
// This is what will be passed as props to the UI component.
return mapValues(loadedVersion.sidebars, (items) => items.map(normalizeItem));
return _.mapValues(loadedVersion.sidebars, (items) =>
items.map(normalizeItem),
);
}

function toVersionDocsProp(loadedVersion: LoadedVersion): PropVersionDocs {
return mapValues(
keyBy(loadedVersion.docs, (doc) => doc.unversionedId),
(doc) => ({
id: doc.unversionedId,
title: doc.title,
description: doc.description,
sidebar: doc.sidebar,
}),
return Object.fromEntries(
loadedVersion.docs.map((doc) => [
doc.unversionedId,
{
id: doc.unversionedId,
title: doc.title,
description: doc.description,
sidebar: doc.sidebar,
},
]),
);
}

Expand Down Expand Up @@ -135,7 +139,7 @@ export function toTagDocListProp({
docs: Pick<DocMetadata, 'id' | 'title' | 'description' | 'permalink'>[];
}): PropTagDocList {
function toDocListProp(): PropTagDocListDoc[] {
const list = compact(
const list = _.compact(
tag.docIds.map((id) => docs.find((doc) => doc.id === id)),
);
// Sort docs by title
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {
NormalizedSidebarItem,
SidebarItemCategoryLinkConfig,
} from './types';
import {sortBy, last} from 'lodash';
import _ from 'lodash';
import {addTrailingSlash, posixPath} from '@docusaurus/utils';
import logger from '@docusaurus/logger';
import path from 'path';
Expand All @@ -25,7 +25,7 @@ const docIdPrefix = '$doc$/';

// Just an alias to the make code more explicit
function getLocalDocId(docId: string): string {
return last(docId.split('/'))!;
return _.last(docId.split('/'))!;
}

export const CategoryMetadataFilenameBase = '_category_';
Expand Down Expand Up @@ -248,7 +248,7 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({
}
return item;
});
const sortedSidebarItems = sortBy(
const sortedSidebarItems = _.sortBy(
processedSidebarItems,
(item) => item.position,
);
Expand Down
Loading

0 comments on commit 53fa129

Please sign in to comment.