[Refactoring] Remove flatten, add generic type for split (#1879)

This commit is contained in:
Alexander Zinchuk 2022-05-30 15:40:06 +04:00
parent d3e3cced6c
commit 9544663aa1
7 changed files with 27 additions and 40 deletions

View File

@ -7,7 +7,7 @@ import { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../t
import { buildApiDocument } from './messages'; import { buildApiDocument } from './messages';
import { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers'; import { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';
import { flatten, pick } from '../../../util/iteratees'; import { pick } from '../../../util/iteratees';
import { getServerTime } from '../../../util/serverTime'; import { getServerTime } from '../../../util/serverTime';
export function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined { 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 { const {
hidden, iso2, defaultName, name, hidden, iso2, defaultName, name,
} = country; } = country;
@ -142,20 +142,18 @@ function buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.Countr
} }
export function buildApiCountryList(countries: GramJs.help.Country[]) { export function buildApiCountryList(countries: GramJs.help.Country[]) {
const listByCode = flatten( const nonHiddenCountries = countries.filter(({ hidden }) => !hidden);
countries const listByCode = nonHiddenCountries
.filter((country) => !country.hidden) .map((country) => (
.map((country) => ( country.countryCodes.map((code) => buildApiCountry(country, code))
country.countryCodes.map((code) => buildApiCountry(country, code)) ))
)), .flat()
)
.sort((a: ApiCountry, b: ApiCountry) => ( .sort((a: ApiCountry, b: ApiCountry) => (
a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName) a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)
)); ));
const generalList = countries const generalList = nonHiddenCountries
.filter((country) => !country.hidden) .map((country) => buildApiCountry(country, country.countryCodes[0]))
.map((country) => buildApiCountry(country))
.sort((a, b) => ( .sort((a, b) => (
a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName) a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)
)); ));

View File

