From 961f494fa2bcf6781b06fe0d3b430ddb008d8f9f Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Sat, 1 Jul 2023 14:06:47 +0300 Subject: [PATCH] use option instead of null --- main.mjs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/main.mjs b/main.mjs index 0aed906..d2a7415 100644 --- a/main.mjs +++ b/main.mjs @@ -1,5 +1,6 @@ import TelegramBot from "node-telegram-bot-api"; import { + option, readerTaskEither as rte, readonlyArray, semigroup, @@ -17,13 +18,13 @@ console.log("The telegram bot listens for updates"); bot.on("channel_post", async (msg) => { const link = extractMessageLink(msg); - if (!link) { + if (option.isNone(link)) { console.log("cannot find link in msg:", msg); return; } pipe( - describeArticle(link), + describeArticle(link.value), rte.map( flow( readonlyArray.foldMap({ @@ -44,21 +45,24 @@ bot.on("channel_post", async (msg) => { )(config)(); }); -// TODO: use option instead function extractMessageLink(msg) { - return getTextLink(msg) || getMessageUrl(msg); + return pipe( + getTextLink(msg), + option.orElse(() => getMessageUrl(msg)), + ); } const RE_URL = /(http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])/; function getMessageUrl(msg) { - return RE_URL.exec(msg.text)[0]; + return option.fromNullable(RE_URL.exec(msg.text)?.[0]); } function getTextLink(msg) { - const textLink = (msg.entities ?? []).find(isTextLink); - return textLink ? textLink.url : null; + return readonlyArray.findFirstMap( + flow(option.fromPredicate(isTextLink), option.map((link) => link.url)), + )(msg.entities ?? readonnlyArray.empty); } function isTextLink(msgEntity) {