refactor: use immutable slice & toReversed

This commit is contained in:
Tony
2026-10-09 09:55:41 +08:00
parent 095aa71d8b
commit 4d4e71a36d
18 changed files with 49 additions and 67 deletions
+2 -2
View File
@@ -191,7 +191,7 @@
"unicorn-js/no-array-from-fill": "error",
"unicorn/no-array-method-this-argument": "error",
// "unicorn/no-array-reduce": "error",
"unicorn/no-array-reverse": "error",
// "unicorn/no-array-reverse": "error",
// "unicorn/no-array-sort": "error",
"unicorn-js/no-array-sort-for-min-max": "error",
"unicorn-js/no-array-splice": "error",
@@ -734,7 +734,7 @@
"unicorn/no-array-callback-reference": "warn",
"unicorn/no-array-reduce": "warn",
"unicorn/no-array-reverse": ["error", { "allowExpressionStatement": false }],
"unicorn/no-array-sort": ["warn", { "allowAfterSpread": true }],
"unicorn/no-await-expression-member": "off",
+1 -1
View File
@@ -63,7 +63,7 @@ async function handler(ctx) {
const limit = ctx.req.query('limit') ? Number.parseInt(ctx.req.query('limit')) : 10;
const items = await Promise.all(
feed.items.splice(0, limit).map((item) =>
feed.items.slice(0, limit).map((item) =>
cache.tryGet(item.link!, async () => {
const response = await got({
method: 'get',
+4 -3
View File
@@ -120,9 +120,10 @@ const visitorId = () => {
sum += Number.parseInt(ch, 16) % 10;
}
const head = String(sum).slice(0, 3).padStart(3, '0');
const parts = uuid.split('-');
parts.splice(1, 0, head + randomString(8 - head.length));
return parts.join('-');
return uuid
.split('-')
.toSpliced(1, 0, head + randomString(8 - head.length))
.join('-');
};
const isString = (value: unknown): value is string => typeof value === 'string';
+1 -2
View File
@@ -66,8 +66,7 @@ async function handler(ctx) {
};
});
const combinedList = [...list, ...otherList];
combinedList.reverse();
const combinedList = [...list, ...otherList].toReversed();
const items = await Promise.all(
combinedList.map((item) =>
+2 -4
View File
@@ -60,9 +60,7 @@ async function handler(ctx) {
const author = contents?.[3] ?? undefined;
const isStar = (contents?.[5] && contents[5] === 'star') ?? false;
if (isStar) {
contents.splice(5, 1);
}
const body = isStar ? contents.toSpliced(5, 1) : contents;
return {
title: `${isStar ? '[STAR] ' : ''}${title}`,
@@ -70,7 +68,7 @@ async function handler(ctx) {
description: renderToString(
<>
{item.resourceList.map((resource) => (resource.externalLink ? <figure>{resource.filename ? <img src={resource.externalLink} alt={resource.filename} /> : <img src={resource.externalLink} />}</figure> : null))}
{raw(md.render(contents?.join('\n\n') ?? ''))}
{raw(md.render(body.join('\n\n')))}
</>
),
author,
+2 -7
View File
@@ -37,13 +37,8 @@ async function handler(ctx) {
author: $(item).find('div.usr-pic a').text(),
};
return info;
});
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].author === '[已注销]') {
list.splice(i, 1);
}
}
})
.filter((info) => info.author !== '[已注销]');
const out = await Promise.all(
list.map(async (info) => {
+2 -2
View File
@@ -125,7 +125,7 @@ const inlineTags = new Map([
]);
const renderRichBlock = (block: any) => {
const chars = [...block.text];
let chars = [...block.text];
const marks = block.inline_style_ranges
.flatMap((range: any) => {
const tag = inlineTags.get(range.inline_style);
@@ -138,7 +138,7 @@ const renderRichBlock = (block: any) => {
})
.toSorted((a: any, b: any) => b.at - a.at || Number(a.html.startsWith('</')) - Number(b.html.startsWith('</')));
for (const mark of marks) {
chars.splice(mark.at, 0, mark.html);
chars = chars.toSpliced(mark.at, 0, mark.html);
}
const tag = blockTags.get(block.block_type) ?? 'p';
return `<${tag}>${chars.join('')}</${tag}>`;
+1 -1
View File
@@ -54,7 +54,7 @@ async function handler(ctx) {
const data = response.data;
const chapter_detail = await Promise.all(
data.mhlist.splice(0, count).map((item) => {
data.mhlist.slice(0, count).map((item) => {
const url = `${host}/api/manhua/${id}/${item.url}`;
return cache.tryGet(url, async () => {
const picContent = await get_pic(url);
+1 -1
View File
@@ -65,7 +65,7 @@ async function handler(ctx) {
// Sort by commits
data.sort((a, b) => a.contributions - b.contributions);
if (order !== 'asc') {
data.reverse();
data = data.toReversed();
}
const items = data.map((item) =>
+1 -2
View File
@@ -104,8 +104,7 @@ const gdgov = async (info, ctx) => {
let pubDate_match = info.pubDate_match;
let pubDate_format = info.pubDate_format;
path.splice(0, 2 + pathstartat);
let pathname = path.join('/');
let pathname = path.slice(2 + pathstartat).join('/');
pathname = pathname === '' ? defaultPath : pathname.endsWith('/') ? pathname : pathname + '/';
const currentUrl = `${rootUrl}/${pathname}`;
+2 -2
View File
@@ -80,8 +80,8 @@ async function handler() {
await familyPriceProductsLoadMore({ pageIndex: 1 });
while (familyPriceProductIds.length) {
productRequests.push(productRequest(familyPriceProductIds.splice(0, 25)));
for (let i = 0; i < familyPriceProductIds.length; i += 25) {
productRequests.push(productRequest(familyPriceProductIds.slice(i, i + 25)));
}
const productResponses = await Promise.all(productRequests);
+21 -20
View File
@@ -86,32 +86,33 @@ async function handler(ctx) {
};
});
items.reverse();
items = await Promise.all(
items.slice(0, limit).map((item) =>
item.isLock
? Promise.resolve(item)
: cache.tryGet(item.link, async () => {
if (!item.isVip) {
const { data: detailResponse } = await got(item.link, {
responseType: 'buffer',
});
items
.toReversed()
.slice(0, limit)
.map((item) =>
item.isLock
? Promise.resolve(item)
: cache.tryGet(item.link, async () => {
if (!item.isVip) {
const { data: detailResponse } = await got(item.link, {
responseType: 'buffer',
});
const content = load(iconv.decode(detailResponse, 'gbk'));
const content = load(iconv.decode(detailResponse, 'gbk'));
content('span.favorite_novel').parent().remove();
content('span.favorite_novel').parent().remove();
item.description += renderBookDescription({
description: content('div.novelbody').html() || undefined,
});
}
item.description += renderBookDescription({
description: content('div.novelbody').html() || undefined,
});
}
delete item.isVip;
delete item.isVip;
return item;
})
)
return item;
})
)
);
const logoEl = $('div.logo a img');
+1 -2
View File
@@ -136,9 +136,8 @@ const parseAttr = (description) => {
const p = new TreeNode(q);
const w = q.start;
while (0 < n.length && n.at(-1)!.attr.start >= w) {
p.children.push(n.pop());
p.children.unshift(n.pop());
}
p.children.reverse();
n.push(p);
}
+2 -2
View File
@@ -40,8 +40,8 @@ async function handler(ctx) {
author,
description: $(item).text(),
link: `https://www.linovelib.com${$(item).attr('href')}`,
}));
items.reverse();
}))
.toReversed();
return {
title: `哩哔轻小说 - ${title}`,
+1 -1
View File
@@ -84,7 +84,7 @@ async function handler(ctx) {
const context = await playwright();
const feed = await parser.parseURL(rssUrl);
const items = await Promise.all(
feed.items.splice(0, 10).map(async (item) => {
feed.items.slice(0, 10).map(async (item) => {
let link = item.link;
let response,
+3 -12
View File
@@ -212,21 +212,12 @@ export const twitterGot = async (
// await cache.set(`twitter:cookie:${auth.token}`, newCookie, config.cache.contentExpire);
// await cache.set(`${lockPrefix}${auth.token}`, '', 1);
// } else {
const tokenIndex = config.twitter.authToken?.indexOf(auth.token);
if (tokenIndex !== undefined && tokenIndex !== -1) {
config.twitter.authToken?.splice(tokenIndex, 1);
}
config.twitter.authToken = config.twitter.authToken?.filter((token) => token !== auth.token);
// if (auth.username) {
// const usernameIndex = config.twitter.username?.indexOf(auth.username);
// if (usernameIndex !== undefined && usernameIndex !== -1) {
// config.twitter.username?.splice(usernameIndex, 1);
// }
// config.twitter.username = config.twitter.username?.filter((username) => username !== auth.username);
// }
// if (auth.password) {
// const passwordIndex = config.twitter.password?.indexOf(auth.password);
// if (passwordIndex !== undefined && passwordIndex !== -1) {
// config.twitter.password?.splice(passwordIndex, 1);
// }
// config.twitter.password = config.twitter.password?.filter((password) => password !== auth.password);
// }
logger.debug(`twitter debug: delete twitter cookie for token ${auth.token} with status ${response.status}, remaining tokens: ${config.twitter.authToken?.length}`);
await cache.set(`${lockPrefix}${auth.token}`, '1', 3600);
+1 -1
View File
@@ -45,7 +45,7 @@ async function handler(ctx) {
const feed = await parser.parseString(response.data);
const items = await Promise.all(
feed.items.splice(0, 10).map((item) => {
feed.items.slice(0, 10).map((item) => {
// generally speaking, changing `item.link` of an existing route could potentially break `item.guid`
// but since the route has been down for at least 8 months, it's probably safe
item.link = item.link!.replace(/^http:\/\//, 'https://');
+1 -2
View File
@@ -179,11 +179,10 @@ async function handler(ctx) {
})
);
out.reverse();
return {
title: mpName || $('.tgme_channel_info_header_title').text(),
link: `https://t.me/s/${id}`,
item: out.filter(Boolean),
item: out.toReversed().filter(Boolean),
allowEmpty: !!mpName,
};
}