@ -5,7 +5,7 @@ import { MessageListType } from '../../global/types';
import { SCHEDULED_WHEN_ONLINE } from '../../config'; import { SCHEDULED_WHEN_ONLINE } from '../../config';
import buildClassName from '../../util/buildClassName'; import buildClassName from '../../util/buildClassName';
import { compact, flatten } from '../../util/iteratees'; import { compact } from '../../util/iteratees';
import { formatHumanDate } from '../../util/dateFormat'; import { formatHumanDate } from '../../util/dateFormat';
import { import {
getMessageHtmlId, getMessageOriginalId, isActionMessage, isOwnMessage, getMessageHtmlId, getMessageOriginalId, isActionMessage, isOwnMessage,
@ -108,7 +108,7 @@ const MessageListContent: FC<OwnProps> = ({
); );
const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => { const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {
return acc + flatten(messageGroup.senderGroups).length; return acc + messageGroup.senderGroups.flat().length;
}, 0); }, 0);
let appearanceIndex = 0; let appearanceIndex = 0;
@ -148,7 +148,7 @@ const MessageListContent: FC<OwnProps> = ({
let currentDocumentGroupId: string | undefined; let currentDocumentGroupId: string | undefined;
return flatten(senderGroup.map(( return senderGroup.map((
messageOrAlbum, messageOrAlbum,
messageIndex, messageIndex,
) => { ) => {
@ -214,7 +214,7 @@ const MessageListContent: FC<OwnProps> = ({
</div> </div>
), ),
]); ]);
})); }).flat();
}); });
return ( return (
@ -240,7 +240,7 @@ const MessageListContent: FC<OwnProps> = ({
{!isSchedule && formatHumanDate(lang, dateGroup.datetime)} {!isSchedule && formatHumanDate(lang, dateGroup.datetime)}
</span> </span>
</div> </div>
{flatten(senderGroups)} {senderGroups.flat()}
</div> </div>
); );
}); });
@ -248,7 +248,7 @@ const MessageListContent: FC<OwnProps> = ({
return ( return (
<div className="messages-container" teactFastList> <div className="messages-container" teactFastList>
<div ref={backwardsTriggerRef} key="backwards-trigger" className="backwards-trigger" /> <div ref={backwardsTriggerRef} key="backwards-trigger" className="backwards-trigger" />
{flatten(dateGroups)} {dateGroups.flat()}
{isViewportNewest && <SponsoredMessage key={chatId} chatId={chatId} containerRef={containerRef} />} {isViewportNewest && <SponsoredMessage key={chatId} chatId={chatId} containerRef={containerRef} />}
<div <div
ref={forwardsTriggerRef} ref={forwardsTriggerRef}

View File

@ -10,7 +10,7 @@ import {
} from '../../../../util/emoji'; } from '../../../../util/emoji';
import focusEditableElement from '../../../../util/focusEditableElement'; import focusEditableElement from '../../../../util/focusEditableElement';
import { import {
buildCollectionByKey, flatten, mapValues, pickTruthy, unique, buildCollectionByKey, mapValues, pickTruthy, unique,
} from '../../../../util/iteratees'; } from '../../../../util/iteratees';
import memoized from '../../../../util/memoized'; import memoized from '../../../../util/memoized';
import useFlag from '../../../../hooks/useFlag'; import useFlag from '../../../../hooks/useFlag';
@ -222,11 +222,11 @@ function searchInLibrary(library: Library, filter: string, limit: number) {
let matched: Emoji[] = MEMO_EMPTY_ARRAY; let matched: Emoji[] = MEMO_EMPTY_ARRAY;
const matchedKeywords = keywords.filter((keyword) => keyword.startsWith(filter)).sort(); const matchedKeywords = keywords.filter((keyword) => 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 // Also search by names, which is useful for non-English languages
const matchedNames = names.filter((name) => name.startsWith(filter)); 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); matched = unique(matched);

View File

@ -228,7 +228,7 @@ addActionHandler('sendMessage', (global, actions, payload) => {
const { const {
text, entities, attachments, ...commonParams text, entities, attachments, ...commonParams
} = params; } = 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++) { for (let i = 0; i < groupedAttachments.length; i++) {
const [firstAttachment, ...restAttachments] = groupedAttachments[i]; const [firstAttachment, ...restAttachments] = groupedAttachments[i];
const groupedId = `${Date.now()}${i}`; const groupedId = `${Date.now()}${i}`;

View File

@ -3,7 +3,7 @@ import { DEBUG, DEBUG_MORE } from '../../config';
import { import {
fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf, fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf,
} from '../../util/schedulers'; } from '../../util/schedulers';
import { flatten, orderBy } from '../../util/iteratees'; import { orderBy } from '../../util/iteratees';
import { getUnequalProps } from '../../util/arePropsShallowEqual'; import { getUnequalProps } from '../../util/arePropsShallowEqual';
import { handleError } from '../../util/handleError'; import { handleError } from '../../util/handleError';
import { removeAllDelegatedListeners } from './dom-events'; import { removeAllDelegatedListeners } from './dom-events';
@ -143,7 +143,7 @@ function createElement(
props = {}; props = {};
} }
children = flatten(children); children = children.flat();
if (source === Fragment) { if (source === Fragment) {
return children; return children;

View File

@ -80,17 +80,6 @@ export function orderBy<T>(
}); });
} }
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<T extends any>(array: T[]): T[] { export function unique<T extends any>(array: T[]): T[] {
return Array.from(new Set(array)); return Array.from(new Set(array));
} }
@ -115,8 +104,8 @@ export function findIntersectionWithSet<T>(array: T[], set: Set<T>): T[] {
return array.filter((a) => set.has(a)); return array.filter((a) => set.has(a));
} }
export function split(array: any[], chunkSize: number) { export function split<T extends any>(array: T[], chunkSize: number) {
const result = []; const result: T[][] = [];
for (let i = 0; i < array.length; i += chunkSize) { for (let i = 0; i < array.length; i += chunkSize) {
result.push(array.slice(i, i + chunkSize)); result.push(array.slice(i, i + chunkSize));
} }

View File

@ -1,5 +1,4 @@
import { ApiCountryCode } from '../api/types'; import { ApiCountryCode } from '../api/types';
import { flatten } from './iteratees';
const PATTERN_PLACEHOLDER = 'X'; const PATTERN_PLACEHOLDER = 'X';
const DEFAULT_PATTERN = 'XXX XXX XXX XXX'; const DEFAULT_PATTERN = 'XXX XXX XXX XXX';
@ -16,13 +15,14 @@ export function getCountryFromPhoneNumber(phoneCodeList: ApiCountryCode[], input
const possibleCountries = phoneCodeList const possibleCountries = phoneCodeList
.filter((country) => phoneNumber.startsWith(country.countryCode)); .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) => { .map((country) => (country.prefixes || ['']).map((prefix) => {
return { return {
code: `${country.countryCode}${prefix}`, code: `${country.countryCode}${prefix}`,
country, country,
}; };
}))); }))
.flat();
const bestMatches = codesWithPrefix const bestMatches = codesWithPrefix
.filter(({ code }) => phoneNumber.startsWith(code)) .filter(({ code }) => phoneNumber.startsWith(code))