Use Object.fromEntries(), Array#flat() and Array#flatMap() (#10853)

This commit is contained in:
fisker Cheung authored and GitHub committed 2021-05-12 01:05:29 +08:00
1 parent b7983971ce
commit 98abb990cc
23 files changed
+85 -83

No files matched your search

+8
View File
@@ -75,6 +75,12 @@ rules:
unicorn/no-array-for-each: error unicorn/no-array-for-each: error
unicorn/no-array-push-push: error unicorn/no-array-push-push: error
unicorn/no-useless-undefined: error unicorn/no-useless-undefined: error
unicorn/prefer-array-flat:
- error
- functions:
- flat
- flatten
unicorn/prefer-array-flat-map: error
unicorn/prefer-includes: error unicorn/prefer-includes: error
unicorn/prefer-number-properties: error unicorn/prefer-number-properties: error
unicorn/prefer-optional-catch-binding: error unicorn/prefer-optional-catch-binding: error
@@ -106,6 +112,8 @@ overrides:
- tests/**/*.js - tests/**/*.js
rules: rules:
strict: off strict: off
unicorn/prefer-array-flat: off
unicorn/prefer-array-flat-map: off
globals: globals:
run_spec: false run_spec: false
- files: - files:
+2 -1
View File
@@ -70,6 +70,7 @@
"commonmark", "commonmark",
"concating", "concating",
"cond", "cond",
"corejs",
"cosmiconfig", "cosmiconfig",
"CRLFs", "CRLFs",
"crossorigin", "crossorigin",
@@ -316,10 +317,10 @@
"readlines", "readlines",
"rebalance", "rebalance",
"rebeccapurple", "rebeccapurple",
"Redeclaration",
"Rects", "Rects",
"recurse", "recurse",
"recurses", "recurses",
"Redeclaration",
"refmt", "refmt",
"regexes", "regexes",
"Reimplement", "Reimplement",
+1
View File
@@ -103,6 +103,7 @@
"babel-loader": "8.2.2", "babel-loader": "8.2.2",
"benchmark": "2.1.4", "benchmark": "2.1.4",
"builtin-modules": "3.2.0", "builtin-modules": "3.2.0",
"core-js": "3.12.1",
"cross-env": "7.0.3", "cross-env": "7.0.3",
"cspell": "4.2.8", "cspell": "4.2.8",
"eslint": "7.26.0", "eslint": "7.26.0",
+1 -1
View File
@@ -22,7 +22,7 @@ process.on("unhandledRejection", (err) => {
process.exit(1); process.exit(1);
}); });
const CACHE_VERSION = "v32"; // This need update when updating build scripts const CACHE_VERSION = "v33"; // This need update when updating build scripts
const statusConfig = [ const statusConfig = [
{ color: "bgYellow", text: "CACHED" }, { color: "bgYellow", text: "CACHED" },
{ color: "bgGreen", text: "DONE" }, { color: "bgGreen", text: "DONE" },
+17 -1
View File
@@ -83,8 +83,10 @@ function webpackNativeShims(config, modules) {
function getBabelConfig(bundle) { function getBabelConfig(bundle) {
const config = { const config = {
babelrc: false, babelrc: false,
sourceType: "unambiguous",
plugins: bundle.babelPlugins || [], plugins: bundle.babelPlugins || [],
compact: bundle.type === "plugin" ? false : "auto", compact: bundle.type === "plugin" ? false : "auto",
exclude: [/\/core-js\//],
}; };
if (bundle.type === "core") { if (bundle.type === "core") {
config.plugins.push( config.plugins.push(
@@ -105,8 +107,22 @@ function getBabelConfig(bundle) {
require.resolve("@babel/preset-env"), require.resolve("@babel/preset-env"),
{ {
targets, targets,
exclude: ["transform-async-to-generator"], exclude: [
"es.array.unscopables.flat-map",
"es.promise",
"es.promise.finally",
"es.string.replace",
"es.symbol.description",
"es.typed-array.*",
"transform-async-to-generator",
"web.*",
],
modules: false, modules: false,
useBuiltIns: "usage",
corejs: {
version: 3,
},
debug: false,
}, },
], ],
]; ];
+1 -2
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
"use strict"; "use strict";
const fromPairs = require("lodash/fromPairs");
if (require.main !== module) { if (require.main !== module) {
module.exports = generateSchema; module.exports = generateSchema;
@@ -22,7 +21,7 @@ function generateSchema(options) {
definitions: { definitions: {
optionsDefinition: { optionsDefinition: {
type: "object", type: "object",
properties: fromPairs( properties: Object.fromEntries(
options.map((option) => [option.name, optionToSchema(option)]) options.map((option) => [option.name, optionToSchema(option)])
), ),
}, },
+1 -2
View File
@@ -1,5 +1,4 @@
"use strict"; "use strict";
const fromPairs = require("lodash/fromPairs");
const pick = require("lodash/pick"); const pick = require("lodash/pick");
// eslint-disable-next-line no-restricted-modules // eslint-disable-next-line no-restricted-modules
@@ -92,7 +91,7 @@ function getContextOptions(plugins, pluginSearchDirs) {
const apiDefaultOptions = { const apiDefaultOptions = {
...optionsModule.hiddenDefaults, ...optionsModule.hiddenDefaults,
...fromPairs( ...Object.fromEntries(
supportOptions supportOptions
.filter(({ deprecated }) => !deprecated) .filter(({ deprecated }) => !deprecated)
.map((option) => [option.name, option.default]) .map((option) => [option.name, option.default])
+3 -5
View File
@@ -1,20 +1,18 @@
"use strict"; "use strict";
const partition = require("lodash/partition"); const partition = require("lodash/partition");
const flat = require("lodash/flatten");
const fromPairs = require("lodash/fromPairs");
module.exports = function createMinimistOptions(detailedOptions) { module.exports = function createMinimistOptions(detailedOptions) {
const [boolean, string] = partition( const [boolean, string] = partition(
detailedOptions, detailedOptions,
({ type }) => type === "boolean" ({ type }) => type === "boolean"
).map((detailedOptions) => ).map((detailedOptions) =>
flat( detailedOptions.flatMap(({ name, alias }) =>
detailedOptions.map(({ name, alias }) => (alias ? [name, alias] : [name])) alias ? [name, alias] : [name]
) )
); );
const defaults = fromPairs( const defaults = Object.fromEntries(
detailedOptions detailedOptions
.filter( .filter(
(option) => (option) =>
+4 -5
View File
@@ -3,7 +3,6 @@
const path = require("path"); const path = require("path");
const fs = require("fs"); const fs = require("fs");
const fastGlob = require("fast-glob"); const fastGlob = require("fast-glob");
const flat = require("lodash/flatten");
/** @typedef {import('./context').Context} Context */ /** @typedef {import('./context').Context} Context */
@@ -121,11 +120,11 @@ async function* expandPatternsInternal(context) {
function getSupportedFilesGlob() { function getSupportedFilesGlob() {
if (!supportedFilesGlob) { if (!supportedFilesGlob) {
const extensions = flat( const extensions = context.languages.flatMap(
context.languages.map((lang) => lang.extensions || []) (lang) => lang.extensions || []
); );
const filenames = flat( const filenames = context.languages.flatMap(
context.languages.map((lang) => lang.filenames || []) (lang) => lang.filenames || []
); );
supportedFilesGlob = `**/{${[ supportedFilesGlob = `**/{${[
...extensions.map((ext) => "*" + (ext[0] === "." ? ext : "." + ext)), ...extensions.map((ext) => "*" + (ext[0] === "." ? ext : "." + ext)),
+4 -3
View File
@@ -1,7 +1,6 @@
"use strict"; "use strict";
const minimist = require("minimist"); const minimist = require("minimist");
const fromPairs = require("lodash/fromPairs");
const PLACEHOLDER = null; const PLACEHOLDER = null;
@@ -15,12 +14,14 @@ module.exports = function (args, options) {
const booleanWithoutDefault = boolean.filter((key) => !(key in defaults)); const booleanWithoutDefault = boolean.filter((key) => !(key in defaults));
const newDefaults = { const newDefaults = {
...defaults, ...defaults,
...fromPairs(booleanWithoutDefault.map((key) => [key, PLACEHOLDER])), ...Object.fromEntries(
booleanWithoutDefault.map((key) => [key, PLACEHOLDER])
),
}; };
const parsed = minimist(args, { ...options, default: newDefaults }); const parsed = minimist(args, { ...options, default: newDefaults });
return fromPairs( return Object.fromEntries(
Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER) Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER)
); );
}; };
+2 -5
View File
@@ -1,9 +1,6 @@
"use strict"; "use strict";
const dashify = require("dashify"); const dashify = require("dashify");
const fromPairs = require("lodash/fromPairs");
const { coreOptions } = require("./prettier-internal"); const { coreOptions } = require("./prettier-internal");
function normalizeDetailedOption(name, option) { function normalizeDetailedOption(name, option) {
@@ -28,7 +25,7 @@ function normalizeDetailedOption(name, option) {
} }
function normalizeDetailedOptionMap(detailedOptionMap) { function normalizeDetailedOptionMap(detailedOptionMap) {
return fromPairs( return Object.fromEntries(
Object.entries(detailedOptionMap) Object.entries(detailedOptionMap)
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName)) .sort(([leftName], [rightName]) => leftName.localeCompare(rightName))
.map(([name, option]) => [name, normalizeDetailedOption(name, option)]) .map(([name, option]) => [name, normalizeDetailedOption(name, option)])
@@ -36,7 +33,7 @@ function normalizeDetailedOptionMap(detailedOptionMap) {
} }
function createDetailedOptionMap(supportOptions) { function createDetailedOptionMap(supportOptions) {
return fromPairs( return Object.fromEntries(
supportOptions.map((option) => { supportOptions.map((option) => {
const newOption = { const newOption = {
...option, ...option,
+3 -7
View File
@@ -1,18 +1,14 @@
"use strict"; "use strict";
const dashify = require("dashify"); const dashify = require("dashify");
const fromPairs = require("lodash/fromPairs");
// eslint-disable-next-line no-restricted-modules // eslint-disable-next-line no-restricted-modules
const prettier = require("../index"); const prettier = require("../index");
const minimist = require("./minimist"); const minimist = require("./minimist");
const { optionsNormalizer } = require("./prettier-internal"); const { optionsNormalizer } = require("./prettier-internal");
const createMinimistOptions = require("./create-minimist-options"); const createMinimistOptions = require("./create-minimist-options");
function getOptions(argv, detailedOptions) { function getOptions(argv, detailedOptions) {
return fromPairs( return Object.fromEntries(
detailedOptions detailedOptions
.filter(({ forwardToApi }) => forwardToApi) .filter(({ forwardToApi }) => forwardToApi)
.map(({ forwardToApi, name }) => [forwardToApi, argv[name]]) .map(({ forwardToApi, name }) => [forwardToApi, argv[name]])
@@ -20,7 +16,7 @@ function getOptions(argv, detailedOptions) {
} }
function cliifyOptions(object, apiDetailedOptionMap) { function cliifyOptions(object, apiDetailedOptionMap) {
return fromPairs( return Object.fromEntries(
Object.entries(object || {}).map(([key, value]) => { Object.entries(object || {}).map(([key, value]) => {
const apiOption = apiDetailedOptionMap[key]; const apiOption = apiDetailedOptionMap[key];
const cliKey = apiOption ? apiOption.name : key; const cliKey = apiOption ? apiOption.name : key;
@@ -31,7 +27,7 @@ function cliifyOptions(object, apiDetailedOptionMap) {
} }
function createApiDetailedOptionMap(detailedOptions) { function createApiDetailedOptionMap(detailedOptions) {
return fromPairs( return Object.fromEntries(
detailedOptions detailedOptions
.filter( .filter(
(option) => option.forwardToApi && option.forwardToApi !== option.name (option) => option.forwardToApi && option.forwardToApi !== option.name
+1 -2
View File
@@ -1,7 +1,6 @@
"use strict"; "use strict";
const groupBy = require("lodash/groupBy"); const groupBy = require("lodash/groupBy");
const flat = require("lodash/flatten");
const camelCase = require("camelcase"); const camelCase = require("camelcase");
const constant = require("./constant"); const constant = require("./constant");
@@ -112,7 +111,7 @@ function getOptionsWithOpposites(options) {
} }
: null, : null,
]); ]);
return flat(optionsWithOpposites).filter(Boolean); return optionsWithOpposites.flat().filter(Boolean);
} }
function createUsage(context) { function createUsage(context) {
+3 -4
View File
@@ -4,7 +4,6 @@ const fs = require("fs");
const path = require("path"); const path = require("path");
const uniqBy = require("lodash/uniqBy"); const uniqBy = require("lodash/uniqBy");
const partition = require("lodash/partition"); const partition = require("lodash/partition");
const flatten = require("lodash/flatten");
const globby = require("globby"); const globby = require("globby");
const mem = require("mem"); const mem = require("mem");
const internalPlugins = require("../languages"); const internalPlugins = require("../languages");
@@ -57,8 +56,8 @@ function load(plugins, pluginSearchDirs) {
} }
); );
const externalAutoLoadPluginInfos = flatten( const externalAutoLoadPluginInfos = pluginSearchDirs.flatMap(
pluginSearchDirs.map((pluginSearchDir) => { (pluginSearchDir) => {
const resolvedPluginSearchDir = path.resolve( const resolvedPluginSearchDir = path.resolve(
process.cwd(), process.cwd(),
pluginSearchDir pluginSearchDir
@@ -85,7 +84,7 @@ function load(plugins, pluginSearchDirs) {
name: pluginName, name: pluginName,
requirePath: resolve(pluginName, { paths: [resolvedPluginSearchDir] }), requirePath: resolve(pluginName, { paths: [resolvedPluginSearchDir] }),
})); }));
}) }
); );
const externalPlugins = [ const externalPlugins = [
+2 -3
View File
@@ -1,6 +1,5 @@
"use strict"; "use strict";
const fromPairs = require("lodash/fromPairs");
const { isNonEmptyArray } = require("../common/util"); const { isNonEmptyArray } = require("../common/util");
const getLast = require("../utils/get-last"); const getLast = require("../utils/get-last");
@@ -28,7 +27,7 @@ class Node {
this[key] = cloneAndUpdateNodes(nodes, this); this[key] = cloneAndUpdateNodes(nodes, this);
if (key === "attrs") { if (key === "attrs") {
setNonEnumerableProperties(this, { setNonEnumerableProperties(this, {
attrMap: fromPairs( attrMap: Object.fromEntries(
this[key].map((attr) => [attr.fullName, attr.value]) this[key].map((attr) => [attr.fullName, attr.value])
), ),
}); });
@@ -134,7 +133,7 @@ function cloneAndUpdateNodes(nodes, parent) {
} }
function setNonEnumerableProperties(obj, props) { function setNonEnumerableProperties(obj, props) {
const descriptors = fromPairs( const descriptors = Object.fromEntries(
Object.entries(props).map(([key, value]) => [ Object.entries(props).map(([key, value]) => [
key, key,
{ value, enumerable: false }, { value, enumerable: false },
+10 -14
View File
@@ -1,22 +1,18 @@
"use strict"; "use strict";
const htmlStyles = require("html-styles"); const htmlStyles = require("html-styles");
const fromPairs = require("lodash/fromPairs");
const flat = require("lodash/flatten");
const getCssStyleTags = (property) => const getCssStyleTags = (property) =>
fromPairs( Object.fromEntries(
flat( htmlStyles
htmlStyles .filter((htmlStyle) => htmlStyle.style[property])
.filter((htmlStyle) => htmlStyle.style[property]) .flatMap((htmlStyle) =>
.map((htmlStyle) => htmlStyle.selectorText
htmlStyle.selectorText .split(",")
.split(",") .map((selector) => selector.trim())
.map((selector) => selector.trim()) .filter((selector) => /^[\dA-Za-z]+$/.test(selector))
.filter((selector) => /^[\dA-Za-z]+$/.test(selector)) .map((tagName) => [tagName, htmlStyle.style[property]])
.map((tagName) => [tagName, htmlStyle.style[property]]) )
)
)
); );
const CSS_DISPLAY_TAGS = { const CSS_DISPLAY_TAGS = {
+5 -8
View File
@@ -1,6 +1,5 @@
"use strict"; "use strict";
const flatten = require("lodash/flatten");
const tryCombinations = require("../utils/try-combinations"); const tryCombinations = require("../utils/try-combinations");
const { const {
getNextNonSpaceNonCommentCharacterIndexWithStartIndex, getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
@@ -106,13 +105,11 @@ function createParse(parseMethod, ...optionsCombinations) {
} }
if (text.includes("|>")) { if (text.includes("|>")) {
combinations = flatten( combinations = pipelineOperatorPlugins.flatMap((pipelineOperatorPlugin) =>
pipelineOperatorPlugins.map((pipelineOperatorPlugin) => combinations.map((options) => ({
combinations.map((options) => ({ ...options,
...options, plugins: [...options.plugins, pipelineOperatorPlugin],
plugins: [...options.plugins, pipelineOperatorPlugin], }))
}))
)
); );
} }
+1 -3
View File
@@ -1,7 +1,5 @@
"use strict"; "use strict";
const flat = require("lodash/flatten");
const { printComments } = require("../../main/comments"); const { printComments } = require("../../main/comments");
const { const {
getLast, getLast,
@@ -327,7 +325,7 @@ function printMemberChain(path, options, print) {
const oneLine = printedGroups; const oneLine = printedGroups;
const cutoff = shouldMerge ? 3 : 2; const cutoff = shouldMerge ? 3 : 2;
const flatGroups = flat(groups); const flatGroups = groups.flat();
const nodeHasComment = const nodeHasComment =
flatGroups flatGroups
+2 -3
View File
@@ -1,6 +1,5 @@
"use strict"; "use strict";
const flat = require("lodash/flatten");
const { hasNewlineInRange } = require("../../common/util"); const { hasNewlineInRange } = require("../../common/util");
const { const {
isJsxNode, isJsxNode,
@@ -304,13 +303,13 @@ function printTernary(path, options, print) {
// We want a whole chain of ConditionalExpressions to all // We want a whole chain of ConditionalExpressions to all
// break if any of them break. That means we should only group around the // break if any of them break. That means we should only group around the
// outer-most ConditionalExpression. // outer-most ConditionalExpression.
const comments = flat([ const comments = [
...testNodePropertyNames.map((propertyName) => ...testNodePropertyNames.map((propertyName) =>
getComments(node[propertyName]) getComments(node[propertyName])
), ),
getComments(consequentNode), getComments(consequentNode),
getComments(alternateNode), getComments(alternateNode),
]); ].flat();
const shouldBreak = comments.some( const shouldBreak = comments.some(
(comment) => (comment) =>
isBlockComment(comment) && isBlockComment(comment) &&
+6 -9
View File
@@ -3,7 +3,6 @@
const vnopts = require("vnopts"); const vnopts = require("vnopts");
const leven = require("leven"); const leven = require("leven");
const chalk = require("chalk"); const chalk = require("chalk");
const flat = require("lodash/flatten");
const getLast = require("../utils/get-last"); const getLast = require("../utils/get-last");
const cliDescriptor = { const cliDescriptor = {
@@ -148,14 +147,12 @@ function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) {
break; break;
case "flag": case "flag":
SchemaConstructor = FlagSchema; SchemaConstructor = FlagSchema;
parameters.flags = flat( parameters.flags = optionInfos.flatMap((optionInfo) =>
optionInfos.map((optionInfo) => [
[ optionInfo.alias,
optionInfo.alias, optionInfo.description && optionInfo.name,
optionInfo.description && optionInfo.name, optionInfo.oppositeDescription && `no-${optionInfo.name}`,
optionInfo.oppositeDescription && `no-${optionInfo.name}`, ].filter(Boolean)
].filter(Boolean)
)
); );
break; break;
case "path": case "path":
+2 -3
View File
@@ -3,7 +3,6 @@
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const readlines = require("n-readlines"); const readlines = require("n-readlines");
const fromPairs = require("lodash/fromPairs");
const { UndefinedParserError } = require("../common/errors"); const { UndefinedParserError } = require("../common/errors");
const { getSupportInfo } = require("../main/support"); const { getSupportInfo } = require("../main/support");
const normalizer = require("./options-normalizer"); const normalizer = require("./options-normalizer");
@@ -29,7 +28,7 @@ function normalize(options, opts = {}) {
const defaults = { const defaults = {
...hiddenDefaults, ...hiddenDefaults,
...fromPairs( ...Object.fromEntries(
supportOptions supportOptions
.filter((optionInfo) => optionInfo.default !== undefined) .filter((optionInfo) => optionInfo.default !== undefined)
.map((option) => [option.name, option.default]) .map((option) => [option.name, option.default])
@@ -68,7 +67,7 @@ function normalize(options, opts = {}) {
const plugin = getPlugin(rawOptions); const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat]; rawOptions.printer = plugin.printers[rawOptions.astFormat];
const pluginDefaults = fromPairs( const pluginDefaults = Object.fromEntries(
supportOptions supportOptions
.filter( .filter(
(optionInfo) => (optionInfo) =>
+1 -2
View File
@@ -1,6 +1,5 @@
"use strict"; "use strict";
const fromPairs = require("lodash/fromPairs");
const semver = { const semver = {
compare: require("semver/functions/compare"), compare: require("semver/functions/compare"),
lt: require("semver/functions/lt"), lt: require("semver/functions/lt"),
@@ -65,7 +64,7 @@ function getSupportInfo({
} }
} }
const pluginDefaults = fromPairs( const pluginDefaults = Object.fromEntries(
plugins plugins
.filter( .filter(
(plugin) => (plugin) =>
+5
View File
@@ -2585,6 +2585,11 @@ core-js-compat@^3.9.0, core-js-compat@^3.9.1:
browserslist "^4.16.3" browserslist "^4.16.3"
semver "7.0.0" semver "7.0.0"
core-js@3.12.1:
version "3.12.1"
resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.12.1.tgz#6b5af4ff55616c08a44d386f1f510917ff204112"
integrity sha512-Ne9DKPHTObRuB09Dru5AjwKjY4cJHVGu+y5f7coGn1E9Grkc3p2iBwE9AI/nJzsE29mQF7oq+mhYYRqOMFN1Bw==
core-util-is@1.0.2, core-util-is@^1.0.2: core-util-is@1.0.2, core-util-is@^1.0.2:
version "1.0.2" version "1.0.2"
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"