Skip to content

Commit

Permalink
Bump ESLint version to add prefer-at condition
Browse files Browse the repository at this point in the history
  • Loading branch information
ShridharGoel committed Aug 16, 2024
1 parent a07cce4 commit cadeafa
Show file tree
Hide file tree
Showing 195 changed files with 794 additions and 768 deletions.
6 changes: 6 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,5 +289,11 @@ module.exports = {
'rulesdir/use-periods-for-error-messages': 'error',
},
},
{
files: ['*.ts', '*.tsx'],
rules: {
'rulesdir/prefer-at': 'error',
},
},
],
};
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function partitionWithChecklist(body: string): string[] {
async function getNumberOfItemsFromAuthorChecklist(): Promise<number> {
const response = await fetch(pathToAuthorChecklist);
const fileContents = await response.text();
const checklist = partitionWithChecklist(fileContents)[1];
const checklist = partitionWithChecklist(fileContents).at(1);
const numberOfChecklistItems = (checklist.match(/\[ \]/g) ?? []).length;
return numberOfChecklistItems;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ async function run(): Promise<IssuesCreateResponse | void> {

// Look at the state of the most recent StagingDeployCash,
// if it is open then we'll update the existing one, otherwise, we'll create a new one.
const mostRecentChecklist = recentDeployChecklists[0];
const mostRecentChecklist = recentDeployChecklists.at(0);
const shouldCreateNewDeployChecklist = mostRecentChecklist.state !== 'open';
const previousChecklist = shouldCreateNewDeployChecklist ? mostRecentChecklist : recentDeployChecklists[1];
const previousChecklist = shouldCreateNewDeployChecklist ? mostRecentChecklist : recentDeployChecklists.at(1);
if (shouldCreateNewDeployChecklist) {
console.log('Latest StagingDeployCash is closed, creating a new one.', mostRecentChecklist);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async function run() {
labels: CONST.LABELS.STAGING_DEPLOY,
state: 'closed',
});
const previousChecklistID = deployChecklists[0].number;
const previousChecklistID = deployChecklists.at(0).number;

// who closed the last deploy checklist?
const deployer = await GithubUtils.getActorWhoClosedIssue(previousChecklistID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ async function run() {
if (assistantResponse.includes(`[${CONST.NO_ACTION}]`)) {
// extract the text after [NO_ACTION] from assistantResponse since this is a
// bot related action keyword
const noActionContext = assistantResponse.split(`[${CONST.NO_ACTION}] `)?.[1]?.replace('"', '');
const noActionContext = assistantResponse.split(`[${CONST.NO_ACTION}] `)?.at(1)?.replace('"', '');
console.log('[NO_ACTION] w/ context: ', noActionContext);
return;
}
Expand All @@ -86,10 +86,10 @@ async function run() {
} else if (assistantResponse.includes('[EDIT_COMMENT]') && !payload.comment?.body.includes('Edited by **proposal-police**')) {
// extract the text after [EDIT_COMMENT] from assistantResponse since this is a
// bot related action keyword
let extractedNotice = assistantResponse.split('[EDIT_COMMENT] ')?.[1]?.replace('"', '');
let extractedNotice = assistantResponse.split('[EDIT_COMMENT] ')?.at(1)?.replace('"', '');
// format the github's updated_at like: 2024-01-24 13:15:24 UTC not 2024-01-28 18:18:28.000 UTC
const date = new Date(payload.comment?.updated_at ?? '');
const formattedDate = `${date.toISOString()?.split('.')?.[0]?.replace('T', ' ')} UTC`;
const formattedDate = `${date.toISOString()?.split('.')?.at(0)?.replace('T', ' ')} UTC`;
extractedNotice = extractedNotice.replace('{updated_timestamp}', formattedDate);
console.log('ProposalPolice™ editing issue comment...', payload.comment.id);
await GithubUtils.octokit.issues.updateComment({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function checkIssueForCompletedChecklist(numberOfChecklistItems: number) {
}

const whitespace = /([\n\r])/gm;
const comment = combinedComments[i].replace(whitespace, '');
const comment = combinedComments.at(i).replace(whitespace, '');

console.log(`Comment ${i} starts with: ${comment.slice(0, 20)}...`);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const run = (): boolean => {
console.log(`Processing ${regressionOutput.countChanged.length} measurements...`);

for (let i = 0; i < regressionOutput.countChanged.length; i++) {
const measurement = regressionOutput.countChanged[i];
const measurement = regressionOutput.countChanged.at(i);
const baseline: PerformanceEntry = measurement.baseline;
const current: PerformanceEntry = measurement.current;

Expand Down
10 changes: 5 additions & 5 deletions .github/libs/GithubUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ class GithubUtils {
throw new Error(`Found more than one ${CONST.LABELS.STAGING_DEPLOY} issue.`);
}

return this.getStagingDeployCashData(data[0]);
return this.getStagingDeployCashData(data.at(0));
});
}

Expand Down Expand Up @@ -254,7 +254,7 @@ class GithubUtils {
}
internalQASection = internalQASection[1];
const internalQAPRs = [...internalQASection.matchAll(new RegExp(`- \\[([ x])]\\s(${CONST.PULL_REQUEST_REGEX.source})`, 'g'))].map((match) => ({
url: match[2].split('-')[0].trim(),
url: match[2].split('-').at(0).trim(),
number: Number.parseInt(match[3], 10),
isResolved: match[1] === 'x',
}));
Expand Down Expand Up @@ -367,7 +367,7 @@ class GithubUtils {
* Fetch all pull requests given a list of PR numbers.
*/
static fetchAllPullRequests(pullRequestNumbers: number[]): Promise<OctokitPR[] | void> {
const oldestPR = pullRequestNumbers.sort((a, b) => a - b)[0];
const oldestPR = pullRequestNumbers.sort((a, b) => a - b).at(0);
return this.paginate(
this.octokit.pulls.list,
{
Expand Down Expand Up @@ -459,7 +459,7 @@ class GithubUtils {
repo: CONST.APP_REPO,
workflow_id: workflow,
})
.then((response) => response.data.workflow_runs[0]?.id);
.then((response) => response.data.workflow_runs.at(0)?.id);
}

/**
Expand Down Expand Up @@ -533,7 +533,7 @@ class GithubUtils {
per_page: 1,
name: artifactName,
})
.then((response) => response.data.artifacts[0]);
.then((response) => response.data.artifacts.at(0));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion .github/libs/nativeVersionUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function updateAndroidVersion(versionName: string, versionCode: string): Promise
* Updates the CFBundleShortVersionString and the CFBundleVersion.
*/
function updateiOSVersion(version: string): string {
const shortVersion = version.split('-')[0];
const shortVersion = version.split('-').at(0);
const cfVersion = version.includes('-') ? version.replace('-', '.') : `${version}.0`;
console.log('Updating iOS', `CFBundleShortVersionString: ${shortVersion}`, `CFBundleVersion: ${cfVersion}`);

Expand Down
2 changes: 1 addition & 1 deletion .github/scripts/createDocsRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function pushOrCreateEntry<TKey extends HubEntriesKey>(hubs: Hub[], hub: string,
}

function getOrderFromArticleFrontMatter(path: string): number | undefined {
const frontmatter = fs.readFileSync(path, 'utf8').split('---')[1];
const frontmatter = fs.readFileSync(path, 'utf8').split('---').at(1);
const frontmatterObject = yaml.load(frontmatter) as Record<string, unknown>;
return frontmatterObject.order as number | undefined;
}
Expand Down
6 changes: 3 additions & 3 deletions .storybook/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,16 @@ const webpackConfig = ({config}: {config: Configuration}) => {

// Necessary to overwrite the values in the existing DefinePlugin hardcoded to the Config staging values
const definePluginIndex = config.plugins.findIndex((plugin) => plugin instanceof DefinePlugin);
if (definePluginIndex !== -1 && config.plugins[definePluginIndex] instanceof DefinePlugin) {
const definePlugin = config.plugins[definePluginIndex] as DefinePlugin;
if (definePluginIndex !== -1 && config.plugins.at(definePluginIndex) instanceof DefinePlugin) {
const definePlugin = config.plugins.at(definePluginIndex) as DefinePlugin;
if (definePlugin.definitions) {
definePlugin.definitions.__REACT_WEB_CONFIG__ = JSON.stringify(env);
}
}
config.resolve.extensions = custom.resolve.extensions;

const babelRulesIndex = custom.module.rules.findIndex((rule) => rule.loader === 'babel-loader');
const babelRule = custom.module.rules[babelRulesIndex];
const babelRule = custom.module.rules.at(babelRulesIndex);
if (babelRule) {
config.module.rules?.push(babelRule);
}
Expand Down
2 changes: 1 addition & 1 deletion assets/emojis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const localeEmojis: LocaleEmojis = {
};

const importEmojiLocale = (locale: Locale) => {
const normalizedLocale = locale.toLowerCase().split('-')[0] as Locale;
const normalizedLocale = locale.toLowerCase().split('-').at(0) as Locale;
if (!localeEmojis[normalizedLocale]) {
const emojiImportPromise = normalizedLocale === 'en' ? import('./en') : import('./es');
return emojiImportPromise.then((esEmojiModule) => {
Expand Down
2 changes: 1 addition & 1 deletion config/webpack/webpack.common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const environmentToLogoSuffixMap: Record<string, string> = {
};

function mapEnvironmentToLogoSuffix(environmentFile: string): string {
let environment = environmentFile.split('.')[2];
let environment = environmentFile.split('.').at(2);
if (typeof environment === 'undefined') {
environment = 'dev';
}
Expand Down
2 changes: 1 addition & 1 deletion jest/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jest.mock('react-native/Libraries/LogBox/LogBox', () => ({

// Turn off the console logs for timing events. They are not relevant for unit tests and create a lot of noise
jest.spyOn(console, 'debug').mockImplementation((...params: string[]) => {
if (params[0].startsWith('Timing:')) {
if (params.at(0).startsWith('Timing:')) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion scripts/release-profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ if (cpuProfiles.length === 0) {
process.exit(1);
} else {
// Construct the command
const cpuprofileName = cpuProfiles[0];
const cpuprofileName = cpuProfiles.at(0);
const command = `npx react-native-release-profiler --local "${cpuprofileName}" --sourcemap-path "${sourcemapPath}"`;

console.log(`Executing: ${command}`);
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddPlaidBankAccount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ function AddPlaidBankAccount({
const {icon, iconSize, iconStyles} = getBankIcon({styles});
const plaidErrors = plaidData?.errors;
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
const plaidDataErrorMessage = !isEmptyObject(plaidErrors) ? (Object.values(plaidErrors)[0] as string) : '';
const plaidDataErrorMessage = !isEmptyObject(plaidErrors) ? (Object.values(plaidErrors).at(0) as string) : '';
const bankName = plaidData?.bankName;

/**
Expand Down
7 changes: 5 additions & 2 deletions src/components/AttachmentPicker/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,10 @@ function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, s
const uri = manipResult.uri;
const convertedAsset = {
uri,
name: uri.substring(uri.lastIndexOf('/') + 1).split('?')[0],
name: uri
.substring(uri.lastIndexOf('/') + 1)
.split('?')
.at(0),
type: 'image/jpeg',
width: manipResult.width,
height: manipResult.height,
Expand Down Expand Up @@ -363,7 +366,7 @@ function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, s
if (focusedIndex === -1) {
return;
}
selectItem(menuItemData[focusedIndex]);
selectItem(menuItemData.at(focusedIndex));
setFocusedIndex(-1); // Reset the focusedIndex on selecting any menu
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
}

// Update the parent modal's state with the source and name from the mapped attachments
if (targetAttachments[initialPage] !== undefined && onNavigate) {
onNavigate(targetAttachments[initialPage]);
if (targetAttachments.at(initialPage) !== undefined && onNavigate) {
onNavigate(targetAttachments.at(initialPage));
}
}
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
Expand All @@ -66,7 +66,7 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
Keyboard.dismiss();
setShouldShowArrows(true);

const item = attachments[newPageIndex];
const item = attachments.at(newPageIndex);

setPage(newPageIndex);
setActiveSource(item.source);
Expand Down
8 changes: 4 additions & 4 deletions src/components/Attachments/AttachmentCarousel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
}

// Update the parent modal's state with the source and name from the mapped attachments
if (targetAttachments[initialPage] !== undefined && onNavigate) {
onNavigate(targetAttachments[initialPage]);
if (targetAttachments.at(initialPage) !== undefined && onNavigate) {
onNavigate(targetAttachments.at(initialPage));
}
}
}, [report.privateNotes, reportActions, parentReportActions, compareImage, report.parentReportActionID, attachments, setDownloadButtonVisibility, onNavigate, accountID, type]);
Expand All @@ -129,7 +129,7 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,

// Since we can have only one item in view at a time, we can use the first item in the array
// to get the index of the current page
const entry = viewableItems[0];
const entry = viewableItems.at(0);
if (!entry) {
setActiveSource(null);
return;
Expand All @@ -156,7 +156,7 @@ function AttachmentCarousel({report, reportActions, parentReportActions, source,
}

const nextIndex = page + deltaSlide;
const nextItem = attachments[nextIndex];
const nextItem = attachments.at(nextIndex);

if (!nextItem || !scrollRef.current) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ function AttachmentViewPdf(props: AttachmentViewPdfProps) {
.manualActivation(true)
.onTouchesMove((evt) => {
if (offsetX.value !== 0 && offsetY.value !== 0 && isScrollEnabled) {
const translateX = Math.abs(evt.allTouches[0].absoluteX - offsetX.value);
const translateY = Math.abs(evt.allTouches[0].absoluteY - offsetY.value);
const translateX = Math.abs(evt.allTouches.at(0).absoluteX - offsetX.value);
const translateY = Math.abs(evt.allTouches.at(0).absoluteY - offsetY.value);
const allowEnablingScroll = !isPanGestureActive.value || isScrollEnabled.value;

// if the value of X is greater than Y and the pdf is not zoomed in,
Expand All @@ -49,8 +49,8 @@ function AttachmentViewPdf(props: AttachmentViewPdfProps) {
}

isPanGestureActive.value = true;
offsetX.value = evt.allTouches[0].absoluteX;
offsetY.value = evt.allTouches[0].absoluteY;
offsetX.value = evt.allTouches.at(0).absoluteX;
offsetY.value = evt.allTouches.at(0).absoluteY;
})
.onTouchesUp(() => {
isPanGestureActive.value = false;
Expand Down
4 changes: 2 additions & 2 deletions src/components/AvatarWithDisplayName.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ function AvatarWithDisplayName({
{shouldShowSubscriptAvatar ? (
<SubscriptAvatar
backgroundColor={avatarBorderColor}
mainAvatar={icons[0]}
secondaryAvatar={icons[1]}
mainAvatar={icons.at(0)}
secondaryAvatar={icons.at(1)}
size={size}
/>
) : (
Expand Down
8 changes: 4 additions & 4 deletions src/components/ButtonWithDropdownMenu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function ButtonWithDropdownMenu<IValueType>({
const {windowWidth, windowHeight} = useWindowDimensions();
const dropdownAnchor = useRef<View | null>(null);
const dropdownButtonRef = isSplitButton ? buttonRef : mergeRefs(buttonRef, dropdownAnchor);
const selectedItem = options[selectedItemIndex] || options[0];
const selectedItem = options.at(selectedItemIndex) ?? options.at(0);
const innerStyleDropButton = StyleUtils.getDropDownButtonHeight(buttonSize);
const isButtonSizeLarge = buttonSize === CONST.DROPDOWN_BUTTON_SIZE.LARGE;
const nullCheckRef = (ref: MutableRefObject<View | null>) => ref ?? null;
Expand Down Expand Up @@ -85,7 +85,7 @@ function ButtonWithDropdownMenu<IValueType>({
}
onPress(e, selectedItem?.value);
} else {
onPress(e, options[0]?.value);
onPress(e, options.at(0)?.value);
}
},
{
Expand Down Expand Up @@ -150,11 +150,11 @@ function ButtonWithDropdownMenu<IValueType>({
success={success}
ref={buttonRef}
pressOnEnter={pressOnEnter}
isDisabled={isDisabled || !!options[0].disabled}
isDisabled={isDisabled || !!options.at(0).disabled}
style={[styles.w100, style]}
isLoading={isLoading}
text={selectedItem.text}
onPress={(event) => onPress(event, options[0].value)}
onPress={(event) => onPress(event, options.at(0).value)}
large={isButtonSizeLarge}
medium={!isButtonSizeLarge}
innerStyles={[innerStyleDropButton]}
Expand Down
4 changes: 2 additions & 2 deletions src/components/CategoryPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ function CategoryPicker({selectedCategory, policyCategories, policyRecentlyUsedC
false,
);

const categoryData = categoryOptions?.[0]?.data ?? [];
const categoryData = categoryOptions?.at(0)?.data ?? [];
const header = OptionsListUtils.getHeaderMessageForNonUserList(categoryData.length > 0, debouncedSearchValue);
const categoriesCount = OptionsListUtils.getEnabledCategoriesCount(categories);
const isCategoriesCountBelowThreshold = categoriesCount < CONST.CATEGORY_LIST_THRESHOLD;
Expand All @@ -71,7 +71,7 @@ function CategoryPicker({selectedCategory, policyCategories, policyRecentlyUsedC
return [categoryOptions, header, showInput];
}, [policyRecentlyUsedCategories, debouncedSearchValue, selectedOptions, policyCategories, policyCategoriesDraft]);

const selectedOptionKey = useMemo(() => (sections?.[0]?.data ?? []).filter((category) => category.searchText === selectedCategory)[0]?.keyForList, [sections, selectedCategory]);
const selectedOptionKey = useMemo(() => (sections?.at(0)?.data ?? []).filter((category) => category.searchText === selectedCategory).at(0)?.keyForList, [sections, selectedCategory]);

return (
<SelectionList
Expand Down
2 changes: 1 addition & 1 deletion src/components/Composer/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ function Composer(

const pasteFile = useCallback(
(e: NativeSyntheticEvent<TextInputPasteEventData>) => {
const clipboardContent = e.nativeEvent.items[0];
const clipboardContent = e.nativeEvent.items.at(0);
if (clipboardContent.type === 'text/plain') {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/ConfirmedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ function ConfirmedRoute({mapboxAccessToken, transaction, isSmallerIcon, shouldHa
pitchEnabled={false}
initialState={{
zoom: CONST.MAPBOX.DEFAULT_ZOOM,
location: waypointMarkers?.[0]?.coordinate ?? (CONST.MAPBOX.DEFAULT_COORDINATE as [number, number]),
location: waypointMarkers?.at(0)?.coordinate ?? (CONST.MAPBOX.DEFAULT_COORDINATE as [number, number]),
}}
directionCoordinates={coordinates as Array<[number, number]>}
style={[styles.mapView, shouldHaveBorderRadius && styles.br4]}
Expand Down
Loading

0 comments on commit cadeafa

Please sign in to comment.