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'
let filter: tl.TypeChannelParticipantsFilter
if (type === 'all') {
switch (type) {
case 'all':
filter = { _: 'channelParticipantsSearch', q }
} else if (type === 'banned') {
break
case 'banned':
filter = { _: 'channelParticipantsKicked', q }
} else if (type === 'restricted') {
break
case 'restricted':
filter = { _: 'channelParticipantsBanned', q }
} else if (type === 'mention') {
break
case 'mention':
filter = { _: 'channelParticipantsMentions', q }
} else if (type === 'bots') {
break
case 'bots':
filter = { _: 'channelParticipantsBots' }
} else if (type === 'recent') {
break
case 'recent':
filter = { _: 'channelParticipantsRecent' }
} else if (type === 'admins') {
break
case 'admins':
filter = { _: 'channelParticipantsAdmins' }
} else if (type === 'contacts') {
break
case 'contacts':
filter = { _: 'channelParticipantsContacts', q }
} else {
return type as never
break
}
const res = await this.call({

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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