Skip to content

Commit

Permalink
Rewrite lodash _each() as for ... of
Browse files Browse the repository at this point in the history
  • Loading branch information
jake-low committed Feb 26, 2025
1 parent a4666f9 commit 497ed36
Show file tree
Hide file tree
Showing 45 changed files with 427 additions and 445 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import _each from "lodash/each";
import _filter from "lodash/filter";
import _uniqBy from "lodash/uniqBy";
import { Component } from "react";
Expand All @@ -23,10 +22,16 @@ const WithChallengeResultParents = function (WrappedComponent) {
: this.props.projects;

const projectsWithChallengeSearchResults = new Set();
_each(this.props.filteredChallenges, (c) => {

for (const c of this.props.filteredChallenges) {
projectsWithChallengeSearchResults.add(c.parent);
_each(c.virtualParents, (vp) => projectsWithChallengeSearchResults.add(vp));
});

if (c.virtualParents) {
for (const vp of c.virtualParents) {
projectsWithChallengeSearchResults.add(vp);
}
}
}

// Include both project results and projects that have challenge results.
return _uniqBy(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import _each from "lodash/each";
import _toPairs from "lodash/toPairs";
import WithSearch from "../../../HOCs/WithSearch/WithSearch";

/**
Expand All @@ -18,10 +16,9 @@ import WithSearch from "../../../HOCs/WithSearch/WithSearch";
const WithComboSearch = (WrappedComponent, searches) => {
let Combo = WrappedComponent;

_each(
_toPairs(searches),
(searchConfig) => (Combo = WithSearch(Combo, searchConfig[0], searchConfig[1])),
);
for (const [searchName, searchFunction] of Object.entries(searches)) {
Combo = WithSearch(Combo, searchName, searchFunction);
}

return Combo;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import _each from "lodash/each";
import _fromPairs from "lodash/fromPairs";
import _isEmpty from "lodash/isEmpty";
import _isObject from "lodash/isObject";
import _map from "lodash/map";
import _values from "lodash/values";
import PropTypes from "prop-types";
import { Component } from "react";
import { TaskPriority } from "../../../../services/Task/TaskPriority/TaskPriority";
Expand All @@ -21,7 +19,7 @@ export default function (WrappedComponent) {
_fromPairs(_map(metrics, (value, label) => [label, (1.0 * value) / total]));

updateTotals = (actions, totalTasks, taskMetrics) => {
_each(actions, (value, label) => {
for (const [label, value] of Object.entries(actions)) {
if (label === "avgTimeSpent") {
taskMetrics.totalTimeSpent = Number.isFinite(taskMetrics.totalTimeSpent)
? taskMetrics.totalTimeSpent + value * actions.tasksWithTime
Expand All @@ -36,7 +34,7 @@ export default function (WrappedComponent) {
? taskMetrics.percentages[label] + percentage
: percentage;
}
});
}
};

render() {
Expand Down Expand Up @@ -72,7 +70,7 @@ export default function (WrappedComponent) {
taskMetricsByPriority.percentages = {};
taskMetricsByPriority.averages = {};

_each(_values(TaskPriority), (priority) => {
for (const priority of Object.values(TaskPriority)) {
taskMetricsByPriority[priority] = { percentages: {}, averages: {} };

for (let challenge of challenges) {
Expand All @@ -92,7 +90,7 @@ export default function (WrappedComponent) {
taskMetricsByPriority[priority].percentages,
totalChallenges,
);
});
}
}

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import _each from "lodash/each";
import _filter from "lodash/filter";
import _find from "lodash/find";
import _isObject from "lodash/isObject";
Expand Down Expand Up @@ -152,13 +151,15 @@ export const WithCurrentProject = function (WrappedComponent, options = {}) {
// the child challenges have parent projects that haven't been
// fetched yet. We need to fetch those so we can show their names.
const missingProjects = [];
_each(result?.entities?.challenges, (challenge) => {
if (!_isObject(challenge.parent)) {
if (!this.props.entities.projects[challenge.parent]) {
missingProjects.push(challenge.parent);
if (result?.entities?.challenges) {
for (const challenge of Object.values(result.entities.challenges)) {
if (!_isObject(challenge.parent)) {
if (!this.props.entities.projects[challenge.parent]) {
missingProjects.push(challenge.parent);
}
}
}
});
}
if (missingProjects.length > 0) {
this.props.fetchProjectsById(missingProjects);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import _each from "lodash/each";
import _isEqual from "lodash/isEqual";
import _omit from "lodash/omit";
import _values from "lodash/values";
Expand Down Expand Up @@ -59,11 +58,13 @@ const WithManageableProjects = function (WrappedComponent, includeChallenges = f
// Since we only fetched a small portion of the total projects in the
// database we need to make sure we also fetch the projects that are pinned.
let missingProjects = [];
_each(this.props.pinnedProjects, (pinnedProject) => {

for (const pinnedProject of this.props.pinnedProjects) {
if (!this.props.entities.projects[pinnedProject]) {
missingProjects.push(pinnedProject);
}
});
}

if (missingProjects.length > 0) {
this.props.fetchProjectsById(missingProjects);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import _cloneDeep from "lodash/cloneDeep";
import _each from "lodash/each";
import _fill from "lodash/fill";
import _filter from "lodash/filter";
import _isEmpty from "lodash/isEmpty";
Expand Down Expand Up @@ -127,24 +126,19 @@ export const WithTaskPropertyStyleRules = function (WrappedComponent) {

render() {
const errors = this.state.validationErrors;
_each(this.state.styleRules, (rule, index) => {
_each(rule.styles, (style) => {
for (const [index, rule] of this.state.styleRules.entries()) {
for (const style of rule.styles) {
if (style.styleName && !style.styleValue) {
// Missing style value
errors[index].push(PROPERTY_RULE_ERRORS.missingStyleValue);
} else if (style.styleValue && !style.styleName) {
// Missing syle name
errors[index].push(PROPERTY_RULE_ERRORS.missingStyleName);
}
});
});

let hasAnyStyleErrors = false;
_each(errors, (e) => {
if (!_isEmpty(e)) {
hasAnyStyleErrors = true;
}
});
}

let hasAnyStyleErrors = errors.some((e) => !_isEmpty(e));

return (
<WrappedComponent
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import idPresets from "@openstreetmap/id-tagging-schema/dist/preset_categories.json";
import _each from "lodash/each";
import _find from "lodash/find";
import _isEmpty from "lodash/isEmpty";
import _reduce from "lodash/reduce";
import _toPairs from "lodash/toPairs";

/**
* Prepares presets received from the server to the representation expected by
Expand Down Expand Up @@ -88,7 +85,9 @@ export const definedPresets = (challengeData, definedCategories) => {
* Remove preset category top-level fields from the challenge
*/
export const prunePresetCategories = (challengeData, activeCategories) => {
_each(activeCategories, (categoryName) => delete challengeData[categoryName]);
for (const categoryName of activeCategories) {
delete challengeData[categoryName];
}
};

/**
Expand All @@ -97,22 +96,22 @@ export const prunePresetCategories = (challengeData, activeCategories) => {
*/
export const categorizePresetStrings = (presetStrings) => {
const categorized = {};
_each(presetStrings, (preset) => {
// eslint-disable-next-line no-unused-vars
const parentCategory = _find(_toPairs(idPresets), ([categoryName, category]) => {
return category.members.indexOf(preset) !== -1;

for (const preset of presetStrings) {
const parentCategory = Object.entries(idPresets).find(([_, category]) => {
return category.members.includes(preset);
});

if (!parentCategory) {
return;
continue;
}

const categoryName = parentCategory[0];
if (!Array.isArray(categorized[categoryName])) {
categorized[categoryName] = [];
}
categorized[categoryName].push(preset);
});
}

return categorized;
};
10 changes: 5 additions & 5 deletions src/components/ChallengeProgress/ChallengeProgress.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ResponsiveBar } from "@nivo/bar";
import classNames from "classnames";
import _chunk from "lodash/chunk";
import _each from "lodash/each";
import _isEqual from "lodash/isEqual";
import _isObject from "lodash/isObject";
import _map from "lodash/map";
Expand Down Expand Up @@ -224,12 +223,13 @@ export class ChallengeProgress extends Component {

calculateChallengeStats(taskActions, orderedStatuses, localizedStatuses) {
let challengeStats = {};
_each(orderedStatuses, (status) => {

for (const status of orderedStatuses) {
challengeStats[localizedStatuses[keysByStatus[status]]] = {
count: taskActions[keysByStatus[status]],
percent: this.percent(taskActions[keysByStatus[status]], taskActions.total),
};
});
}

return challengeStats;
}
Expand All @@ -240,12 +240,12 @@ export class ChallengeProgress extends Component {
[availableLabel]: this.percent(taskActions.available, taskActions.total),
};

_each(orderedStatuses, (status) => {
for (const status of orderedStatuses) {
completionData[localizedStatuses[keysByStatus[status]]] = this.percent(
taskActions[keysByStatus[status]],
taskActions.total,
);
});
}

return completionData;
}
Expand Down
15 changes: 6 additions & 9 deletions src/components/CommentList/CommentList.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import classNames from "classnames";
import { parseISO } from "date-fns";
import _each from "lodash/each";
import _isObject from "lodash/isObject";
import _map from "lodash/map";
import _reverse from "lodash/reverse";
Expand Down Expand Up @@ -33,20 +32,18 @@ export default class CommentList extends Component {
// Show in descending order, with the most recent comment first.
let sortedComments = [];

if (this.props.comments?.length !== 0) {
commentDates = new Map();
_each(this.props.comments, (comment) =>
commentDates.set(comment.id, parseISO(comment.created)),
if (this.props.comments?.length > 0) {
commentDates = new Map(
this.props.comments.map((comment) => [comment.id, parseISO(comment.created)]),
);

// Show in descending order, with the most recent comment first.
sortedComments = _reverse(
_sortBy(this.props.comments, (comment) => commentDates.get(comment.id).getTime()),
);
} else {
commentDates = new Map();
_each(this.props.taskComments, (comment) =>
commentDates.set(comment.id, parseISO(comment.created)),
} else if (this.props.taskComments?.length > 0) {
commentDates = new Map(
this.props.taskComments.map((comment) => [comment.id, parseISO(comment.created)]),
);

// Show in descending order, with the most recent comment first.
Expand Down
15 changes: 6 additions & 9 deletions src/components/CountrySelector/CountrySelector.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import _each from "lodash/each";
import _map from "lodash/map";
import _sortBy from "lodash/sortBy";
import PropTypes from "prop-types";
import { Component } from "react";
import { FormattedMessage, injectIntl } from "react-intl";
Expand Down Expand Up @@ -63,14 +60,14 @@ const CountryButton = function (props) {
};

const ListCountryItems = function (props) {
const countryList = _sortBy(
_each(supportedCountries(), (country) => {
const countryList = supportedCountries()
.map((country) => {
country.name = props.intl.formatMessage(countryMessages[country.countryCode]);
}),
"name",
);
return country;
})
.sort((a, b) => a.name.localeCompare(b.name));

const menuItems = _map(countryList, (country) => (
const menuItems = countryList.map((country) => (
<li key={country.countryCode}>
<a onClick={() => props.pickCountry(country.countryCode, props.closeDropdown)}>
{country.name}
Expand Down
Loading

0 comments on commit 497ed36

Please sign in to comment.