Skip to content

Commit

Permalink
Use Object.values and Object.entries instead of Object.keys where useful
Browse files Browse the repository at this point in the history
  • Loading branch information
lukastaegert committed May 15, 2021
1 parent f4766a6 commit d5766d2
Show file tree
Hide file tree
Showing 19 changed files with 46 additions and 71 deletions.
4 changes: 1 addition & 3 deletions cli/run/build.ts
Expand Up @@ -24,9 +24,7 @@ export default async function build(
} else if (inputOptions.input instanceof Array) {
inputFiles = inputOptions.input.join(', ');
} else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
inputFiles = Object.keys(inputOptions.input)
.map(name => (inputOptions.input as Record<string, string>)[name])
.join(', ');
inputFiles = Object.values(inputOptions.input).join(', ');
}
stderr(cyan(`\n${bold(inputFiles!)}${bold(files.join(', '))}...`));
}
Expand Down
4 changes: 1 addition & 3 deletions cli/run/watch-cli.ts
Expand Up @@ -106,9 +106,7 @@ export async function watch(command: any) {
if (typeof input !== 'string') {
input = Array.isArray(input)
? input.join(', ')
: Object.keys(input as Record<string, string>)
.map(key => (input as Record<string, string>)[key])
.join(', ');
: Object.values(input as Record<string, string>).join(', ');
}
stderr(
cyan(`bundles ${bold(input)}${bold(event.output.map(relativeId).join(', '))}...`)
Expand Down
22 changes: 9 additions & 13 deletions src/Bundle.ts
Expand Up @@ -6,6 +6,7 @@ import {
GetManualChunk,
NormalizedInputOptions,
NormalizedOutputOptions,
OutputAsset,
OutputBundle,
OutputBundleWithPlaceholders,
OutputChunk,
Expand Down Expand Up @@ -41,11 +42,7 @@ export default class Bundle {
async generate(isWrite: boolean): Promise<OutputBundle> {
timeStart('GENERATE', 1);
const outputBundle: OutputBundleWithPlaceholders = Object.create(null);
this.pluginDriver.setOutputBundle(
outputBundle,
this.outputOptions,
this.facadeChunkByModule
);
this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
try {
await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);

Expand Down Expand Up @@ -104,9 +101,9 @@ export default class Bundle {
): Promise<Map<Module, string>> {
const manualChunkAliasByEntry = new Map<Module, string>();
const chunkEntries = await Promise.all(
Object.keys(manualChunks).map(async alias => ({
Object.entries(manualChunks).map(async ([alias, files]) => ({
alias,
entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
entries: await this.graph.moduleLoader.addAdditionalModules(files)
}))
);
for (const { alias, entries } of chunkEntries) {
Expand Down Expand Up @@ -169,24 +166,23 @@ export default class Bundle {
}

private finaliseAssets(outputBundle: OutputBundleWithPlaceholders): void {
for (const key of Object.keys(outputBundle)) {
const file = outputBundle[key] as any;
for (const file of Object.values(outputBundle)) {
if (!file.type) {
warnDeprecation(
'A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.',
true,
this.inputOptions
);
file.type = 'asset';
(file as OutputAsset).type = 'asset';
}
if (this.outputOptions.validate && typeof file.code == 'string') {
if (this.outputOptions.validate && typeof (file as OutputChunk).code == 'string') {
try {
this.graph.contextParse(file.code, {
this.graph.contextParse((file as OutputChunk).code, {
allowHashBang: true,
ecmaVersion: 'latest'
});
} catch (exception) {
this.inputOptions.onwarn(errChunkInvalid(file, exception));
this.inputOptions.onwarn(errChunkInvalid(file as OutputChunk, exception));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Chunk.ts
Expand Up @@ -1326,8 +1326,8 @@ export default class Chunk {
if (!this.outputOptions.preserveModules) {
if (this.includedNamespaces.has(module)) {
const memberVariables = module.namespace.getMemberVariables();
for (const name of Object.keys(memberVariables)) {
moduleImports.add(memberVariables[name]);
for (const variable of Object.values(memberVariables)) {
moduleImports.add(variable);
}
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/Graph.ts
Expand Up @@ -34,9 +34,9 @@ function normalizeEntryModules(
name: null
}));
}
return Object.keys(entryModules).map(name => ({
return Object.entries(entryModules).map(([name, id]) => ({
fileName: null,
id: entryModules[name],
id,
implicitlyLoadedAfter: [],
importer: undefined,
name
Expand Down Expand Up @@ -74,13 +74,14 @@ export default class Graph {
// increment access counter
for (const name in this.pluginCache) {
const cache = this.pluginCache[name];
for (const key of Object.keys(cache)) cache[key][0]++;
for (const value of Object.values(cache)) value[0]++;
}
}

if (watcher) {
this.watchMode = true;
const handleChange: WatchChangeHook = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
const handleChange: WatchChangeHook = (...args) =>
this.pluginDriver.hookSeqSync('watchChange', args);
const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
watcher.on('change', handleChange);
watcher.on('close', handleClose);
Expand Down Expand Up @@ -118,9 +119,9 @@ export default class Graph {

if (onCommentOrig && typeof onCommentOrig == 'function') {
options.onComment = (block, text, start, end, ...args) => {
comments.push({type: block ? "Block" : "Line", value: text, start, end});
comments.push({ type: block ? 'Block' : 'Line', value: text, start, end });
return onCommentOrig.call(options, block, text, start, end, ...args);
}
};
} else {
options.onComment = comments;
}
Expand All @@ -146,8 +147,8 @@ export default class Graph {
for (const name in this.pluginCache) {
const cache = this.pluginCache[name];
let allDeleted = true;
for (const key of Object.keys(cache)) {
if (cache[key][0] >= this.options.experimentalCacheExpiry) delete cache[key];
for (const [key, value] of Object.entries(cache)) {
if (value[0] >= this.options.experimentalCacheExpiry) delete cache[key];
else allDeleted = false;
}
if (allDeleted) delete this.pluginCache[name];
Expand Down Expand Up @@ -238,8 +239,7 @@ export default class Graph {

private warnForMissingExports() {
for (const module of this.modules) {
for (const importName of Object.keys(module.importDescriptions)) {
const importDescription = module.importDescriptions[importName];
for (const importDescription of Object.values(module.importDescriptions)) {
if (
importDescription.name !== '*' &&
!(importDescription.module as Module).getVariableForExportName(importDescription.name)
Expand Down
3 changes: 1 addition & 2 deletions src/Module.ts
Expand Up @@ -1002,8 +1002,7 @@ export default class Module {
private addModulesToImportDescriptions(importDescription: {
[name: string]: ImportDescription | ReexportDescription;
}) {
for (const name of Object.keys(importDescription)) {
const specifier = importDescription[name];
for (const specifier of Object.values(importDescription)) {
const id = this.resolvedIds[specifier.source].id;
specifier.module = this.graph.modulesById.get(id)!;
}
Expand Down
2 changes: 1 addition & 1 deletion src/ast/keys.ts
Expand Up @@ -9,7 +9,7 @@ export const keys: {

export function getAndCreateKeys(esTreeNode: GenericEsTreeNode) {
keys[esTreeNode.type] = Object.keys(esTreeNode).filter(
key => key !== '_rollupAnnotations' && typeof esTreeNode[key] === 'object'
key => typeof esTreeNode[key] === 'object' && key !== '_rollupAnnotations'
);
return keys[esTreeNode.type];
}
4 changes: 0 additions & 4 deletions src/ast/nodes/shared/ClassNode.ts
Expand Up @@ -21,14 +21,10 @@ import { ObjectEntity, ObjectProperty } from './ObjectEntity';
import { ObjectMember } from './ObjectMember';
import { OBJECT_PROTOTYPE } from './ObjectPrototype';

// TODO Lukas
// * __proto__ assignment handling might be possible solely via the object prototype? But it would need to deoptimize the entire prototype chain: Bad. Better we always replace the prototype with "unknown" on assigment
// * __proto__: foo handling however is an ObjectExpression feature
export default class ClassNode extends NodeBase implements DeoptimizableEntity {
body!: ClassBody;
id!: Identifier | null;
superClass!: ExpressionNode | null;

private classConstructor!: MethodDefinition | null;
private objectEntity: ObjectEntity | null = null;

Expand Down
3 changes: 0 additions & 3 deletions src/ast/nodes/shared/FunctionNode.ts
Expand Up @@ -13,15 +13,13 @@ import { ObjectEntity } from './ObjectEntity';
import { OBJECT_PROTOTYPE } from './ObjectPrototype';
import { PatternNode } from './Pattern';

// TODO Lukas improve prototype handling to fix #2219
export default class FunctionNode extends NodeBase {
async!: boolean;
body!: BlockStatement;
id!: IdentifierWithVariable | null;
params!: PatternNode[];
preventChildBlockScope!: true;
scope!: FunctionScope;

private isPrototypeDeoptimized = false;

createScope(parentScope: FunctionScope) {
Expand All @@ -42,7 +40,6 @@ export default class FunctionNode extends NodeBase {
}
}

// TODO Lukas handle other event types as well
deoptimizeThisOnEventAtPath(event: NodeEvent, path: ObjectPath, thisParameter: ExpressionEntity) {
if (event === EVENT_CALLED) {
if (path.length > 0 ) {
Expand Down
1 change: 0 additions & 1 deletion src/ast/nodes/shared/MethodBase.ts
Expand Up @@ -22,7 +22,6 @@ export default class MethodBase extends NodeBase implements DeoptimizableEntity
private accessedValue: ExpressionEntity | null = null;
private accessorCallOptions: CallOptions = {
args: NO_ARGS,
// TODO Lukas in the end, handle this differently or get rid of the shared call options
thisParam: null,
withNew: false
};
Expand Down
1 change: 0 additions & 1 deletion src/ast/nodes/shared/MethodTypes.ts
Expand Up @@ -76,7 +76,6 @@ export class Method extends ExpressionEntity {
EMPTY_PATH,
{
args: NO_ARGS,
// TODO Lukas check if we need something else here
thisParam: null,
withNew: false
},
Expand Down
3 changes: 1 addition & 2 deletions src/ast/nodes/shared/Node.ts
Expand Up @@ -195,10 +195,9 @@ export class NodeBase extends ExpressionEntity implements ExpressionNode {
}

parseNode(esTreeNode: GenericEsTreeNode) {
for (const key of Object.keys(esTreeNode)) {
for (const [key, value] of Object.entries(esTreeNode)) {
// That way, we can override this function to add custom initialisation and then call super.parseNode
if (this.hasOwnProperty(key)) continue;
const value = esTreeNode[key];
if (key === '_rollupAnnotations') {
this.annotations = value;
} else if (typeof value !== 'object' || value === null) {
Expand Down
5 changes: 2 additions & 3 deletions src/ast/nodes/shared/ObjectEntity.ts
Expand Up @@ -85,9 +85,9 @@ export class ObjectEntity extends ExpressionEntity {
return;
}
this.hasUnknownDeoptimizedInteger = true;
for (const key of Object.keys(this.propertiesAndGettersByKey)) {
for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
if (INTEGER_REG_EXP.test(key)) {
for (const property of this.propertiesAndGettersByKey[key]) {
for (const property of propertiesAndGetters) {
property.deoptimizePath(UNKNOWN_PATH);
}
}
Expand Down Expand Up @@ -421,7 +421,6 @@ export class ObjectEntity extends ExpressionEntity {
}
}

// TODO Lukas check everywhere if we can replace Object.keys with Object.entries/values
private deoptimizeCachedIntegerEntities() {
for (const [key, expressionsToBeDeoptimized] of Object.entries(
this.expressionsToBeDeoptimizedByKey
Expand Down
4 changes: 1 addition & 3 deletions src/ast/variables/NamespaceVariable.ts
Expand Up @@ -66,9 +66,7 @@ export default class NamespaceVariable extends Variable {
const t = options.indent;

const memberVariables = this.getMemberVariables();
const members = Object.keys(memberVariables).map(name => {
const original = memberVariables[name];

const members = Object.entries(memberVariables).map(([name, original]) => {
if (this.referencedEarly || original.isReassigned) {
return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${
options.compact ? '' : ';'
Expand Down
13 changes: 4 additions & 9 deletions src/rollup/rollup.ts
Expand Up @@ -170,9 +170,7 @@ async function handleGenerateWrite(
message: 'You must specify "output.file" or "output.dir" for the build.'
});
}
await Promise.all(
Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions))
);
await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions)));
await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
}
return createOutput(generated);
Expand Down Expand Up @@ -228,12 +226,9 @@ function getOutputOptions(

function createOutput(outputBundle: Record<string, OutputChunk | OutputAsset | {}>): RollupOutput {
return {
output: (Object.keys(outputBundle)
.map(fileName => outputBundle[fileName])
.filter(outputFile => Object.keys(outputFile).length > 0) as (
| OutputChunk
| OutputAsset
)[]).sort((outputFileA, outputFileB) => {
output: (Object.values(outputBundle).filter(
outputFile => Object.keys(outputFile).length > 0
) as (OutputChunk | OutputAsset)[]).sort((outputFileA, outputFileB) => {
const fileTypeA = getSortingFileType(outputFileA);
const fileTypeB = getSortingFileType(outputFileB);
if (fileTypeA === fileTypeB) return 0;
Expand Down
10 changes: 6 additions & 4 deletions src/utils/FileEmitter.ts
Expand Up @@ -106,9 +106,12 @@ function hasValidType(
);
}

function hasValidName(emittedFile: { type: 'asset' | 'chunk'; [key: string]: unknown; }): emittedFile is EmittedFile {
function hasValidName(emittedFile: {
type: 'asset' | 'chunk';
[key: string]: unknown;
}): emittedFile is EmittedFile {
const validatedName = emittedFile.fileName || emittedFile.name;
return !validatedName || typeof validatedName === 'string' && !isPathFragment(validatedName);
return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
}

function getValidSource(
Expand Down Expand Up @@ -351,8 +354,7 @@ function findExistingAssetFileNameWithSource(
bundle: OutputBundleWithPlaceholders,
source: string | Uint8Array
): string | null {
for (const fileName of Object.keys(bundle)) {
const outputFile = bundle[fileName];
for (const [fileName, outputFile] of Object.entries(bundle)) {
if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source)) return fileName;
}
return null;
Expand Down
4 changes: 2 additions & 2 deletions src/utils/chunkAssignment.ts
Expand Up @@ -185,8 +185,8 @@ function createChunks(
chunkModules[chunkSignature] = [module];
}
}
return Object.keys(chunkModules).map(chunkSignature => ({
return Object.values(chunkModules).map(modules => ({
alias: null,
modules: chunkModules[chunkSignature]
modules
}));
}
4 changes: 2 additions & 2 deletions src/utils/options/normalizeInputOptions.ts
Expand Up @@ -187,8 +187,8 @@ const getModuleContext = (
}
if (configModuleContext) {
const contextByModuleId = Object.create(null);
for (const key of Object.keys(configModuleContext)) {
contextByModuleId[resolve(key)] = configModuleContext[key];
for (const [key, moduleContext] of Object.entries(configModuleContext)) {
contextByModuleId[resolve(key)] = moduleContext;
}
return id => contextByModuleId[id] || context;
}
Expand Down
6 changes: 3 additions & 3 deletions src/utils/timers.ts
Expand Up @@ -76,8 +76,8 @@ function timeEndImpl(label: string, level = 3) {

export function getTimings(): SerializedTimings {
const newTimings: SerializedTimings = {};
for (const label of Object.keys(timers)) {
newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
for (const [label, { time, memory, totalMemory }] of Object.entries(timers)) {
newTimings[label] = [time, memory, totalMemory];
}
return newTimings;
}
Expand All @@ -102,7 +102,7 @@ function getPluginWithTimers(plugin: any, index: number): Plugin {
timerLabel += ` (${plugin.name})`;
}
timerLabel += ` - ${hook}`;
timedPlugin[hook] = function() {
timedPlugin[hook] = function () {
timeStart(timerLabel, 4);
let result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
timeEnd(timerLabel, 4);
Expand Down

0 comments on commit d5766d2

Please sign in to comment.