refactor: prefer switches to else-if chains

This commit is contained in:
teidesu 2021-05-12 17:58:45 +03:00
parent 6879ae945a
commit 9be7b0d6c9
10 changed files with 704 additions and 611 deletions

View file

@ -102,24 +102,31 @@ export async function getChatMembers(
const type = params.type ?? 'recent' const type = params.type ?? 'recent'
let filter: tl.TypeChannelParticipantsFilter let filter: tl.TypeChannelParticipantsFilter
if (type === 'all') { switch (type) {
case 'all':
filter = { _: 'channelParticipantsSearch', q } filter = { _: 'channelParticipantsSearch', q }
} else if (type === 'banned') { break
case 'banned':
filter = { _: 'channelParticipantsKicked', q } filter = { _: 'channelParticipantsKicked', q }
} else if (type === 'restricted') { break
case 'restricted':
filter = { _: 'channelParticipantsBanned', q } filter = { _: 'channelParticipantsBanned', q }
} else if (type === 'mention') { break
case 'mention':
filter = { _: 'channelParticipantsMentions', q } filter = { _: 'channelParticipantsMentions', q }
} else if (type === 'bots') { break
case 'bots':
filter = { _: 'channelParticipantsBots' } filter = { _: 'channelParticipantsBots' }
} else if (type === 'recent') { break
case 'recent':
filter = { _: 'channelParticipantsRecent' } filter = { _: 'channelParticipantsRecent' }
} else if (type === 'admins') { break
case 'admins':
filter = { _: 'channelParticipantsAdmins' } filter = { _: 'channelParticipantsAdmins' }
} else if (type === 'contacts') { break
case 'contacts':
filter = { _: 'channelParticipantsContacts', q } filter = { _: 'channelParticipantsContacts', q }
} else { break
return type as never
} }
const res = await this.call({ const res = await this.call({

View file

@ -208,8 +208,7 @@ async function _loadDifference(
qts: 0, qts: 0,
}) })
if (diff._ === 'updates.differenceEmpty') if (diff._ === 'updates.differenceEmpty') return
return
if (diff._ === 'updates.differenceTooLong') { if (diff._ === 'updates.differenceTooLong') {
this._pts = diff.pts this._pts = diff.pts
@ -340,7 +339,8 @@ async function _loadChannelDifference(
} }
diff.messages.forEach((message) => { diff.messages.forEach((message) => {
if (noDispatch && noDispatch.msg[channelId]?.[message.id]) return if (noDispatch && noDispatch.msg[channelId]?.[message.id])
return
this.dispatchUpdate(message, users, chats) this.dispatchUpdate(message, users, chats)
}) })
@ -409,13 +409,12 @@ export function _handleUpdate(
// i tried my best to follow the documentation, but i still may have missed something. // i tried my best to follow the documentation, but i still may have missed something.
// feel free to contribute! // feel free to contribute!
// reference: https://core.telegram.org/api/updates // reference: https://core.telegram.org/api/updates
if (update._ === 'updatesTooLong') { switch (update._) {
// "there are too many events pending to be pushed to the client", we need to fetch them manually case 'updatesTooLong': // "there are too many events pending to be pushed to the client", we need to fetch them manually
await _loadDifference.call(this, noDispatchIndex) await _loadDifference.call(this, noDispatchIndex)
} else if ( break
update._ === 'updates' || case 'updates':
update._ === 'updatesCombined' case 'updatesCombined': {
) {
// const seqStart = // const seqStart =
// update._ === 'updatesCombined' // update._ === 'updatesCombined'
// ? update.seqStart // ? update.seqStart
@ -508,7 +507,9 @@ export function _handleUpdate(
// this._seq = update.seq // this._seq = update.seq
this._date = update.date this._date = update.date
} }
} else if (update._ === 'updateShort') { break
}
case 'updateShort': {
const upd = update.update const upd = update.update
if (upd._ === 'updateDcOptions' && this._config) { if (upd._ === 'updateDcOptions' && this._config) {
;(this._config as tl.Mutable<tl.TypeConfig>).dcOptions = ;(this._config as tl.Mutable<tl.TypeConfig>).dcOptions =
@ -520,7 +521,9 @@ export function _handleUpdate(
} }
this._date = update.date this._date = update.date
} else if (update._ === 'updateShortMessage') { break
}
case 'updateShortMessage': {
if (noDispatch) return if (noDispatch) return
const message: tl.RawMessage = { const message: tl.RawMessage = {
@ -605,7 +608,8 @@ export function _handleUpdate(
limit: 20, limit: 20,
hash: 0, hash: 0,
}) })
if (dialogs._ === 'messages.dialogsNotModified') return if (dialogs._ === 'messages.dialogsNotModified')
return
const user = dialogs.users.find( const user = dialogs.users.find(
(it) => it.id === update.userId (it) => it.id === update.userId
@ -637,7 +641,9 @@ export function _handleUpdate(
chats: rawChats, chats: rawChats,
}) })
this.dispatchUpdate(message, users, chats) this.dispatchUpdate(message, users, chats)
} else if (update._ === 'updateShortChatMessage') { break
}
case 'updateShortChatMessage': {
if (noDispatch) return if (noDispatch) return
const message: tl.RawMessage = { const message: tl.RawMessage = {
@ -749,11 +755,13 @@ export function _handleUpdate(
chats: rawChats, chats: rawChats,
}) })
this.dispatchUpdate(message, users, chats) this.dispatchUpdate(message, users, chats)
} else if (update._ === 'updateShortSentMessage') { break
// only store the new pts and date values }
case 'updateShortSentMessage': // only store the new pts and date values
// we never need to dispatch this // we never need to dispatch this
this._date = update.date this._date = update.date
this._pts = update.pts this._pts = update.pts
break
} }
}) })
.catch((err) => this._emitError(err)) .catch((err) => this._emitError(err))

