From 9544663aa106f19f28f599374dce6969ec10e588 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Mon, 30 May 2022 15:40:06 +0400 Subject: [PATCH] [Refactoring] Remove `flatten`, add generic type for `split` (#1879) --- src/api/gramjs/apiBuilders/misc.ts | 22 +++++++++---------- src/components/middle/MessageListContent.tsx | 12 +++++----- .../middle/composer/hooks/useEmojiTooltip.ts | 6 ++--- src/global/actions/api/messages.ts | 2 +- src/lib/teact/teact.ts | 4 ++-- src/util/iteratees.ts | 15 ++----------- src/util/phoneNumber.ts | 6 ++--- 7 files changed, 27 insertions(+), 40 deletions(-) diff --git a/src/api/gramjs/apiBuilders/misc.ts b/src/api/gramjs/apiBuilders/misc.ts index 790930ef8..2c217fb9d 100644 --- a/src/api/gramjs/apiBuilders/misc.ts +++ b/src/api/gramjs/apiBuilders/misc.ts @@ -7,7 +7,7 @@ import { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../t import { buildApiDocument } from './messages'; import { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers'; -import { flatten, pick } from '../../../util/iteratees'; +import { pick } from '../../../util/iteratees'; import { getServerTime } from '../../../util/serverTime'; export function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined { @@ -124,7 +124,7 @@ export function buildApiNotifyException( }; } -function buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) { +function buildApiCountry(country: GramJs.help.Country, code: GramJs.help.CountryCode) { const { hidden, iso2, defaultName, name, } = country; @@ -142,20 +142,18 @@ function buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.Countr } export function buildApiCountryList(countries: GramJs.help.Country[]) { - const listByCode = flatten( - countries - .filter((country) => !country.hidden) - .map((country) => ( - country.countryCodes.map((code) => buildApiCountry(country, code)) - )), - ) + const nonHiddenCountries = countries.filter(({ hidden }) => !hidden); + const listByCode = nonHiddenCountries + .map((country) => ( + country.countryCodes.map((code) => buildApiCountry(country, code)) + )) + .flat() .sort((a: ApiCountry, b: ApiCountry) => ( a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName) )); - const generalList = countries - .filter((country) => !country.hidden) - .map((country) => buildApiCountry(country)) + const generalList = nonHiddenCountries + .map((country) => buildApiCountry(country, country.countryCodes[0])) .sort((a, b) => ( a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName) )); diff --git a/src/components/middle/MessageListContent.tsx b/src/components/middle/MessageListContent.tsx index f33232dc9..1c8deddab 100644 --- a/src/components/middle/MessageListContent.tsx +++ b/src/components/middle/MessageListContent.tsx @@ -5,7 +5,7 @@ import { MessageListType } from '../../global/types'; import { SCHEDULED_WHEN_ONLINE } from '../../config'; import buildClassName from '../../util/buildClassName'; -import { compact, flatten } from '../../util/iteratees'; +import { compact } from '../../util/iteratees'; import { formatHumanDate } from '../../util/dateFormat'; import { getMessageHtmlId, getMessageOriginalId, isActionMessage, isOwnMessage, @@ -108,7 +108,7 @@ const MessageListContent: FC = ({ ); const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => { - return acc + flatten(messageGroup.senderGroups).length; + return acc + messageGroup.senderGroups.flat().length; }, 0); let appearanceIndex = 0; @@ -148,7 +148,7 @@ const MessageListContent: FC = ({ let currentDocumentGroupId: string | undefined; - return flatten(senderGroup.map(( + return senderGroup.map(( messageOrAlbum, messageIndex, ) => { @@ -214,7 +214,7 @@ const MessageListContent: FC = ({ ), ]); - })); + }).flat(); }); return ( @@ -240,7 +240,7 @@ const MessageListContent: FC = ({ {!isSchedule && formatHumanDate(lang, dateGroup.datetime)} - {flatten(senderGroups)} + {senderGroups.flat()} ); }); @@ -248,7 +248,7 @@ const MessageListContent: FC = ({ return (
- {flatten(dateGroups)} + {dateGroups.flat()} {isViewportNewest && }
keyword.startsWith(filter)).sort(); - matched = matched.concat(flatten(Object.values(pickTruthy(byKeyword!, matchedKeywords)))); + matched = matched.concat(Object.values(pickTruthy(byKeyword!, matchedKeywords)).flat()); // Also search by names, which is useful for non-English languages const matchedNames = names.filter((name) => name.startsWith(filter)); - matched = matched.concat(flatten(Object.values(pickTruthy(byName, matchedNames)))); + matched = matched.concat(Object.values(pickTruthy(byName, matchedNames)).flat()); matched = unique(matched); diff --git a/src/global/actions/api/messages.ts b/src/global/actions/api/messages.ts index ef207d9c1..6ce9df764 100644 --- a/src/global/actions/api/messages.ts +++ b/src/global/actions/api/messages.ts @@ -228,7 +228,7 @@ addActionHandler('sendMessage', (global, actions, payload) => { const { text, entities, attachments, ...commonParams } = params; - const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM); + const groupedAttachments = split(attachments as ApiAttachment[], MAX_MEDIA_FILES_FOR_ALBUM); for (let i = 0; i < groupedAttachments.length; i++) { const [firstAttachment, ...restAttachments] = groupedAttachments[i]; const groupedId = `${Date.now()}${i}`; diff --git a/src/lib/teact/teact.ts b/src/lib/teact/teact.ts index 89b5f1d6b..b2629bead 100644 --- a/src/lib/teact/teact.ts +++ b/src/lib/teact/teact.ts @@ -3,7 +3,7 @@ import { DEBUG, DEBUG_MORE } from '../../config'; import { fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf, } from '../../util/schedulers'; -import { flatten, orderBy } from '../../util/iteratees'; +import { orderBy } from '../../util/iteratees'; import { getUnequalProps } from '../../util/arePropsShallowEqual'; import { handleError } from '../../util/handleError'; import { removeAllDelegatedListeners } from './dom-events'; @@ -143,7 +143,7 @@ function createElement( props = {}; } - children = flatten(children); + children = children.flat(); if (source === Fragment) { return children; diff --git a/src/util/iteratees.ts b/src/util/iteratees.ts index a84190d1f..40344295e 100644 --- a/src/util/iteratees.ts +++ b/src/util/iteratees.ts @@ -80,17 +80,6 @@ export function orderBy( }); } -export function flatten(array: any[]) { - return array.reduce((result, member) => { - if (Array.isArray(member)) { - return result.concat(member); - } else { - result.push(member); - return result; - } - }, []); -} - export function unique(array: T[]): T[] { return Array.from(new Set(array)); } @@ -115,8 +104,8 @@ export function findIntersectionWithSet(array: T[], set: Set): T[] { return array.filter((a) => set.has(a)); } -export function split(array: any[], chunkSize: number) { - const result = []; +export function split(array: T[], chunkSize: number) { + const result: T[][] = []; for (let i = 0; i < array.length; i += chunkSize) { result.push(array.slice(i, i + chunkSize)); } diff --git a/src/util/phoneNumber.ts b/src/util/phoneNumber.ts index 7ebf1f69e..7d322e9ea 100644 --- a/src/util/phoneNumber.ts +++ b/src/util/phoneNumber.ts @@ -1,5 +1,4 @@ import { ApiCountryCode } from '../api/types'; -import { flatten } from './iteratees'; const PATTERN_PLACEHOLDER = 'X'; const DEFAULT_PATTERN = 'XXX XXX XXX XXX'; @@ -16,13 +15,14 @@ export function getCountryFromPhoneNumber(phoneCodeList: ApiCountryCode[], input const possibleCountries = phoneCodeList .filter((country) => phoneNumber.startsWith(country.countryCode)); - const codesWithPrefix: { code: string; country: ApiCountryCode }[] = flatten(possibleCountries + const codesWithPrefix: { code: string; country: ApiCountryCode }[] = possibleCountries .map((country) => (country.prefixes || ['']).map((prefix) => { return { code: `${country.countryCode}${prefix}`, country, }; - }))); + })) + .flat(); const bestMatches = codesWithPrefix .filter(({ code }) => phoneNumber.startsWith(code))