View file

@ -56,7 +56,8 @@ export async function resolvePeer(
const peerType = getBasicPeerType(peerId) const peerType = getBasicPeerType(peerId)
if (peerType === 'user') { switch (peerType) {
case 'user':
await this.call({ await this.call({
_: 'users.getUsers', _: 'users.getUsers',
id: [ id: [
@ -67,12 +68,14 @@ export async function resolvePeer(
}, },
], ],
}) })
} else if (peerType === 'chat') { break
case 'chat':
await this.call({ await this.call({
_: 'messages.getChats', _: 'messages.getChats',
id: [-peerId], id: [-peerId],
}) })
} else if (peerType === 'channel') { break
case 'channel':
await this.call({ await this.call({
_: 'channels.getChannels', _: 'channels.getChannels',
id: [ id: [
@ -83,6 +86,7 @@ export async function resolvePeer(
}, },
], ],
}) })
break
} }
const fromStorage = await this.storage.getPeerById(peerId) const fromStorage = await this.storage.getPeerById(peerId)

View file

@ -75,16 +75,18 @@ export class Thumbnail extends FileLocation {
| (() => tl.TypeInputFileLocation | Buffer) | (() => tl.TypeInputFileLocation | Buffer)
let size, width, height: number let size, width, height: number
if (sz._ === 'photoStrippedSize') { switch (sz._) {
case 'photoStrippedSize':
location = strippedPhotoToJpg(sz.bytes) location = strippedPhotoToJpg(sz.bytes)
width = height = NaN width = height = NaN
size = location.length size = location.length
} else if (sz._ === 'photoPathSize') { break
// lazily case 'photoPathSize': // lazily
location = () => svgPathToFile(this._path!) location = () => svgPathToFile(this._path!)
width = height = NaN width = height = NaN
size = Infinity // this doesn't really matter size = Infinity // this doesn't really matter
} else { break
default:
location = { location = {
_: _:
media._ === 'photo' media._ === 'photo'
@ -98,6 +100,7 @@ export class Thumbnail extends FileLocation {
width = sz.w width = sz.w
height = sz.h height = sz.h
size = sz._ === 'photoSize' ? sz.size : Math.max(...sz.sizes) size = sz._ === 'photoSize' ? sz.size : Math.max(...sz.sizes)
break
} }
super(client, location, size, media.dcId) super(client, location, size, media.dcId)

View file

@ -272,22 +272,26 @@ export class Message {
if (fwd.fromName) { if (fwd.fromName) {
sender = fwd.fromName sender = fwd.fromName
} else if (fwd.fromId) { } else if (fwd.fromId) {
if (fwd.fromId._ === 'peerChannel') { switch (fwd.fromId._) {
case 'peerChannel':
sender = new Chat( sender = new Chat(
this.client, this.client,
this._chats[fwd.fromId.channelId] this._chats[fwd.fromId.channelId]
) )
} else if (fwd.fromId._ === 'peerUser') { break
case 'peerUser':
sender = new User( sender = new User(
this.client, this.client,
this._users[fwd.fromId.userId] this._users[fwd.fromId.userId]
) )
} else break
default:
throw new MtCuteTypeAssertionError( throw new MtCuteTypeAssertionError(
'Message#forward (@ raw.fwdFrom.fromId)', 'Message#forward (@ raw.fwdFrom.fromId)',
'peerUser | peerChannel', 'peerUser | peerChannel',
fwd.fromId._ fwd.fromId._
) )
}
} else { } else {
this._forward = null this._forward = null
return this._forward return this._forward
@ -431,18 +435,21 @@ export class Message {
} else { } else {
const rm = this.raw.replyMarkup const rm = this.raw.replyMarkup
let markup: ReplyMarkup | null let markup: ReplyMarkup | null
if (rm._ === 'replyKeyboardHide') { switch (rm._) {
case 'replyKeyboardHide':
markup = { markup = {
type: 'reply_hide', type: 'reply_hide',
selective: rm.selective, selective: rm.selective,
} }
} else if (rm._ === 'replyKeyboardForceReply') { break
case 'replyKeyboardForceReply':
markup = { markup = {
type: 'force_reply', type: 'force_reply',
singleUse: rm.singleUse, singleUse: rm.singleUse,
selective: rm.selective, selective: rm.selective,
} }
} else if (rm._ === 'replyKeyboardMarkup') { break
case 'replyKeyboardMarkup':
markup = { markup = {
type: 'reply', type: 'reply',
resize: rm.resize, resize: rm.resize,
@ -450,12 +457,17 @@ export class Message {
selective: rm.selective, selective: rm.selective,
buttons: BotKeyboard._rowsTo2d(rm.rows), buttons: BotKeyboard._rowsTo2d(rm.rows),
} }
} else if (rm._ === 'replyInlineMarkup') { break
case 'replyInlineMarkup':
markup = { markup = {
type: 'inline', type: 'inline',
buttons: BotKeyboard._rowsTo2d(rm.rows), buttons: BotKeyboard._rowsTo2d(rm.rows),
} }
} else markup = null break
default:
markup = null
break
}
this._markup = markup this._markup = markup
} }

View file

@ -126,20 +126,28 @@ export class User {
ret = 'long_time_ago' ret = 'long_time_ago'
} else if (bot) { } else if (bot) {
ret = 'bot' ret = 'bot'
} else if (us._ === 'userStatusOnline') { } else
switch (us._) {
case 'userStatusOnline':
ret = 'online' ret = 'online'
date = new Date(us.expires * 1000) date = new Date(us.expires * 1000)
} else if (us._ === 'userStatusOffline') { break
case 'userStatusOffline':
ret = 'offline' ret = 'offline'
date = new Date(us.wasOnline * 1000) date = new Date(us.wasOnline * 1000)
} else if (us._ === 'userStatusRecently') { break
case 'userStatusRecently':
ret = 'recently' ret = 'recently'
} else if (us._ === 'userStatusLastWeek') { break
case 'userStatusLastWeek':
ret = 'within_week' ret = 'within_week'
} else if (us._ === 'userStatusLastMonth') { break
case 'userStatusLastMonth':
ret = 'within_month' ret = 'within_month'
} else { break
default:
ret = 'long_time_ago' ret = 'long_time_ago'
break
} }
return { return {

View file

@ -652,7 +652,8 @@ export class BaseTelegramClient {
continue continue
} }
if (peer._ === 'user') { switch (peer._) {
case 'user':
parsedPeers.push({ parsedPeers.push({
id: peer.id, id: peer.id,
accessHash: peer.accessHash!, accessHash: peer.accessHash!,
@ -662,7 +663,9 @@ export class BaseTelegramClient {
updated: 0, updated: 0,
fromMessage: peer.fromMessage, fromMessage: peer.fromMessage,
}) })
} else if (peer._ === 'chat' || peer._ === 'chatForbidden') { break
case 'chat':
case 'chatForbidden':
parsedPeers.push({ parsedPeers.push({
id: -peer.id, id: -peer.id,
accessHash: bigInt.zero, accessHash: bigInt.zero,
@ -672,7 +675,9 @@ export class BaseTelegramClient {
updated: 0, updated: 0,
fromMessage: peer.fromMessage, fromMessage: peer.fromMessage,
}) })
} else if (peer._ === 'channel' || peer._ === 'channelForbidden') { break
case 'channel':
case 'channelForbidden':
parsedPeers.push({ parsedPeers.push({
id: MAX_CHANNEL_ID - peer.id, id: MAX_CHANNEL_ID - peer.id,
accessHash: peer.accessHash!, accessHash: peer.accessHash!,
@ -685,6 +690,7 @@ export class BaseTelegramClient {
updated: 0, updated: 0,
fromMessage: peer.fromMessage, fromMessage: peer.fromMessage,
}) })
break
} }
} }

View file

@ -74,9 +74,14 @@ export function getBasicPeerType(peer: tl.TypePeer | number): BasicPeerType {
export function markedPeerIdToBare(peerId: number): number { export function markedPeerIdToBare(peerId: number): number {
const type = getBasicPeerType(peerId) const type = getBasicPeerType(peerId)
if (type === 'user') return peerId switch (type) {
else if (type === 'chat') return -peerId case 'user':
else if (type === 'channel') return MAX_CHANNEL_ID - peerId return peerId
case 'chat':
return -peerId
case 'channel':
return MAX_CHANNEL_ID - peerId
}
throw new Error('Invalid marked peer id') throw new Error('Invalid marked peer id')
} }

View file

@ -60,54 +60,62 @@ export class HtmlMessageEntityParser implements IMessageEntityParser {
name = name.toLowerCase() name = name.toLowerCase()
let entity: tl.TypeMessageEntity let entity: tl.TypeMessageEntity
if (name === 'b' || name === 'strong') { switch (name) {
case 'b':
case 'strong':
entity = { entity = {
_: 'messageEntityBold', _: 'messageEntityBold',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if (name === 'i' || name === 'em') { break
case 'i':
case 'em':
entity = { entity = {
_: 'messageEntityItalic', _: 'messageEntityItalic',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if (name === 'u') { break
case 'u':
entity = { entity = {
_: 'messageEntityUnderline', _: 'messageEntityUnderline',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if ( break
name === 's' || case 's':
name === 'del' || case 'del':
name === 'strike' case 'strike':
) {
entity = { entity = {
_: 'messageEntityStrike', _: 'messageEntityStrike',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if (name === 'blockquote') { break
case 'blockquote':
entity = { entity = {
_: 'messageEntityBlockquote', _: 'messageEntityBlockquote',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if (name === 'code') { break
case 'code':
entity = { entity = {
_: 'messageEntityCode', _: 'messageEntityCode',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
} }
} else if (name === 'pre') { break
case 'pre':
entity = { entity = {
_: 'messageEntityPre', _: 'messageEntityPre',
offset: plainText.length, offset: plainText.length,
length: 0, length: 0,
language: attribs.language ?? '', language: attribs.language ?? '',
} }
} else if (name === 'a') { break
case 'a':
const url = attribs.href const url = attribs.href
if (!url) return if (!url) return
@ -141,7 +149,10 @@ export class HtmlMessageEntityParser implements IMessageEntityParser {
url, url,
} }
} }
} else return break
default:
return
}
if (!(name in stacks)) { if (!(name in stacks)) {
stacks[name] = [] stacks[name] = []
@ -232,18 +243,16 @@ export class HtmlMessageEntityParser implements IMessageEntityParser {
) )
const type = entity.type const type = entity.type
if ( switch (type) {
type === 'bold' || case 'bold':
type === 'italic' || case 'italic':
type === 'underline' || case 'underline':
type === 'strikethrough' case 'strikethrough':
) {
html.push(`<${type[0]}>${entityText}</${type[0]}>`) html.push(`<${type[0]}>${entityText}</${type[0]}>`)
} else if ( break
type === 'code' || case 'code':
type === 'pre' || case 'pre':
type === 'blockquote' case 'blockquote':
) {
html.push( html.push(
`<${type}${ `<${type}${
type === 'pre' && entity.language type === 'pre' && entity.language
@ -258,22 +267,32 @@ export class HtmlMessageEntityParser implements IMessageEntityParser {
: entityText : entityText
}</${type}>` }</${type}>`
) )
} else if (type === 'email') { break
html.push(`<a href="mailto:${entityText}">${entityText}</a>`) case 'email':
} else if (type === 'url') { html.push(
`<a href="mailto:${entityText}">${entityText}</a>`
)
break
case 'url':
html.push(`<a href="${entityText}">${entityText}</a>`) html.push(`<a href="${entityText}">${entityText}</a>`)
} else if (type === 'text_link') { break
case 'text_link':
html.push( html.push(
`<a href="${HtmlMessageEntityParser.escape( `<a href="${HtmlMessageEntityParser.escape(
entity.url!, entity.url!,
true true
)}">${entityText}</a>` )}">${entityText}</a>`
) )
} else if (type == 'text_mention') { break
case 'text_mention':
html.push( html.push(
`<a href="tg://user?id=${entity.userId!}">${entityText}</a>` `<a href="tg://user?id=${entity.userId!}">${entityText}</a>`
) )
} else skip = true break
default:
skip = true
break
}
lastOffset = relativeOffset + (skip ? 0 : length) lastOffset = relativeOffset + (skip ? 0 : length)
} }

View file

@ -209,10 +209,20 @@ export class MarkdownMessageEntityParser implements IMessageEntityParser {
| 'Underline' | 'Underline'
| 'Strike' | 'Strike'
| null = null | null = null
if (c === '_') type = 'Italic' switch (c) {
else if (c === '*') type = 'Bold' case '_':
else if (c === '-') type = 'Underline' type = 'Italic'
else if (c === '~') type = 'Strike' break
case '*':
type = 'Bold'
break
case '-':
type = 'Underline'
break
case '~':
type = 'Strike'
break
}
if (type) { if (type) {
if (!(type in stacks)) stacks[type] = [] if (!(type in stacks)) stacks[type] = []
@ -288,17 +298,23 @@ export class MarkdownMessageEntityParser implements IMessageEntityParser {
} }
let startTag, endTag: string let startTag, endTag: string
if (type === 'bold') { switch (type) {
case 'bold':
startTag = endTag = TAG_BOLD startTag = endTag = TAG_BOLD
} else if (type === 'italic') { break
case 'italic':
startTag = endTag = TAG_ITALIC startTag = endTag = TAG_ITALIC
} else if (type === 'underline') { break
case 'underline':
startTag = endTag = TAG_UNDERLINE startTag = endTag = TAG_UNDERLINE
} else if (type === 'strikethrough') { break
case 'strikethrough':
startTag = endTag = TAG_STRIKE startTag = endTag = TAG_STRIKE
} else if (type === 'code') { break
case 'code':
startTag = endTag = TAG_CODE startTag = endTag = TAG_CODE
} else if (type === 'pre') { break
case 'pre':
startTag = TAG_PRE startTag = TAG_PRE
if (entity.language) { if (entity.language) {
@ -307,13 +323,18 @@ export class MarkdownMessageEntityParser implements IMessageEntityParser {
startTag += '\n' startTag += '\n'
endTag = '\n' + TAG_PRE endTag = '\n' + TAG_PRE
} else if (type === 'text_link') { break
case 'text_link':
startTag = '[' startTag = '['
endTag = `](${entity.url!})` endTag = `](${entity.url!})`
} else if (type === 'text_mention') { break
case 'text_mention':
startTag = '[' startTag = '['
endTag = `](tg://user?id=${entity.userId!})` endTag = `](tg://user?id=${entity.userId!})`
} else continue break
default:
continue
}
insert.push([start, startTag]) insert.push([start, startTag])
insert.push([end, endTag]) insert.push([end, endTag])