<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cheryl Li on Medium]]></title>
        <description><![CDATA[Stories by Cheryl Li on Medium]]></description>
        <link>https://medium.com/@cherylrueichun?source=rss-2257fbe733e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d8r1IzcvRiAKVYlETG98UA.jpeg</url>
            <title>Stories by Cheryl Li on Medium</title>
            <link>https://medium.com/@cherylrueichun?source=rss-2257fbe733e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:33:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cherylrueichun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[產品經理新手入門：用Foodpanda與外送市場拆解「市場機會」]]></title>
            <link>https://medium.com/@cherylrueichun/%E7%94%A2%E5%93%81%E7%B6%93%E7%90%86%E6%96%B0%E6%89%8B%E5%85%A5%E9%96%80-%E7%94%A8foodpanda%E8%88%87%E5%A4%96%E9%80%81%E5%B8%82%E5%A0%B4%E6%8B%86%E8%A7%A3-%E5%B8%82%E5%A0%B4%E6%A9%9F%E6%9C%83-17fe9c10f4e1?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/17fe9c10f4e1</guid>
            <category><![CDATA[市場機會]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 15:31:09 GMT</pubDate>
            <atom:updated>2025-08-10T14:09:24.619Z</atom:updated>
            <content:encoded><![CDATA[<p>提及外送平台，多數台灣人腦海中浮現的會是 Foodpanda 的粉紅熊貓與 Uber Eats 的經典黑白圖樣。這兩大平台不僅主導了台灣的外送市場，背後更上演一場驚心動魄的商業大戲。去年，Uber Eats 意圖收購 Foodpanda，卻因台灣公平會憂慮合併後將形成高達九成的市場壟斷而破局。這一關鍵事件不僅鞏固了雙雄競爭的態勢，也為我們觀察市場變化提供了絕佳的案例。 接下來，這篇產品經理新手學習筆記，將以 Foodpanda 為主題，深入探討外送市場的組成與機會，一步步解析產品經理如何評估市場。</p><h4>什麼是一個市場?</h4><p>一個市場的核心要素是<strong>需求、供給與通路</strong>。這三者齊備，便構成一個有機會的市場。然而，若其中一項有所欠缺，則可能存在兩種情況：一是你發現了一個未被滿足的<strong>創新商業機會</strong>；二是這個商業構想本身就<strong>不具備可行性或獲利性</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*pJMioibXLH6v_0C9QeJfJQ.png" /></figure><ul><li><strong>【缺少通路】的市場機會：</strong> 雖然有<strong>需求</strong>（想吃美食）和<strong>供給</strong>（餐廳），但兩者之間因<strong>距離太遠</strong>而缺乏<strong>通路</strong>。這正是外送平台誕生的契機。當消費者想吃 20 分鐘車程外的餐廳，卻沒有交通工具或時間時，Foodpanda 就提供了「騎手」這個通路，成功滿足了使用者的需求。同樣的商業模式也促成了代購和跨境電商的興起。</li><li><strong>【資訊不對稱】的市場機會：</strong> 在某些市場，雖然<strong>需求和供給都存在</strong>，但由於資訊不透明，導致兩者無法有效連結。房仲業和 104 人力銀行便是最佳例子，他們扮演了關鍵的「媒介」或「通路」角色，為買賣房屋、求職與徵才的公司提供一個溝通橋樑，解決了資訊不對稱的問題。</li><li><strong>【缺少供給】的市場機會：</strong> 如果一個市場有<strong>需求和通路</strong>，卻<strong>沒有人做供給</strong>，這又是為什麼？</li></ul><ol><li><strong>無利可圖</strong>：市場可能已習慣免費服務。例如，網路上的免費文章隨手可得，除非你提供的內容品質遠超免費資訊，否則很難說服使用者付費。</li><li><strong>技術限制</strong>：目前技術尚未成熟，導致產品或服務無法實現。</li><li><strong>未被發掘</strong>：若該市場單純是還沒被人看到，那這就是你切入的絕佳<strong>創新機會</strong>。</li></ol><p><strong>論需求，會有使用者、利害關係人角色，他們分別是誰？</strong></p><p><strong>誰是外送平台的使用者與利害關係人？</strong></p><p><strong>使用者 (User)：</strong> 外送平台主要有三類使用者：<strong>消費者、商家與騎手</strong>。</p><ul><li><strong>消費者</strong>：因沒有交通工具、時間不足或單純想圖個方便，而產生外送的需求。</li><li><strong>商家</strong>：為了增加生意、擴大觸及範圍，卻缺乏自己的外送人力，因而需要平台的支援。</li><li><strong>騎手</strong>：為了賺取收入，透過接單來協助商家將商品送達消費者手中。 這三類使用者環環相扣，共同構成了一個完整的服務循環。</li></ul><p><strong>利害關係人 (Stakeholder)：</strong> 除了直接使用者外，外送平台還有其他重要的利害關係人，例如 <strong>Foodpanda 公司的員工、股東以及政府單位</strong>（如公平會、勞動部）等。</p><p><strong>供給：誰是競爭者？</strong> 「供給」指的是能夠以類似方式滿足市場需求的競爭者。在外送市場，主要可分為幾類：</p><ul><li><strong>直接競爭者 (Direct Competitors)</strong>：與 Foodpanda 提供相似服務的平台，例如最大的競爭對手 <strong>Uber Eats</strong>。</li><li><strong>間接競爭者 (Indirect Competitors)</strong>：提供部分外送服務但非主要業務的平台，例如<strong>全聯的 PXGo!</strong> 和統一超商旗下的 <strong>Foodmo</strong>。</li><li><strong>替代性服務 (Substitutes)</strong>：提供線上點餐或金流服務，但沒有自有騎手的外送系統，例如 <strong>你訂、iCHEF 和 Ocard</strong> 等，他們在某種程度上也與外送平台競爭。</li></ul><p><strong>通路：服務如何傳遞？</strong> 「通路」是指讓產品、服務或資訊得以流通與傳遞的管道，主要包含<strong>物流、金流和資訊流</strong>。 Foodpanda 透過其 <strong>App 和網頁</strong>作為核心平台，整合了這三種「流」：</p><ul><li><strong>資訊流</strong>：消費者透過平台下單，資訊即時傳遞給商家與騎手。</li><li><strong>金流</strong>：消費者在平台上完成付款，款項經由平台處理。</li><li><strong>物流</strong>：平台系統調度騎手在指定時間內取餐並送達消費者手中，並將這些進度同步顯示在App上，讓使用者能掌握最新狀況。</li></ul><h4>外送平台的市場規模</h4><p>為什麼要估市場規模？<br>估算市場規模的意義在於建立<strong>合理的預期和目標</strong>，它能幫助我們判斷一個市場的吸引力、潛力以及我們可能獲得的份額。我們通常會分析三個層面：<strong>總潛在市場 (TAM)、目標市場 (SAM) 和可獲得市場 (SOM)</strong>。</p><p><strong>總潛在市場 (Total Addressable Market, TAM)</strong></p><p><strong>定義:</strong> TAM 代表整個外送服務的理論最大市場規模，假設所有潛在客戶都使用外送服務。</p><p><strong>計算方法:</strong></p><ul><li><strong>基於人數計算:</strong> 目標市場人數* 每位客戶的平均年支出。</li><li><strong>基於行業報告:</strong> 參考行業研究報告，直接獲取外送產業的總體規模。</li><li><strong>自下而上（Bottom-up）</strong>: 單一訂單平均金額 x 平均每人每月訂單數 x 外送服務潛在使用者數 x 12（月）。</li></ul><p><strong>應用</strong>：TAM 是整個市場的最大潛力，再評估是否要決定踏入該市場的時候，如果 TAM 的規模小到無法支撐你預期的商業模式（例如，扣除所有成本後無法獲利），那麼就應該重新評估或放棄</p><p><strong>目標市場 (Serviceable Addressable Market, SAM)</strong></p><p><strong>定義:</strong> SAM 是公司在 TAM 中<strong>可以實際服務的目標市場</strong>。它考慮了地理限制、技術限制以及你所選擇的特定客戶群。</p><p><strong>計算方法:</strong> TAM x 公司可服務地區或鎖定客群的比例<br>SAM 可以是特定城市或區域中，願意使用外送服務的消費者和商家，排除掉無法觸及的地區或不使用外送服務的族群。</p><p><strong>應用</strong>：假設台灣外送市場的 TAM 是 1000 億台幣，而 UberEats 決定只專注於六都（約佔總人口的 70%），且只服務年齡介於 20–50 歲的族群（約佔六都人口的 60%），那麼 SAM 就可以粗略估算為 1000億×70%×60%=420億。</p><p>補充: 上面的假設也可較接近 UberEats 之於 foodpanda 的選擇，後者對於中南部近郊市場也是有投入較多的心力。</p><p><strong>可獲得市場 (Serviceable Obtainable Market, SOM)</strong></p><p><strong>定義:</strong> SOM代表公司在目標市場(SAM)中，實際可以獲得的市場份額，受到競爭、品牌影響力、行銷策略等因素影響。<br>SOM 的關鍵在於<strong>它代表了公司在短中期內（通常是未來 1–3 年)</strong>可以合理預期達成的市場規模。這是最實際、最直接影響營收目標的數字</p><p><strong>計算方法:</strong> SAM * 公司市場份額。<br>SOM 是公司在目標市場中，實際能夠搶佔的市場份額，例如，如果公司在台北市外送市場的市佔率是20%，則SOM就是台北市SAM的20%</p><p><strong>應用</strong>：公司在發展初期，應該<strong>優先專注於 SOM</strong>，確保在這個細分市場中建立穩固的立足點。一旦成功，再逐步擴大服務範圍，進而搶佔 SAM 的其他部分。</p><h4><strong>應該如何選擇市場呢？</strong></h4><p>在投入任何產品之前，該如何評估一個市場是否值得進入？</p><ol><li><strong>跑道多寬？(市場規模與成長性)</strong>：這個市場的潛力有多大？是正在擴張還是已經飽和？</li><li><strong>跑到什麼階段？(產業生命週期)</strong>：市場處於導入期、成長期、成熟期還是衰退期？這決定了我們的策略和機會。</li><li><strong>多少人在跑？(競爭現狀)</strong>：主要競爭對手是誰？他們的優勢和弱點是什麼？</li><li><strong>容不容易進入？(進入門檻)</strong>：進入這個市場的障礙高不高？我們有獨特的競爭力嗎？</li></ol><p>以台灣外送市場為例，雖然其<strong>進入門檻相對較低</strong>（僅需App與平台），但由於已趨近<strong>成熟期</strong>，市場已由兩大巨頭主導，生存難度極高。根據《數位時代》的文章 <a href="https://www.bnext.com.tw/article/82278/mic-2025deliveryreport">2025年外送王出爐！Uber Eats常用率破60%「緊咬foodpanda」：4大平台排名一次看</a>，顯示 <strong>Uber Eats 的常用率已突破60%，緊追 Foodpanda</strong>，市場競爭態勢已非常明朗，有興趣的朋友可以點進去閱讀，裡面針對這四個外送平台有更詳細的介紹。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*iLLhsziV9S8efdNT" /><figcaption>圖取自數位時代:2025年外送王出爐！Uber Eats常用率破60%「緊咬foodpanda」：4大平台排名一次看</figcaption></figure><h4><strong>產業生命周期: 觀察市場的成長可能與機會</strong></h4><ul><li><strong>導入期 (Introduction)</strong>：機會多、不確定性大，但失敗率也高。</li><li><strong>成長期 (Growth)</strong>：是獲利最佳的時期，吸引大量玩家進入，並逐漸出現主要領導者。</li><li><strong>成熟期 (Maturity)</strong>：技術與需求成熟，市場由大型玩家主導，新進者難以取得顯著市佔。</li><li><strong>衰退期 (Decline)</strong>：需求下降，利潤率減少，競爭者開始退出市場</li></ul><h4>如何評估市場競爭現狀？</h4><p>除了產業生命週期外，深入分析競爭現狀是做出決策的關鍵。我們可以從以下幾個維度來觀察：</p><p><strong>市場結構：</strong></p><ul><li><strong>市佔率與壟斷程度</strong>：是否存在已形成壟斷或雙雄鼎立的強勢玩家？</li><li><strong>顧客忠誠度</strong>：評估顧客的<strong>黏著度</strong>和<strong>轉換成本</strong>。以B2B市場為例，企業更換供應商的系統成本高昂，使得顧客轉換意願低。而在外送平台這類B2C市場，雖然轉換成本低（只需下載新App並註冊），但強大的<strong>品牌印象</strong>或<strong>優惠誘因</strong>仍能維持一定的顧客忠誠度。</li></ul><p><strong>競爭策略：</strong></p><ul><li><strong>產品與服務</strong>：市場上的產品功能是否已趨於完整？我們的產品是否有<strong>創新點</strong>或<strong>差異化</strong>的機會？</li><li><strong>價格策略</strong>：市場的價格區間如何？我們的產品是否有<strong>價格競爭力</strong>？</li><li><strong>通路與佈局</strong>：競爭對手的通路是否已全面鋪設？我們是否有機會進入特定通路，並與通路商建立<strong>議價關係</strong>？</li><li><strong>財務與資金實力</strong>：競爭對手的資金是否雄厚，足以發動<strong>價格戰</strong>或<strong>補貼大戰</strong>？這會直接影響新創公司的生存空間。</li></ul><h4>市場是否有進入障礙？ — — 評估潛在競爭威脅</h4><p>除了現有競爭，評估一個市場的<strong>進入障礙（Entry Barrier）</strong>，能幫助我們判斷未來的競爭態勢，這通常是決定是否投入的關鍵。</p><p>在深入分析外送市場的現狀後，我們可能會問：「既然外送市場競爭如此激烈，新進者還有機會嗎？」這個問題的答案，取決於這個市場的「進入障礙」<strong>高不高。以下，我們將探討幾種常見的市場進入障礙，並</strong>將其與外送市場的特性進行對比，幫助我們理解為什麼外送市場雖然看似容易進入，但想生存卻極為困難。</p><ol><li><strong>規模經濟 (Economies of Scale)</strong></li></ol><ul><li><strong>定義</strong>：在<strong>高固定成本、低變動成本</strong>的產業中，產量或規模越大，平均成本就越低，形成成本優勢。</li><li><strong>範例</strong>：鴻海這類硬體製造商接下 iPhone 的大量生產訂單，能大幅攤提固定成本，讓其他小廠難以競爭。</li><li><strong>外送市場分析</strong>：外送平台初期需要投入高昂的<strong>App開發、行銷補貼</strong>等固定成本，而每多一筆訂單的變動成本相對較低。這使得<strong>Foodpanda 和 Uber Eats 這類巨頭能夠透過龐大的訂單量來攤提成本</strong>，形成規模經濟優勢。</li></ul><p><strong>2. 網路效應 (Network Effect)</strong></p><ul><li><strong>定義</strong>：使用者越多，產品的價值就越高，進而吸引更多新使用者加入，形成正向循環。</li><li><strong>範例</strong>：Facebook、Line、Instagram 等社群平台，或是蝦皮等電商平台。使用者越多，買家就越多，賣家就越願意進駐；賣家越多，商品選擇越豐富，也越能吸引買家。對新進者來說，這是極高的護城河。</li><li><strong>外送市場分析</strong>：外送市場的<strong>三邊網路效應</strong>極為顯著。平台上的<strong>商家越多，能吸引更多消費者；消費者越多，能吸引更多騎手；騎手越多，能滿足更多訂單，反過來又吸引更多商家與消費者</strong>。這使得新進平台很難打破現有巨頭的循環</li></ul><p><strong>3. 政策法規 (Government Regulations)</strong></p><ul><li><strong>定義</strong>：某些民生必需的基礎建設或特殊產業，需要政府特許執照才能進入，進入門檻極高。</li><li><strong>範例</strong>：電信業、金融服務、水力發電廠等，皆需取得政府頒發的執照，形成天然的壟斷。</li><li><strong>外送市場分析</strong>：雖然外送平台的進入門檻不像電信業那麼高，但<strong>食品安全、交通法規、勞工權益</strong>等相關法規仍會對營運造成影響。例如，公平會對 Foodpanda 和 Uber Eats 合併案的審核，就是重要的政策法規障礙。</li></ul><p><strong>4. 高資本投入 (High Capital Requirement)</strong></p><ul><li><strong>定義</strong>：與規模經濟相似，但更強調<strong>初期</strong>就需要投入鉅額資金的產業。</li><li><strong>範例</strong>：如台積電的晶圓廠建設、採礦業的設備投資，這類需要高資本才能啟動的產業，能有效阻擋潛在競爭者。</li><li><strong>外送市場分析</strong>：外送平台初期需要<strong>鉅額的行銷費用、優惠補貼</strong>來燒錢搶佔市場，以及App開發、技術維護的成本。這也是為什麼許多小型新創難以進入的原因。</li></ul><p><strong>5. 資源與通路壟斷 (Monopoly of Resources and Channels)</strong></p><ul><li><strong>定義</strong>：透過掌握<strong>關鍵資源、黃金地段或核心通路</strong>，來限制競爭者進入。</li><li><strong>範例</strong>：7–11 善於佔據人潮眾多的黃金地段；App Store 則是 iOS 裝置使用者唯一的應用程式通路，掌握了觸及 iPhone 使用者的關鍵。</li><li><strong>外送市場分析</strong>：對外送平台來說，**「獨家合作商家」<strong>和</strong>「騎手資源」**就是一種重要的通路與資源壟斷。如果大部分熱門餐廳都與兩大平台簽約獨家合作，新平台將難以吸引消費者。</li></ul><p><strong>6. 技術與專利 (Technology and Patents)</strong></p><ul><li><strong>定義</strong>：擁有獨特的技術專利、核心技術或長期研發累積的知識，使競爭對手難以模仿。</li><li><strong>範例</strong>：台積電在晶圓代工技術上的領先地位、航太火箭的專門技術，以及生物科技的專利藥物等。</li><li><strong>外送市場分析</strong>：相較於高科技產業，外送平台的技術專利障礙較低，但其<strong>精密的訂單調度系統、AI 路線規劃演算法</strong>等，仍是需要大量技術投入才能建立的護城河。</li></ul><p>若想要了解 foodpanda 為何市佔率位居第一，之前還要把自己賣給 Ubereats，可以參考商業週刊去年的影片 <a href="https://www.youtube.com/watch?v=rOoNkCDDuuM">#foodpanda 為何要把自己賣給 #ubereats ？最大敵人竟然是自己【懂商業 看商周】Ep.28 #熊猫 #外送平台</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17fe9c10f4e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2025 產品年會心得：產品決策、職涯定錨與我的成長新篇章]]></title>
            <link>https://medium.com/@cherylrueichun/2025-%E7%94%A2%E5%93%81%E5%B9%B4%E6%9C%83%E5%BF%83%E5%BE%97-%E7%94%A2%E5%93%81%E6%B1%BA%E7%AD%96-%E8%81%B7%E6%B6%AF%E5%AE%9A%E9%8C%A8%E8%88%87%E6%88%91%E7%9A%84%E6%88%90%E9%95%B7%E6%96%B0%E7%AF%87%E7%AB%A0-5c184f4b7c81?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c184f4b7c81</guid>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 08:27:17 GMT</pubDate>
            <atom:updated>2025-07-05T09:36:15.360Z</atom:updated>
            <content:encoded><![CDATA[<p>六月很榮幸參與了2025產品年會主議程，主題「CROSS DILEMMA AND BIAS」精準描繪了產品開發中遇到的兩難、衝突與偏見。身為<strong>具備前端經驗的我</strong>，一開始確實有些擔心能否完全融入，但年會的內容精彩紮實，讓我全程投入，收穫良多。</p><figure><img alt="照片來源： Taiwan Product Managers 社群" src="https://cdn-images-1.medium.com/max/1024/1*mZmDYT-wUnQ-XsdXsJJKBA.jpeg" /></figure><p>年會的用心從入場前就清晰可見：像是職涯年資調查、Mentor/Mentee 配對，以及觀眾互動模式（Open to chat/It depends/Leave me alone），都十分有巧思。他們也提供了詳盡的 Notion 年會手冊，包含活動細節、講者介紹和共筆連結，現場還有好吃的療癒甜點，實在地展現了主辦方（產品經理們）對產品體驗的高度重視，整個活動都好喜歡！</p><h3>💡 主議程亮點回顧與我的啟發：</h3><p><strong>1. Fintech 專案從 0 到 1 的實戰經驗</strong></p><p>第一場議程由全支付和 BTSE 區塊鏈公司的產品專家主講，深入探討了 Fintech 與傳統金融的差異、台灣和海外市場的發展機會。兩位與談者也分享了各自專案從 0 到 1 的寶貴經驗，涵蓋了遇到的阻力、問題的應對與解法，到具體實施方案，內容非常啟發人心。</p><p><strong>✨ 講者分享的 Fintech 核心建議：</strong></p><ul><li><strong>持續學習與生活應用：</strong> 產品思維不應僅限於工作範疇，將其融入日常生活，能發現更多洞察與樂趣。</li><li><strong>數據分析與使用者洞察：</strong> 數據是看清事實的基礎，而深入的使用者調查則是確保產品能真正解決痛點的關鍵。</li></ul><p><strong>💡 我的領悟與反思：產品核心與用戶理解</strong></p><p>我深刻體會到，一件商品之所以讓人喜愛，往往是因為它真正解決了實際或心靈層面的問題。若商品無法真正幫助用戶，即便功能再強大，也難以吸引用戶購買。這讓我更明確了「產品的核心價值在於解決問題與創造體驗」。因此，製作 Persona、進行使用者與市場調查、繪製使用者旅程地圖變得至關重要 — — <strong>因為沒有真正理解使用者需求，再多的想像都只會是徒勞。</strong></p><p><strong>2. 女性產品經理的職涯與自我定位</strong></p><p>這場議程從 Bias 談起，探討了女性 PM 的職涯發展、角色定位，以及所面臨的選擇與挑戰。講者們分享了優秀 PM 的特質、面對焦慮的經驗、如何將失敗轉化為養分，以及在規劃產品策略時取得利害關係人支持、爭取升遷的經驗，內容非常具有參考價值。</p><p><strong>💖 特別觸動我的三大分享：</strong></p><ul><li><strong>Tomofun CPO Cammy 的產品決策模板：</strong> 這套模板提供了一個極具實用性的框架，協助團隊系統化地推進產品決策：</li></ul><ol><li><strong>目的：</strong> 我們現在要解決的核心問題是什麼？</li><li><strong>指標：</strong> 我們將如何衡量成功？</li><li><strong>數據：</strong> 透過數據釐清真實情況，用客觀事實證明假設。這正是為了方便團隊做出更精準的判斷與決策。</li><li><strong>可執行方法：</strong> 至少提出 5–10 個多元的解決方案，不應只有單一選項。</li><li><strong>利害關係人回饋：</strong> 邀請相關方參與決策過程，確保共識與支持。</li><li><strong>老闆決策：</strong> 將團隊討論結果呈現給老闆，協助其做出最佳決策。</li></ol><ul><li><strong>IBM Consulting Angie 升遷的秘訣：主動爭取與目標導向</strong> 許多人常抱怨主管沒有看到自己的努力，導致加薪或升遷遙遙無期。Angie 分享的秘訣是：<strong>不要被動等待，要主動出擊。</strong> 她建議與主管溝通期望的升遷職位，確認該職位所需的能力，盤點自身仍欠缺的部分，並與主管討論如何透過參與具體專案來學習並達成這些能力。她的分享讓我深刻體會到<strong>主動性和目標設定的重要性</strong>。</li><li><strong>IBM Consulting Angie 的職涯「定錨」哲學：</strong> Angie 在職涯初期，不以產業或商業模式為導向，而是思考「未來希望被大家如何記得」。她選擇了「體驗策略」作為自己的關鍵字，受賈伯斯啟發，致力於將「體驗」深植於產品中。</li></ul><p><strong>✨ 我的反思與職涯展望：</strong> 這個覺察方式讓我深受啟發。如同產品需要一個「定錨」點一樣，我的人生這個專案也需要清晰的定位。未來，我希望我的標籤是：</p><ul><li><strong>「創造者」：</strong> 打造出很棒、受人喜愛、能真實幫助他人生活的工具、軟體或產品。</li><li><strong>「溫暖的連結者」：</strong> 能貼心理解他人心情，在需要時成為一束微光，讓人感到溫暖與喜悅。雖然我不一定能做到善解人意，但我真心希望讓身邊的人感到溫暖。</li></ul><h3>3. 產品策略的本質與實踐</h3><p>SHOPLINE 的 VP Liwei Yeh 針對「什麼是產品策略」和「有什麼產品策略」做了深入分享。簡而言之，產品策略的目的是<strong>找到產品對客戶與商業能帶來什麼樣的價值，如何贏得市場，並引導團隊朝同一個方向努力。</strong> 他也提到，由於每家公司情況不同，產品策略無法生硬地套用模板。</p><p>至於「有什麼產品策略」，Liwei 強調，產品策略首先要思考的就是<strong>如何將產品推向市場，找到 Product Market Fit (PMF)</strong>。這必須同時考慮「內在」和「外在」因素，從一開始的學習與思考，到最終形成一套成熟的產品策略。</p><figure><img alt="照片來源： Taiwan Product Managers 社群" src="https://cdn-images-1.medium.com/max/1024/1*L9UunUAeIVZBbC2XCGhr2w.jpeg" /></figure><p><strong>內部因素：</strong></p><ul><li><strong>公司的財務規模：</strong> 理解公司的收入與成本結構。</li><li><strong>產品現狀：</strong> 盤點現有產品，建立「產品矩陣」，明確每個產品在商業上的角色。</li><li><strong>技術框架：</strong> 意識到技術框架大約每 3–5 年會進入一個大的迭代週期。</li></ul><p><strong>外部因素：</strong></p><ul><li><strong>市場客戶：</strong> 深入理解客戶、理解市場，親自與客戶接觸，體驗當用戶的感覺。</li><li><strong>競爭對手：</strong> 贏得市場需要靠差異化，無論是產品功能差異還是定價差異。</li><li><strong>經濟環境：</strong> 景氣好壞將影響產品策略的積極或保守態度（例如：積極向上或準備過冬）。</li></ul><p><strong>✨ 我的想法與實踐啟示：</strong> 我認為，儘管大家對產品策略的定義可能略有不同，但其本質始終圍繞著<strong>商業目標</strong> — — 即讓產品能夠成功銷售、被用戶使用，確保公司能持續經營下去。在初期為了找到 PMF，產品策略可能需要不斷地調整與驗證；而一旦找到 PMF，產品策略便會趨於長期穩定，成為團隊齊心努力的目標。</p><p>最困難的往往是<strong>如何開始</strong>。講者分享的建議非常受用：可以先從<strong>學習公司資深前輩的思考方式</strong>、<strong>分析業界成功案例</strong>，並<strong>深入思考他人做出某個策略決定的原因</strong>。我認為這點非常關鍵，因為這些都是從入門培養到資深產品經理的重要途徑。</p><h3>結語與感謝</h3><p>最後，我衷心<strong>感謝主辦人 Eileen 以及所有主辦方們</strong>，如此用心、精彩地舉辦了這場產品年會。從我一開始加入臉書社團 <a href="https://www.facebook.com/share/g/1Eyo9ju3fd/">Taiwan Product Managers</a>，就發現裡面分享的乾貨滿滿，在社團潛水半年多，產品年會活動一出來，我對實際活動內容一無所知就直接購買了盲鳥票，結果真的物超所值(笑)。雖然我目前還不是產品經理，但我很感謝有這麼一群熱情分享的人，舉辦了如此高水準的活動。這場年會不僅讓我收穫豐碩，也讓我對轉職產品經理的目標更加明確，對未來充滿了期待。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjOqJBlo1lpXyQGYU4p37Q.png" /></figure><p>以上心得僅為本次年會的部分內容。強力推薦想查看完整精彩回放，可以到 Hahow 課程平台購買<a href="https://hahow.in/courses/680a57f0e7cfb571b972de14">「跨越焦慮的產品開發之道｜2025 軟體產品年會 — 完整回放」</a>，結帳時輸入折扣碼「HHTWPC」還能享有 200 元折扣優惠喔！</p><p>#產品年會 #產品經理轉型 #產品思維 #用戶體驗 #數據驅動 #職涯發展 #Fintech #個人成長</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c184f4b7c81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios 練習筆記]]></title>
            <link>https://medium.com/@cherylrueichun/axios-%E7%B7%B4%E7%BF%92%E7%AD%86%E8%A8%98-6297e8617b44?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6297e8617b44</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[axios-interceptor]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 15:20:51 GMT</pubDate>
            <atom:updated>2023-07-22T15:20:51.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Axios 是 HTTP Client 可在瀏覽器和 Node.js 上執行回傳 Promise 的結果，告訴你這個請求資源 (可以是任何 type) 成功或失敗的結果和它拿回的資料。</p><p>在瀏覽器會發送 XMLHttpRequest 請求，在 Node.js，使用 http request，請求物件會與服務器交互，Axios 可以透過 URL 去取得資料更新頁面，但不打斷使用者做的其他事情。</p><p>如果這個溝通是需要即時、雙向的溝通，可以改使用 WebScokets，不同於 http request 的單向溝通，伺服器也可以主動發送 events。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h_mLtzU7hqhO5bV8.jpg" /><figcaption><a href="https://www.cloudsigma.com/configuring-a-rest-api-with-axios-in-vue-js-a-tutoril/">image resource: Configuring a REST API with Axios in Vue.js: A Tutorial</a></figcaption></figure><p>在這篇文章，我會練習基本使用方法:</p><ul><li>基本設置: GET/POST/PUT/PATCH/DELETE</li><li>Error handling 處理錯誤訊息</li><li>設置 Timeout</li><li>axios.create() 建立實例</li><li>使用 Interceptors 攔截器</li></ul><h3>基本設置: GET/POST/PUT/PATCH/DELETE</h3><p>可安裝 $ npm install axios</p><pre>const axios = require &#39;axios&#39;<br>或者 React 用 import<br>import axios from &#39;axios&#39;</pre><p>或使用 CDN 連結像 <a href="https://www.youtube.com/watch?v=6LyagkoRWYA">Axios Crash Course | HTTP Library</a></p><p>在這裡，我會跟著上面影片使用 <a href="https://jsonplaceholder.typicode.com/">Jsonplaceholder free fake api</a> 來做串接練習:</p><h4>function getTodos() GET 取得全部資料 或限制多筆/單筆資料</h4><pre>function getTodos() {<br>  axios({<br>    method: &#39;get&#39;,<br>    url: &#39;https://jsonplaceholder.typicode.com/todos&#39;,<br>    params: {<br>      _limit: 5,<br>    },<br>  })<br>    .then((res) =&gt; console.log(res))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><p>使用 get 方法拿回所有 todos 資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PV4UP6PZNMGxTd7b.png" /></figure><p>若想要限制取回資料的筆數，可加上 params: {_limit:5} 來限制每次 get request 只取回 5 筆。<br>data:(5) 就只會顯示 5 筆而不是原來的 data:(200)筆</p><p>常用以下簡潔的方式改寫，並套用 fn showOutput 呈現需求的畫面和資料:</p><pre>axios<br>    .get(&#39;https://jsonplaceholder.typicode.com/todos?_limit=5&#39;)<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; console.log(err));</pre><p>在這裡限制取得資料的筆數，可以直接把 parameter 用 ?_limit=5 寫在 URL 後面。</p><p>axios 如果不寫 get、post 取得資料的方法等方法，默認設置就是 get 方法，但是直接寫 get 可以更清楚的表示現在是用什麼方法，所以我也是會習慣寫。</p><h3>function addTodo ＝＞ POST 新增資料</h3><p>記得要對應新增資料的屬性名稱，格式不正確就會跳錯誤喔!<br>譬如說，data 裡完成屬性名稱叫做 completed，就不能寫 finished，不然資料庫的表格就亂掉啦~</p><pre>function addTodo() {<br>  axios({<br>    method: &#39;post&#39;,<br>    url: &#39;https://jsonplaceholder.typicode.com/todos&#39;,<br>    data: {<br>      title: &#39;create new todos&#39;,<br>      completed: false,<br>    },<br>  })<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><p>或改寫成簡潔的寫法:</p><pre>// POST REQUEST<br>function addTodo() {<br> axios<br>    .post(&#39;https://jsonplaceholder.typicode.com/todos&#39;, {<br>      title: &#39;create new todos&#39;,<br>      completed: false,<br>    })<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><h4>function updateTodo =&gt; PUT/PATCH 修改資料</h4><p>記得這裡路由要加上特定的 id，axios 才知道要修改哪筆路由的單筆資料</p><p><strong>PUT/PATCH 同為更新資料，它們的差異在哪?</strong></p><p>PUT 更新: 直接取代這個特定資料<br>PATCH 更新: 只更新我們寫的屬性資料</p><p>可以從下面截圖看兩個方法取回的 data 會更清楚~</p><p>記得在路由後加上我們要更新的資料內容:</p><pre>function updateTodo() {<br>  axios<br>    .put(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;, {<br>      title: &#39;update this item&#39;,<br>      completed: true,<br>    })<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/0*-Tv5RNn6Zx9c5igW.png" /></figure><p>若把上面的 put 方法改成 patch 的話，取回的資料則會是下圖:<br>原本的 userId 不會像 put 方法傳回的內容直接被整個取代掉了~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*gxahuiMPx6WgZYwA.png" /></figure><h4>function deleteTodo 刪除特定 todo 資料</h4><p>因為要刪除特定 todo 的單筆資料，也要在路由的最後加上 id。<br>最後一個，我來用 async await + try catch 的寫法來練習。</p><pre>// DELETE REQUEST<br>async function removeTodo() {<br>  try {<br>    const data = await axios.delete(<br>      &#39;https://jsonplaceholder.typicode.com/todos/2&#39;<br>    );<br>    return showOutput(data);<br>  } catch (err) {<br>    console.log(err);<br>  }<br>}</pre><p>DELETE 方法回傳的 data 就不會有資料，但還是可以用上面 async await 的方式去使用別的方法來操作資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*00r4YOEBMUXv_qOi.png" /></figure><h4>使用 axios.all + axios spread 同時呼叫不同 api 取得資料</h4><p>使用 axios.all 陣列裡放兩個 request，就可以同時呼叫這兩個 api 請求。</p><p>這裡就像是 Promise.all 的概念，任一回傳的 promise 有錯誤，你就會直接收到 error，兩個資料都拿不到。</p><p>可以使用最直接的方式，使用 index 取出需要的資料:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*mdA2-8-T8f5T4Izt.png" /></figure><p>或使用 axios.spread 取回 第一個 api 資料變數取為 todo、第二個 api 資料變數取為 post。</p><p>並套用 post 資料呈現畫面:</p><pre>// SIMULTANEOUS DATA<br>function getData() {<br>  axios<br>    .all([<br>      axios.get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;),<br>      axios.get(&#39;https://jsonplaceholder.typicode.com/posts/1&#39;),<br>    ])<br>    .then(axios.spread((todo, post) =&gt; showOutput(posts)))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*Mm5MSwQu52rQKYht.png" /></figure><h3>Error Handling 處理錯誤訊息</h3><p>錯誤的 URL 連結， 可以利用回傳的錯誤狀態碼來顯示給使用者不同的錯誤呈現畫面，例如: 404 Not found</p><p>可以去 console.log 出來看看哦!</p><pre>function errorHandling() {<br>  axios<br>    .get(&#39;https://jsonplaceholder.typicode.com/todoss&#39;)<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; {<br>      if (err.response) {<br>        console.log(err.response.data);<br>        console.log(err.response.headers);<br>        console.log(err.response.status);<br>      }<br>      if (err.response.status === 404) {<br>        alert(&#39;Error: Page Not found&#39;);<br>      } else if (err.request) {<br>        // request was mad but no response<br>        console.error(err.response);<br>      }<br>    });<br>}</pre><h3>設置 Timeout</h3><p>在 getTodos 請求加上 timeout: 5000毫秒 (5秒)的設定，如果超過五秒還沒得到 response 請求送出後伺服器回覆的資料，就會得到 error。</p><pre>function getTodos() {<br>  axios<br>    .get(&#39;https://jsonplaceholder.typicode.com/todos?_limit=5&#39;, {<br>      timeout: 5000,<br>    })<br>    .then((res) =&gt; showOutput(res))<br>    .catch((err) =&gt; console.log(err));<br>}</pre><h3>Axios.create() 來創造實例</h3><p>axios.create([config]) 新增一個 axios instance 來建立客製化的 config</p><p>先建立一個 axiosInstance, 在介紹 Interceptors 攔截器可以接著使用設定基本 URL 的實例。</p><pre>const axiosInstance = axios.create({<br>  baseURL: &#39;https://jsonplaceholder.typicode.com/&#39;<br>})</pre><p>axios 官方文件<a href="https://axios-http.com/docs/req_config">這裡</a>也有各個 config 設定的使用說明</p><p>可以在 config 增加更多的設定:</p><pre>const instance = axios.create({<br>  baseURL: &#39;https://some-domain.com/api/&#39;,<br>  timeout: 1000,<br>  headers: {&#39;X-Custom-Header&#39;: &#39;foobar&#39;}<br>});</pre><h3>Interceptors 攔截器: 在 .then/.catch 前攔截request 或 response 來 do something</h3><p>這個攔截器就可以用來做身分驗證，在使用者要求進入會員限定的頁面時，判別使用者是否登入，有相對應的 token (入場卷)就可導入相對應頁面。</p><p>沒有的話，就能請使用者先登入在進入該頁面。</p><p>那我們來看看怎麼使用吧~</p><pre>// 添加 request interceptor<br>axios.interceptors.request.use(function(config){<br>  // 在此加入需求發送前要執行的程式<br>  return config<br>}, function(error){<br>  // 在此加入若 request 有錯誤<br>  return Promise.reject(error)<br>})</pre><pre> // 添加 response interceptor<br> axios.interceptors.response.use(function(response){<br> // 任何 2XX 成功的狀態碼都可觸發此 function<br> // 針對 response data 做操作<br> return response<br> }, function(error){<br>  // 任何 2XX 以外的狀態碼都可觸法此 function<br>  // 針對 error 回傳資料做操作<br>  return Promise.reject(error)<br> })</pre><p>使用我們在 axios.create 建立的 axiosInstance 來設置攔截器，在客戶端發出請求前確認是否含有 token (身分驗證票卷)。</p><p>如果有，我們就把 token 塞入 config 的 headers[‘Authorization’] 裡。 伺服器收到這個請求時就知道這個請求瀏覽會員限定的頁面是會員，並讓此使用者順利導覽到該頁面。</p><p>(此處 local storage 存的 token 是在登入的時候從伺服器拿到之後就要存入 local storage，這裡才可以拿來驗證哦!)</p><pre>axiosInstance.interceptors.request.use(<br> (config) =&gt; {<br>  const token = localStorage.getItem(&#39;token&#39;);<br>  if(token){<br>   config.headers[&#39;Authorization&#39;] = `Bearer${token}`;<br>  }<br>  return config<br> }, <br> (error) =&gt; {<br>   console.log(error)<br> }<br>)</pre><p>後面就可以拿來使用了!</p><pre>// 瀏覽所有的todos<br>export const getTodos = async () =&gt; {<br>  try {<br>    const res = await axiosInstance.get(`${baseUrl}/todos`);<br>    // 拿到資料庫裡存的所有的todos<br>    return res.data;<br>  } catch (error) {<br>    console.error(`[Get all todos failed]`, error);<br>  }<br>};</pre><h4>整理筆記資料來源:</h4><p><a href="https://axios-http.com/docs/instance">Axios 官方文件</a><br><a href="https://medium.com/i-am-mike/%E4%BD%BF%E7%94%A8axios%E6%99%82%E4%BD%A0%E7%9A%84api%E9%83%BD%E6%80%8E%E9%BA%BC%E7%AE%A1%E7%90%86-557d88365619">使用Axios你的API都怎麼管理？</a><br><a href="https://www.youtube.com/watch?v=6LyagkoRWYA">Axios Crash Course | HTTP Library</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6297e8617b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking in React 筆記]]></title>
            <link>https://medium.com/@cherylrueichun/thinking-in-react-%E7%AD%86%E8%A8%98-3456526122bb?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3456526122bb</guid>
            <category><![CDATA[thinking-in-react]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[official-document]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 00:51:44 GMT</pubDate>
            <atom:updated>2023-06-25T00:51:44.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0CD3cjbt3dgKzbab" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>重讀 Thinking in React，這篇是用 React 建專案很重要的一篇核心概念，這篇筆記來重讀畫重點 ❤️</p><p>當我們正準備使用 React 來打造 UI (User Interface) 的時候:</p><p><strong>1. 需要先把它拆開成一個個元件。<br>2. 形容每一個元件裡會發生的 “不同的畫面上的狀態 (states)”。<br>3. 連結元件確認資料流 (data flow)。</strong></p><p>這篇會以用 React 打造一個可搜尋的產品資料表為例來解釋思考的步驟。</p><p>首先想像你已經有了 JSON API 資料，並且有設計稿模型。</p><p>JSON API 長這樣</p><pre><br>[<br> { category: “Fruits”, price: “$1”, stocked: true, name: “Apple” },<br> { category: “Fruits”, price: “$1”, stocked: true, name: “Dragonfruit” },<br> { category: “Fruits”, price: “$2”, stocked: false, name: “Passionfruit” },<br> { category: “Vegetables”, price: “$2”, stocked: true, name: “Spinach” },<br> { category: “Vegetables”, price: “$4”, stocked: false, name: “Pumpkin” },<br> { category: “Vegetables”, price: “$1”, stocked: true, name: “Peas” }<br>]<br></pre><p>Mockup 設計稿</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*3xOzEM4eRPMU4LMN.png" /></figure><p>因為我現在還在一人學習的階段，我最近要規劃我的新專案，我就需要先畫出設計稿，去設想要如何拆分元件，畫面變化的狀態有哪些，初擬我需要的資料，如何連結元件確認資料流走向。</p><h4>步驟1 : 將 UI 有層次架構的拆分成元件</h4><p>在設計稿上開始在元件和次元件上先畫出方格並作命名，如果是跟設計師合作，設計稿的工具裡應該都已經命名好這些元件了。</p><p>● 程式碼: 要注意遵守一個元件只做一件事情，如果元件持續變的肥大，就需要拆分成不同的元件。<br>● CSS: 思考要使用什麼 CSS 選擇器<br>● 設計: 思考要如何組織設計各層</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3nIVEzQJBCT3oxVs.png" /></figure><p>1. FilterableProductTable 包含整個 App<br>2. SearchBar 收到使用者的輸入<br>3. ProductTable 呈現產品列表，並按照使用者的輸入來呈現篩選內容。<br>4. ProductCategoryRow 呈現每個種類的主標題<br>5. ProductRow 呈現每一列的產品</p><p>階層關係的呈現就會是:</p><p>* FilterableProductTable<br> * SearchBar<br> * ProductTable<br> * ProductCategoryRow<br> * ProductRow</p><h4>步驟2 建立 React 的靜態版本</h4><p>了解 UI 組織階層規劃，就可以先打造一個靜態版本的渲染畫面，<strong>還先別加</strong>任何的互動內容。</p><p>也就是說先不要設置 state! 開始設計互動是要去思考非常多的，要如何設計重複使用的元件，如何使用 props 去傳遞資料。</p><p>可以先從最頂端的階層開始寫到內層: <strong>FilterableProductTable </strong>到 <strong>ProductRow</strong>，也可以反著順序寫。</p><p>在比較簡單的專案，比較適合由上往下去寫; 但若是比較複雜和大的專案，建議由下往上撰寫。</p><p>建置完靜態版本的元件，就可以思考要怎麼去串資料流 (data flow)，因為資料流只能由上到下傳遞。</p><h4>步驟3 找到 UI 最小且可完整代表的狀態 (state)</h4><p>最重要去建立 state 的一個準則是 Keep it dry (不要重複你自己)。<br>舉例來說，如果你要建立一個購物清單，我們可以將品項以陣列的方式存在”狀態”裡。</p><pre><br>const shoppingList = [“衛生紙”, “鮮奶”, “布丁”, “蘋果”]<br>const [list, setList] = useState(shoppingList)</pre><pre>// 避免設置重複的 state<br>let quantity = shoppingList.length X<br>const [number, setNumber] = useState(quantity) X<br></pre><p>要是我們要顯示出清單裡品項的數量，不要設置另一個數量的”狀態”，用陣列的長度去計算即可。</p><p>= &gt; 直接用 list.length</p><p>現在，思考專案裡的所有資料:</p><p>1. 原始的產品清單<br>2. 使用者輸入的搜尋文字<br>3. 核取方塊的值<br>4. 篩選過後的產品清單</p><p><strong>哪些是 state ? 並辨認哪些不是 ?</strong></p><p><strong>* 它是否一直保持不變 ? 如果是，他不是 state<br>* 它是否是從父元素以 props 傳下？ 如果是，他不是 state<br>* 它是否可從現有的元件中的 state 或 props 去計算得到 ? 如果是，它絕對不是 state</strong></p><p>讓我們來檢核一次上面的資料:</p><p>1. 原始的產品清單是從 props 傳遞的，所以不是 state<br>2. 使用者輸入的搜尋文字會一直改變，且無法透過別的地方來計算，應可設成 state<br>3. 核取方塊的值會一直改變，且無法透過透過其他方式計算，應可設成 state<br>4. 篩選過後的產品清單不需要設成 state，因為它可以從原始的產品清單透過搜尋的文字和核取方塊的值兩個條件篩選得出</p><p>props vs. state</p><p>有一些父元件會存取一些資訊在 state 裡 (所以父元件可以更新其值)，並將此資料以 props 的方式傳給子元件。</p><h4>步驟4 確認 state 應該存在 “在哪裡”?</h4><p>確認好 app 裡的最小資料狀態，我們需要辨認出哪個元件負責更新 “狀態”或者擁有這個”狀態”。</p><p>需要記住: React 是單向資料流，是從父元件的階層傳向子元件。<br>以上概念可能還不清楚，我們可以透過以下步驟來釐清。</p><p>在 APP 裡的每一個”狀態”:</p><p>1. 識別每個元件的狀態組件<br>2. 找到它們最接近的共同父元件 — 層次結構位於它們之上的元件<br>3. 決定應該把 state 設置在哪一個元件<br> * 大部分的時候，可直接把”狀態”放在它們共同的父元件<br> * 你也可以將其”狀態”放在共同父元件之上的元件<br> * 如果沒有辦法找到適合的元件來擁有這個”狀態”，我們也可以直接創建一個新的元件來保存這個”狀態”，並將其添加到共同父元件之上的階層。</p><p>現在，來實際應用上面的策略來確認”狀態”應該存在哪?</p><p>1. 識別每個元件的狀態組件:<br> * ProductTable 需要根據該狀態去篩選產品清單 (搜尋文字和核取方塊的值 true or false)<br> * 搜尋框需要顯示該”狀態” (透過搜尋文字和核取方塊的值)<br> <br>2. 找到它們最接近的共同父元件 — 層次結構位於它們之上的元件<br> * 第一個最接近的共同父元件是 FilterableProductTable</p><p>3. 決定應該把”狀態”設置在哪一個元件<br> * 會將篩選的文字和核取方塊”狀態”的值保留在 FilterableProductTable</p><p>所以 state 的值會被保存在 FilterableProductTable</p><pre><br>function FilterableProductTable({ products }) {<br> const [filterText, setFilterText] = useState(‘’);<br> const [inStockOnly, setInStockOnly] = useState(false);<br></pre><p>然後將 filterText 和 inStockOnly 用 props 傳遞的方式傳到 ProductTable 和 SearchBar。</p><p>但是，如果要將使用者的輸入文字來呈現在 SearchBar 上，我們尚未完成，還需要再完成最後一個步驟!</p><p><strong>要將 input 的 value 交給 onChange 事件來控制</strong></p><pre><br>&lt;div&gt;<br> &lt;SearchBar <br> filterText={filterText} <br> inStockOnly={inStockOnly} /&gt;<br> &lt;ProductTable <br> products={products}<br> filterText={filterText}<br> inStockOnly={inStockOnly} /&gt;<br>&lt;/div&gt;<br></pre><h4>步驟5 加入逆向的資料流</h4><p>目前如果我們去改動 useState 的初始值，是可以看到畫面上的內容被更改，但是若要真的根據使用者的輸入去做變化，要使用 form 的組件去做另一種資料流。</p><p>我們需要去更新兩個狀態的值，使用 setFilterText 和 setInStockOnly。</p><p>並且在 SearchBar 加上 onChange 的事件</p><pre><br>function FilterableProductTable({ products }) {<br> const [filterText, setFilterText] = useState(‘’);<br> const [inStockOnly, setInStockOnly] = useState(false);<br><br> return (<br> &lt;div&gt;<br> &lt;SearchBar <br> filterText={filterText} <br> inStockOnly={inStockOnly} <br> onFilterTextChange={setFilterText} <br> onInStockOnlyChange={setInStockOnly} /&gt;<br> &lt;ProductTable <br> products={products} <br> filterText={filterText}<br> inStockOnly={inStockOnly} /&gt;<br> &lt;/div&gt;<br> );<br>}<br><br>…</pre><pre>function SearchBar({<br> filterText,<br> inStockOnly,<br> onFilterTextChange,<br> onInStockOnlyChange<br>}) {<br> return (<br> &lt;form&gt;<br> &lt;input <br> type=”text” <br> value={filterText} placeholder=”Search…” <br> onChange={(e) =&gt; onFilterTextChange(e.target.value)} /&gt;<br> &lt;label&gt;<br> &lt;input <br> type=”checkbox” <br> checked={inStockOnly} <br> onChange={(e) =&gt; onInStockOnlyChange(e.target.checked)} /&gt;<br> {‘ ‘}<br> Only show products in stock<br> &lt;/label&gt;<br> &lt;/form&gt;<br> );<br>}<br></pre><p>這篇筆記來自於官方文件 [<a href="https://react.dev/learn/thinking-in-react">Thinking in React</a>]，下一篇可前往<a href="https://react.dev/learn/adding-interactivity"> [Adding Interactivity]</a> 去看看 useState 如何更新狀態，我們該如何在 React 增加互動性的內容。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3456526122bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode刷題: 複習Promise & Async Await]]></title>
            <link>https://medium.com/@cherylrueichun/leetcode%E5%88%B7%E9%A1%8C-%E8%A4%87%E7%BF%92promise-async-await-93950d4f670b?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/93950d4f670b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 16:50:03 GMT</pubDate>
            <atom:updated>2023-06-21T06:17:23.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*anbjv21wkOud1jTi" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Promise 物件是一個代表即將完成或失敗的非同步操作，和它產生結果的值 (resolve, reject)</strong></p><p>Promise 的出現是為了解決非同步過度巢狀的問題，也就是常聽到的 callback hell 的問題。</p><p>忘記的朋友看到下面這張圖就應該能勾起回憶了吧 😆</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*hK7hga0bKz-JQITPCxGKYw.jpeg" /><figcaption><a href="https://dev.to/jerrycode06/callback-hell-and-how-to-rescue-it-ggj">Callback Hell and How to Rescue it ?</a></figcaption></figure><p><strong>Promise 語法:</strong></p><p>new Promise( /* executor */ function(resolve, reject) { ... } );</p><p>executor 為依序接收兩個參數的函式: resolve 及 reject（實現及拒絕回呼函式）</p><p>Promise 物件會處於以下三種狀態之一:</p><ul><li><em>擱置（pending）</em>：初始狀態，不是 fulfilled 與 rejected。</li><li><em>實現（fulfilled）</em>：事件已執行完畢且成功操作，回傳 resolve 結果。</li><li><em>拒絕（rejected）</em>：事件已執行完畢但操作失敗，回傳 rejected 的結果。</li></ul><pre>function callback(resolve, reject){<br>  // Async operation , network call, disk read I/O<br>  // Async non-block language<br>  setTimeout(()=&gt; resolve(), 1000)<br>}<br><br>const promise = new Promise(callback)<br><br>promise.then(() =&gt; console.log(&quot;hello&quot;))<br>       .catch(() =&gt; console.log(&quot;rejected&quot;))</pre><p>如果 resolve, reject 都沒有使用，只會console.log 出hello <br> .then/.catch/.finally 就都不會被處理，promise 狀態就會永遠停在 pending 狀態。</p><pre>function callback(resolve, reject) {<br>  console.log(&quot;hello&quot;)<br>}<br><br>const promise = new Promise(callback)<br>promise.then(() =&gt; console.log(&quot;hello&quot;))<br>       .catch(() =&gt; console.log(&quot;rejected&quot;))<br>       .finally(()=&gt; console.log(&quot;Promise completed&quot;))</pre><p><strong>Async / Await 的出現是為了什麼 ?</strong></p><p>它是Promise 的語法糖，也就是基於 Promise 的結構上，Async / Await 讓非同步的 Promise 可以更直觀的被使用，新手也可以容易上手的非同步程式！</p><p>不過還是要好好了解 Promise ，才可以真正了解 Async / Await。</p><p><strong>當 async function 被呼叫時，它會回傳一個 Promise 物件</strong></p><p>回傳值是一個 Promise 可以是 即將 resolved 的非同步函式，也可以是被例外拋出錯誤的 rejected。</p><p>await 表達式會暫停執行程式碼，確保等到 Promise return 值是 fulfilled 或 rejected ，讓程式碼執行的向同步函式一樣。</p><p>如果 async 函式回傳一個值 沒有明確寫是 Promise，它也會是隱藏式的被包在 Promise 中。</p><p>例如:</p><pre>async function foo() {<br>  return 1;<br>}</pre><p>相近於以下程式碼</p><pre>function foo() {<br>  return Promise.resolve(1);<br>}</pre><p>如果有回傳值，第二個 async function Promise 如果 resovle 成功會回傳hello =&gt; 使用 then 來接著，若成功回傳 resolve 值 “hello”<br><strong>hello().then((res) =&gt; console.log(res)) // hello</strong></p><pre>function hello (){}<br>console.log(hello())  // undefined<br><br>async function hello(){}  <br>console.log(hello())   // Promise {undefined}<br><br>function hello() {return &quot;hello&quot;} <br>console.log(hello())   // hello<br><br>async function hello(){return &quot;hello&quot;}  <br>console.log(hello())   // Promise {&#39;hello&#39;}<br><br>hello().then((res) =&gt; console.log(res)) // hello</pre><p>來試寫兩題 LeetCode 的 Promise 題目吧! <br>Sleep 比較簡單， Promise Time Limit 比較複雜一點，但兩個都是歸類在easy 的題目。</p><p>要看完整題目內容的朋友可以點進去連結裡</p><p><a href="https://leetcode.com/problems/sleep/description/"><strong>2621. Sleep</strong></a></p><p>Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.</p><p>給定一個正整數 millis，寫一個非同步函式在經過睡眠 millis milliseconds, 它可以 resolve 任何值。</p><p><strong>Example 1:</strong></p><pre>Input: millis = 100<br>Output: 100<br>Explanation: It should return a promise that resolves after 100ms.<br>let t = Date.now();<br>sleep(100).then(() =&gt; {<br>  console.log(Date.now() - t); // 100<br>});</pre><p><strong>Example 2:</strong></p><pre>Input: millis = 200<br>Output: 200<br>Explanation: It should return a promise that resolves after 200ms.</pre><p><strong>思路: 要寫一個非同步的 sleep 函式，參數會帶入 millis 代表多少秒以後要轉成 fulfilled 的狀態，並且可以resolve任何值。</strong></p><p>看到 async function 和 resolve 就知道要 return new Promise。<br>在 executor 放入 resolve ，設定 setTimeout 在 millis 毫秒後 resolve( )。<br>= &gt; 不放任何參數代表可以 resolve 任何值</p><p>因為這裡不需要接住 error，可以不用放 reject。</p><p>以下為 解答:</p><pre>async function sleep(millis) {<br>    return new Promise((resolve) =&gt;{<br>       setTimeout(() =&gt; {<br>           resolve()<br>       }, millis)<br>    })<br>}<br><br>/** <br> * let t = Date.now()<br> * sleep(100).then(() =&gt; console.log(Date.now() - t)) // 100<br> */</pre><p>而下一題，我們會介紹兩個寫法 Promise 和 Promise.race( )<br>先來看看題目！ 這題非常的實用~</p><p><a href="https://leetcode.com/problems/promise-time-limit/description/"><strong>2637. Promise Time Limit</strong></a></p><p>Given an asynchronous function fn and a time t in milliseconds, return a new <strong>time limited</strong> version of the input function. fn takes arguments provided to the <strong>time limited </strong>function.</p><p>給一個非同步函式 fn 和 t 毫秒時間，會回傳一個 input 函式有新的時間限制版本。 fn 會接受限時函式的 arguments 參數。</p><p>The <strong>time limited</strong> function should follow these rules:</p><ul><li>If the fn completes within the time limit of t milliseconds, the <strong>time limited</strong> function should resolve with the result.</li><li>If the execution of the fn exceeds the time limit, the <strong>time limited</strong> function should reject with the string &quot;Time Limit Exceeded&quot;.</li></ul><p>限時函式應有以下規則:</p><p>．如果 fn 在 t 毫秒內完成， 限時函式要 resolve 結果<br>．在處理 fn 時超過了時間限制，限時函式要 reject 並回傳字串&quot;Time Limit Exceeded&quot; 。</p><p><strong>Example 1:</strong></p><pre>Input: <br>fn = async (n) =&gt; { <br>  await new Promise(res =&gt; setTimeout(res, 100)); <br>  return n * n; <br>}<br>inputs = [5]<br>t = 50<br>Output: {&quot;rejected&quot;:&quot;Time Limit Exceeded&quot;,&quot;time&quot;:50}<br>Explanation:<br>const limited = timeLimit(fn, t)<br>const start = performance.now()<br>let result;<br>try {<br>   const res = await limited(...inputs)<br>   result = {&quot;resolved&quot;: res, &quot;time&quot;: Math.floor(performance.now() - start)};<br>} catch (err) {<br>   result = {&quot;rejected&quot;: err, &quot;time&quot;: Math.floor(performance.now() - start)};<br>}<br>console.log(result) // Output</pre><pre>The provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.</pre><p><strong>Example 2:</strong></p><pre>Input: <br>fn = async (n) =&gt; { <br>  await new Promise(res =&gt; setTimeout(res, 100)); <br>  return n * n; <br>}<br>inputs = [5]<br>t = 150<br>Output: {&quot;resolved&quot;:25,&quot;time&quot;:100}<br>Explanation:<br>The function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.</pre><p><strong>Example 3:</strong></p><pre>Input: <br>fn = async (a, b) =&gt; { <br>  await new Promise(res =&gt; setTimeout(res, 120)); <br>  return a + b; <br>}<br>inputs = [5,10]<br>t = 150<br>Output: {&quot;resolved&quot;:15,&quot;time&quot;:120}<br>Explanation:<br>​​​​The function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.</pre><p><strong>Example 4:</strong></p><pre>Input: <br>fn = async () =&gt; { <br>  throw &quot;Error&quot;;<br>}<br>inputs = []<br>t = 1000<br>Output: {&quot;rejected&quot;:&quot;Error&quot;,&quot;time&quot;:0}<br>Explanation:<br>The function immediately throws an error.</pre><p><strong>Constraints:</strong></p><ul><li>0 &lt;= inputs.length &lt;= 10</li><li>0 &lt;= t &lt;= 1000</li><li>fn returns a promise</li></ul><p>起手式:</p><pre>/**<br> * @param {Function} fn<br> * @param {number} t<br> * @return {Function}<br> */<br>var timeLimit = function(fn, t) {<br> return async function(...args) {<br>        <br>    }<br>};<br><br>/**<br> * const limited = timeLimit((t) =&gt; new Promise(res =&gt; setTimeout(res, t)), 100);<br> * limited(150).catch(console.log) // &quot;Time Limit Exceeded&quot; at t=100ms<br> */</pre><p><strong>思路:</strong></p><ol><li>我要去處理 resolve 和 reject 分別的結果，那我會需要 return new Promise，這樣就可以去處理 題目要求的 fn 完成或失敗的結果。</li><li>fn 會接收 arguments 參數， return 一個 Promise， t 毫秒內完成就 resolve(result)，若沒有完成則 reject(“Time Limit Exceeded”)。</li><li>在最後，我們把每一個 setTimeout 清除掉。沒有刪掉也是可以運行，但是用 clearTimeout 可以減少內存溢出 (out of memeory) 的風險。</li></ol><pre>var timeLimit = function(fn, t) {<br> return async function(...args) {<br>        return new Promise((resolve, reject) =&gt; {<br>          const timeoutId = setTimeout(() =&gt; {<br>            reject(&quot;Time Limit Exceeded&quot;)<br>          }, t)<br>          fn(...args)<br>          .then((res) =&gt; resolve(res))<br>          .catch((err) =&gt; reject(err))<br>            // finally() 不管失敗或成功都要執行的函式<br>          .finally(() =&gt; clearTimeout(timeoutId))<br>        })<br>    }<br>};<br><br>/**<br> * const limited = timeLimit((t) =&gt; new Promise(res =&gt; setTimeout(res, t)), 100);<br> * limited(150).catch(console.log) // &quot;Time Limit Exceeded&quot; at t=100ms<br> */</pre><p>若是使用 Promise.race() 就更簡潔了</p><p>Promise.race(iterable) 方法回傳一個 Promise 物件，這個 Promise 物件裡帶進的 iterable 參數(例如 array)，任一個 promise 轉為 resolve 或 rejected 時也會跟著轉變，並接收其成功或失敗的訊息。</p><p><strong>思路:</strong></p><p>要用兩個Promise 函式給 Promise.race，一個是 resolve 成功要執行的，一個是 rejected 失敗要執行的。</p><pre>/**<br> * @param {Function} fn<br> * @param {number} t<br> * @return {Function}<br> */<br>var timeLimit = function(fn, t) {<br> return async function(...args) {<br>       const originalFnPromise = fn(...args)<br>       const rejectedPromise = new Promise((_, reject) =&gt;{<br>          setTimeout(() =&gt; {<br>             reject(&quot;Time Limit Exceeded&quot;)<br>           }, t)    <br>        })<br>       return Promise.race([originalFnPromise, rejectedPromise])<br>    }<br>};<br><br>/**<br> * const limited = timeLimit((t) =&gt; new Promise(res =&gt; setTimeout(res, t)), 100);<br> * limited(150).catch(console.log) // &quot;Time Limit Exceeded&quot; at t=100ms<br> */</pre><h4>補充 Promise.all() 筆記:</h4><p>Promise.all()方法將可迭代的 Promise 作為 input 並返回單個<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>.<br>當所有輸入的 Promise 都實現時（包括傳遞一個空的可迭代對象時），這個返回的 Promise 就會實現，並回傳一個包含這些 fulfillment 被實現的值的陣列。</p><p>若其中有一個 Promise 被 rejected，Promise.all() 回傳的 promise 也是會被 rejected，會回傳失敗的結果值。</p><p>好的~ Promise 系列目前就到這邊啦~ 日後有新增修改再來補上</p><p>若有發現任何錯誤的地方，也請麻煩路過的大大指點 🙏</p><p>想要看中文版 youtuber 的影片文軒解碼有這一系列的影片還不錯~</p><p><a href="https://www.youtube.com/watch?v=CTChl_DYTz0"><strong>【零基础JavaScript教程】#14 JavaScript Promise 是什么？异步(非同步)编程必须掌握的技巧 程序员终于可以逃出回调地狱callback hell了！！</strong></a></p><p><a href="https://www.youtube.com/watch?v=zoZiQJ38bXk&amp;t=627s"><strong>【JavaScript教程】#15 轻松入门 JavaScript Async Await | Async Await 比 Promise 更好用？让你快速掌握 async await 异步执行概念</strong></a></p><p>參考資料:</p><ol><li><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN Promise</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">MDN Async / Await</a></li><li><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">MDN Promise.race( )</a></li><li><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">MDN Promise.all( )</a></li><li><a href="https://leetcode.com/problems/sleep/description/">LeetCode 2621 sleep</a></li><li><a href="https://leetcode.com/problems/promise-time-limit/description/">LeetCode 2637. Promise Time Limit</a></li><li><a href="https://www.youtube.com/watch?v=hfH57rdZhOk&amp;t=528s">Promise Time Limit — Leetcode 2637 — JavaScript 30-Day Challenge</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93950d4f670b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 2621 Sleep]]></title>
            <link>https://medium.com/@cherylrueichun/leetcode-2621-sleep-%E9%87%8D%E6%96%B0%E8%AA%8D%E8%AD%98promise-9960d9c5274b?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9960d9c5274b</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 11:21:23 GMT</pubDate>
            <atom:updated>2023-06-20T16:53:56.902Z</atom:updated>
            <content:encoded><![CDATA[<p>先看看題目，我們來重新認識一下非同步執行的 Promise，最後再來一起解答。</p><p>Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.</p><p>題目會給一個正整數millis，寫一個非同步執行的函式，再睡了millis毫秒以後，就可以 resolve 解決任何的值。</p><p>看到非同步執行和 resolve 不就是 Promise 大大嗎~</p><p><strong>Example 1:</strong></p><pre>Input: millis = 100<br>Output: 100<br>Explanation: It should return a promise that resolves after 100ms.<br>let t = Date.now();<br>sleep(100).then(() =&gt; {<br>  console.log(Date.now() - t); // 100<br>});</pre><p><strong>Example 2:</strong></p><pre>Input: millis = 200<br>Output: 200<br>Explanation: It should return a promise that resolves after 200ms.</pre><p>Examples 也有說這個函式會 return promise 可以在millis毫秒後解決任何值。 想想如何寫~</p><p>我們拉回 Promise 的介紹</p><p><strong>Promise 是一個表示非同步運算，一個即將完成和一個失敗的物件，以及成功或失敗所產生的值。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*uExFMHC3bwabYpSQQyuvsw.jpeg" /><figcaption>image from <a href="https://www.themuse.com/advice/how-to-turn-every-failure-into-a-success">themuse.com</a></figcaption></figure><p>了解 Promise 他其實是根據兩個 callback 回傳的物件，以取代 callback 回傳到這個函數。</p><pre>function doSomething() {<br>  return new Promise((resolve, reject) =&gt; {<br>   // 在這裡執行非同步操作<br>    let condition = true;<br>    if (condition) {<br>      resolve(&quot;Success&quot;);<br>    } else {<br>      reject(&quot;Failure&quot;);<br>    }<br>  });<br>}<br><br>function successCallback(result) {<br>  console.log(&quot;It succeeded with &quot; + result);<br>}<br><br>function failureCallback(error) {<br>  console.log(&quot;It failed with &quot; + error);<br>}<br><br>// 使用 Promise 的方式调用 doSomething<br>let promise = doSomething();<br>promise.then(successCallback, failureCallback);</pre><p>直接使用兩個 callback 函式 到函數裡</p><p>這題有使用到 setTimeout 延遲幾秒後就可以 resolve 任何的值</p><p>說說 setTimeout 函式，它是 web API ，作用就是可以延遲函式的執行。<br>語法為 setTimeout ( fn, delay) <br>那我們加上 setTimeout 來延遲一秒執行函式</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>  // 搭配 condition 來決定是否迎向 success<br>  let condition = true<br>   setTimeout(() =&gt; {<br>   if(condition){<br>     resolve(&quot;Hello&quot;) <br>     } else {<br>     reject(&quot;bye bye&quot;) <br>     }<br>   })<br>})<br><br>// 搭配 .then /.catch 來拿到成功或失敗得到的值<br>promise<br> .then((value)=&gt; {<br>   console.log(&quot;Resolved&quot;, value)<br>  })<br> .catch((error) =&gt; {<br>   console.log(&quot;Rejected&quot;, error)<br>  })</pre><h4>Promise 總共有三種狀態:</h4><ol><li><strong>尚未執行 (Pending) </strong>的狀態: 初始狀態</li><li>表示<strong>操作成功 (Fulfilled)</strong> 的狀態 =&gt; resolve<br>=&gt; 需要使用 .then 去接住成功回傳的值</li><li>表示<strong>操作失敗 (Rejected) </strong>的狀態 =&gt; reject<br>=&gt; 需要使用 .catch 去接住成功回傳的值</li></ol><p>透過使用 .then / .catch 去接住回傳的值的概念，我們還可以使用多個 then 組合形成 Promise 鍊 ( Promise Chaining )。</p><p>一定要 return， 才能讓下一個 then 去接住上面 return 的結果</p><pre>new Promise ((resolve, reject) =&gt; {<br> setTimeout(resolve(1), 1000)<br>}) <br>  <br>.then(function(result){<br>  console.log(&quot;result&quot;,result)<br>  //1<br>  return result*2  <br>  })<br>  // 也可以使用箭頭函式<br>.then((result) =&gt;{<br> console.log(&quot;result2&quot;,result)<br>  //2<br> return result*2<br>})<br> // 在這個 .then 丟出一個 error <br>.then((result) =&gt;{<br> console.log(&quot;result3&quot;,result)<br> // 4，但下一行 throw new error 會變成 rejected<br> throw new Error(&quot;No result&quot;)<br> return result*2<br>})<br> // 被略過<br>.then((result) =&gt;{<br> console.log(&quot;result4&quot;,result)<br> return result*3<br>})<br> // 遇到 catch 接住 error<br>.catch((error) =&gt;{<br> console.log(&quot;error&quot;,error)<br>// return new Promise resolve 新的值，沒此行後面 result 就是 undefined<br> return Promise.resolve(100);<br>})<br> // 可以接上面的回傳值 100<br>.then((result) =&gt;{<br> console.log(&quot;result6&quot;,result)<br> return result<br>})</pre><h4><strong>同步認識 Promise.all 和 Promise.race</strong></h4><p><strong>Promise.all</strong> 方法接收可迭代的多個 promise 為參數，回傳一個 Promise。<br>若參數內的所有 promise們 都完成 fulfills 狀態，單個 Promise 就也可以成功取得 fulfills 狀態。若任何一個參數 promise 被 rejected，單個 Promise 也會被 rejcted</p><pre>const a = Promise.resolve(1)<br>const b = 500<br>const c = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>     resolve(&quot;Aloha&quot;)<br>  }, 1000)<br>}) <br><br>Promise.all([a, b, c]).then((values) =&gt; {<br>   console.log(values)<br>})<br><br>// 一秒後回傳 [1, 500, &#39;Aloha&#39;]</pre><p><strong>Promise.race </strong>方法接收可迭代的多個 promise 為參數，回傳一個 Promise。<br>會 fulfill 去執行 第一個 fulfilled 的 promise，若第一個處理完的 promise 結果為 reject，那單個 promise 回傳的結果也是 rejected。</p><p>如果接收可迭代的參數是空的，則 Promise 狀態會一值呈現在 pending 的狀態。<br>如果可迭代參數不是空的，但沒有待處理的 promise，被回傳的這個 Promise 還是會被非同步執行處理完。</p><pre>const promise1 = new Promise((resolve, reject) =&gt; {<br>   setTimeout(() =&gt; {<br>     resolve(1)<br>  }, 500)<br>})<br><br>const promise2 = new Promise((resolve, reject) =&gt; {<br>   setTimeout(() =&gt; {<br>     resolve(2)<br>  }, 100)<br>})<br><br>Promise.race([promise1, promise2]).then((value) =&gt; {<br>  console.log(value)<br>})<br><br>// promise1, promise2 都 resolved 但是 promise2 比較快，所以回傳 2</pre><p>最後再回來看題目要怎麼解 :</p><ol><li>回傳 new Promise</li><li>使用 reolve 代表若狀態 fulfilled，則會執行一個 setTimeout 函式，延遲時間為參數 millis</li><li>setTimeout 函式裡會執行的是 resolve( )，可以 resolve 任意值</li></ol><pre>function sleep(millis) {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve()<br>        },millis)<br>    })<br>}</pre><p>額外小補充: setTimeout() 的回傳值是一個 timeoutID，當我們要使用 clearTimeout() 的函式參數是要放設置 setTimeout() 的 timeoutID 才可以取消這個 setTimeout 。</p><p>參考資料: Leetcode 2621 Sleep 和 MDN<br>Murmur: 今天作筆記到一半，發現 Leetcode JS 30 挑戰的 editorial 都被鎖了 😢</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9960d9c5274b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 2648. Generate Fibonacci Sequence Generator Function]]></title>
            <link>https://medium.com/@cherylrueichun/2648-generate-fibonacci-sequence-generator-function-3a0d0c773364?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0d0c773364</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 10:31:53 GMT</pubDate>
            <atom:updated>2023-06-09T04:19:05.564Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>解這題以前，若是像我一樣不了解 “yield” Generator Functions 的用法，需要先一起認識一下來解這題。</strong></p><p>JavaScript 裡的 Generator functions 是比較特別的函式，它可以暫停在繼續，在不同次的呼叫使它們 yield 出產生多個不同的 outputs。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSHpMa7RLL188J4cmYhYEA.jpeg" /></figure><p>Generator functions 使用function*關鍵字來定義，呼叫時回傳 generator object</p><p>當 generator function 被呼叫時，它會回傳一個 generator object。<br>這個物件是一個迭代器，它有這個 next()的方法可以被呼叫從generator 來產生一個值。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*VQ9Z_6RW9ZDIgono2Meq2Q.png" /></figure><p>next() 的語法如下:</p><ul><li>每一次呼叫會回傳一個物件包含兩個屬性: value and done.</li><li>此 value屬性是此排序中現在項目的 value 數值</li><li>done 屬性是一個布林值，如果執行了排序中的最後一個項目的value ， done屬性回傳 true，否則回傳 false</li></ul><p>yield 有類似於一般 function “return” 的效果，都是回傳值，但是執行yield 不代表函式結束，Generator 函式裡有多少個 yield 就代表我們賦予給它幾個值，但函式被呼叫時，就會出現 yield “value” 值。</p><h4>Generator Function 的三種方法: next, return, throw</h4><pre>function* simpleGenerator(){<br>  yield 1<br>  yield 2<br>  yield 3<br>  // return 4<br>}<br><br>const generatorObject = simpleGenerator()<br>console.log(generatorObject.next()) //{value:1, done: false}<br>console.log(generatorObject.next()) //{value:2, done: false}<br>console.log(generatorObject.return(10))   //{value:10, done: true}<br>console.log(generatorObject.next())  //{value:undefined, done: true}<br>console.log(generatorObject.throw(new Error(&quot;finished&quot;))) //Error: finihed</pre><h4>使用範例 Use Cases: 無限迴圈 Infiniite loop</h4><pre>function* gereratedId(){<br> let id = 1<br> <br> while(true) {<br> const increment = yield id<br> if (increment != null){<br>    id += increment<br>   } else {<br>     id++<br>   }<br>  }<br>}<br><br>const generatorObject = generateId()<br>console.log(generatorObject.next()) //{value:1, done: false}<br>console.log(generatorObject.next()) //{value:2, done: false}<br>console.log(generatorObject.next(4)) <br>//{value:6, done: false} 傳進去 increment 非null值<br>console.log(generatorObject.next()) <br>//{value:7, done: false}</pre><p>前面介紹了Generator Function<br><strong>這題當然就是要用 Generator Function 來 Generate Fibonacci Sequence</strong></p><p>題目說明: <br>Write a generator function that returns a generator object which yields the <strong>fibonacci sequence</strong>.</p><p>The <strong>fibonacci sequence</strong> is defined by the relation Xn = Xn-1 + Xn-2.</p><p>The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.</p><p><strong>Example 1:</strong></p><pre>Input: callCount = 5<br>Output: [0,1,1,2,3]<br>Explanation:<br>const gen = fibGenerator();<br>gen.next().value; // 0<br>gen.next().value; // 1<br>gen.next().value; // 1<br>gen.next().value; // 2<br>gen.next().value; // 3</pre><p><strong>Example 2:</strong></p><pre>Input: callCount = 0<br>Output: []<br>Explanation: gen.next() is never called so nothing is outputted</pre><p>題目給的初始程式:</p><pre>var fibGenerator = function*() {<br>    <br>};<br><br>/**<br> * const gen = fibGenerator();<br> * gen.next().value; // 0<br> * gen.next().value; // 1<br> */</pre><p><strong>解題思路1:</strong><br>0 1 1 2 3 5 8 13 21 34 55…<br>除了 base case 前面兩個數字 0 1, 其他都是取前面兩個數字相加而來的<br>我們要利用 yield 來回傳值 + while loop</p><pre><br>var fibGenerator = function*() {<br>    let preNum1 = 0;<br>    let preNum2 = 1;<br>    // create infinite loop<br>    while(true) {<br>     yield preNum1;<br>     let num = preNum1 + preNum2;<br>     preNum1 = preNum2;<br>     preNum2 = num;<br>   }<br>};<br><br><br>// 也可以使用解構賦值 + while loop<br>var fibGenerator = function*() {<br>    let preNum1 = 0;<br>    let preNum2 = 1;<br>    // create infinite loop<br>    while(true) {<br>     yield preNum1;<br>     [preNum1, preNum2] = [preNum2, preNum1+preNum2]<br>   }<br>};<br><br><br><br><br>/**<br> * const gen = fibGenerator();<br> * gen.next().value; // 0<br> * gen.next().value; // 1<br> */<br></pre><p><strong>解題思路2: 利用遞迴的Generator Function 來產生 Fibonacci Sequencee</strong></p><pre>var fibGenerator = function*(a=0, b=1) {<br>    yield a<br>    yield* fibGenerator(b, a+b)<br>};<br><br>/**<br> * const gen = fibGenerator();<br> * gen.next().value; // 0<br> * gen.next().value; // 1<br> */</pre><p>yield* 用來表示不只是yield 的回傳值，會yield 另一個 generator，然後就會產生遞迴效果，因此這裡可以無限產生 Fibonacci sequence</p><h4><strong>參考資料:</strong></h4><p><a href="https://leetcode.com/problems/generate-fibonacci-sequence/">LeetCode 30days Challenge 2648. Generate Fibonacci Sequence</a></p><p><a href="https://www.youtube.com/watch?v=IJ6EgdiI_wU">Learn JavaScript Generators In 12 Minutes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0d0c773364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 2631. Group By 解題]]></title>
            <link>https://medium.com/@cherylrueichun/leetcode-2631-group-by-%E8%A7%A3%E9%A1%8C-68b0527c776b?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/68b0527c776b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sun, 28 May 2023 08:18:59 GMT</pubDate>
            <atom:updated>2023-06-09T06:32:32.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XrBP8E9qXNVFZc7r" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>JS 30 天挑戰Leetcode 2631. Group By 題目:</h4><p>Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a <strong>grouped</strong> version of the array.</p><p>需要寫一段程式可以使用任何的 array 呼叫 array.groupBy(fn) 方法, 並且回傳分組後的陣列版本</p><p>A <strong>grouped</strong> array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array with that key.</p><p>每一組被分類的陣列是被 一個外層的 object 包住， key 值是 fn(arr[i]) 的 output，然後其對應的 value 值是一個陣列包含在原始陣列裡有著相同 key 的項目 (Item =&gt; value)</p><p>The provided callback fn will accept an item in the array and return a string key.</p><p>提供的 callback fn 會接受陣列的 item，並回傳一個字串 key。</p><p>The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.</p><p>Please solve it without lodash’s _.groupBy function.</p><p>每個值的順序應需要按照原始陣列裡的項目順序排列，keys 的順序不同是可接受的。<br>請不要使用 lodash’s _.groupBy function 解題。</p><p>題目看不是很懂? 直接看 Example</p><p><strong>Example 1:</strong></p><pre>Input: <br>array = [<br>  {&quot;id&quot;:&quot;1&quot;},<br>  {&quot;id&quot;:&quot;1&quot;},<br>  {&quot;id&quot;:&quot;2&quot;}<br>], <br>fn = function (item) { <br>  return item.id; <br>}<br>Output: <br>{ <br>  &quot;1&quot;: [{&quot;id&quot;: &quot;1&quot;}, {&quot;id&quot;: &quot;1&quot;}],   <br>  &quot;2&quot;: [{&quot;id&quot;: &quot;2&quot;}] <br>}<br>Explanation:<br>Output is from array.groupBy(fn).<br>The selector function gets the &quot;id&quot; out of each item in the array.<br>There are two objects with an &quot;id&quot; of 1. <br>Both of those objects are put in the first array.<br>There is one object with an &quot;id&quot; of 2. <br>That object is put in the second array.</pre><p><strong>Example 2:</strong></p><pre>Input: <br>array = [<br>  [1, 2, 3],<br>  [1, 3, 5],<br>  [1, 5, 9]<br>]<br>fn = function (list) { <br>  return String(list[0]); <br>}<br>Output: <br>{ <br>  &quot;1&quot;: [[1, 2, 3], [1, 3, 5], [1, 5, 9]] <br>}<br>Explanation:<br>The array can be of any type. <br>In this case, the selector function defines the key <br>as being the first element in the array. <br>All the arrays have 1 as their first element so they are grouped together.<br>{<br>  &quot;1&quot;: [[1, 2, 3], [1, 3, 5], [1, 5, 9]]<br>}</pre><p><strong>Example 3:</strong></p><pre>Input: <br>array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>fn = function (n) { <br>  return String(n &gt; 5);<br>}<br>Output:<br>{<br>  &quot;true&quot;: [6, 7, 8, 9, 10],<br>  &quot;false&quot;: [1, 2, 3, 4, 5]<br>}<br>Explanation:<br>The selector function splits the array by whether each number is greater than 5.</pre><p><strong>Constraints:</strong></p><ul><li>0 &lt;= array.length &lt;= 105</li><li>fn returns a string</li></ul><p>將上面的 Example 整理成以下表格</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*uPXrXJwsptsy1z_T3d2BJQ.jpeg" /></figure><p>思路:</p><ol><li>要把回傳值當作 key 存進去 空物件 { } ，他的原始陣列的項目 item 為其 value。</li><li>使用 for of loop 存進去 key value pair</li><li>若有相同的 key，則不用重複存進去，直接將其分類把對應的 item 值存進所屬 key 值的 value 值</li><li>題目的開頭如下，是將Array 的 prototype 加入此 groupBy方法，每個Array 都能有此方法。</li></ol><pre>Array.prototype.groupBy = function(fn) {<br>    const collection = {}<br>    for(const item of this) {<br>        const key = fn(item)<br>        if (collection.hasOwnProperty(key)){<br>            // [{&quot;id&quot;: &quot;1&quot;}]<br>            collection[key].push(item)<br>        } else {<br>        collection[key] = [item]<br>        }<br>    }<br>    return collection<br>};</pre><p>寫this 的地方不能直接寫 Array的原因是什麼?</p><p>這是我犯的錯誤，一開始在this 的地方寫 關鍵字Array</p><pre>Array.prototype.groupBy = function(fn) {<br>    const collection = {}<br>// 以下 應該寫成 for(const item of this)<br>    for(const item of Array) {<br>        const key = fn(item)<br>        if (collection.hasOwnProperty(key)){<br>            // [{&quot;id&quot;: &quot;1&quot;}]<br>            collection[key].push(item)<br>        } else {<br>        collection[key] = [item]<br>        }<br>    }<br>    return collection<br>};</pre><p>因為Array 是一個構造函數(constructor)，用於建構新的陣列<br>當我使用到 Array 關鍵字時，實際上是引用到 Array 構造函數本身，而不是一個特定的陣列對象。<br>所以要使用 this 關鍵字 ，引用調用 groupBy 方法對象的特定陣列。</p><p>const myArray = new Array()</p><p>這邊也是使用 new 关键字来調用 Array 構造函数</p><h4>Approach 2: 使用 reduce 方法</h4><p><strong>認識 ||= 賦值運算符，如果對象是假值才賦值空陣列[]，不然不會有變化</strong></p><pre>Array.prototype.groupBy = function(fn) {<br> return this.reduce((accum, item) =&gt; {<br>     const key = fn(item)<br>     //如果 accum[key]為 falsy值 = []<br>     accum[key] ||= []<br>     accum[key].push(item)<br>     return accum<br> }, {})<br>};</pre><h3>Logical OR assignment (||=)</h3><p>The logical OR assignment (x ||= y) operator only assigns if x is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a>.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment">Logical OR assignment (||=) - JavaScript | MDN</a></p><p><strong>groupBy方法在現實生活中非常有用<br>我們可以使用 groupBy 方法來分類資料，整理記錄做簡單的分析<br>也可以用 groupBy 將得到的錯誤做分類，看哪種錯誤最常發生。</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68b0527c776b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 2627. Debounce : 前端優化必備知識Debounce防抖]]></title>
            <link>https://medium.com/@cherylrueichun/leetcode-2627-debounce-%E5%89%8D%E7%AB%AF%E5%84%AA%E5%8C%96%E5%BF%85%E5%82%99%E7%9F%A5%E8%AD%98debounce%E9%98%B2%E6%8A%96-7371ef984589?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7371ef984589</guid>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Fri, 19 May 2023 15:50:30 GMT</pubDate>
            <atom:updated>2023-06-08T00:38:51.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 2627. Debounce : 前端優化必備知識Debounce防抖</h3><p>今天的 Leetcode 不只很有趣，對前端優化也很重要的啊~<br>解完今天這題學到了debounce ，覺得實在太實用了 😍</p><h3>Debounce 手寫防抖:</h3><p><a href="https://www.techtarget.com/whatis/definition/debouncing">TechTarget </a>給的英文定義<br>Debouncing is removing unwanted input noise from buttons, switches or other user input</p><p>Input 是最常聽到的範例，在搜尋框寫 input onChange 事件處理器，我們每打一個字就會送請求給伺服器端，可能打了十個字才是我們想送出的內容，但是前面九個字都有分別送出請求給 Server，送一次和送十次請求這個效能一定就有差。</p><p>如果用中文來記的話，防抖也可以想成防止手抖線上購物按了兩次付款會被收費兩次，也是可以透過 debounce 來設置。</p><p>要寫 debounce 函式，他會接收兩個參數</p><ol><li>要執行的函式</li><li>延遲的時間 (ms)</li></ol><p>以 Input 來舉例的話，參照影片與一般Input 比對(default) 思路:</p><p>(1) 可以設置 Input 打字的時候，若使用者還在輸入，嘗試呼叫同個 function 去作用，我們可以把它先忽略，或是解除這個呼叫。<br>(2) 呈上，可在第一次呼叫 fn 時，就設置 setTimeout，如果特定的時間內沒有呼叫的話，我們就可以確認使用者可能已完成輸入，送出請求。<br>(3) 若在這個時間內呼叫同個 fn，那就可以在前一次的請求送出前把它刪除。</p><p>如下，我們先設置 setTimeout 回傳的 timeoutId 先宣告此變數 timeout<br>一開始雖然沒有被賦值，使用 clearTimeout(undefined) 也不會被影響，所以其實也可以不用加 if (timeout)</p><p>只要一呼叫這個 fn，就先 clearTimout 之前的操作，在設置新的操作</p><pre>const input = document.querySelector(&quot;input&quot;);<br>const defaultText = document.getElementById(&quot;default&quot;);<br>const debounceText = document.getElementById(&quot;debounce&quot;);<br><br>const updateDebounceText = debounce((text) =&gt; {<br>  debounceText.textContent = text;<br>}, 1000);<br><br>input.addEventListener(&quot;input&quot;, (e) =&gt; {<br>  defaultText.textContent = e.target.value;<br>  updateDebounceText(e.target.value);<br>});<br><br>// function debounce 接收兩個參數:callback fn 和 delay 時間<br>function debounce(fn, delay = 1000) {<br>  let timeout;<br>  return (...args) =&gt; {<br>    if (timeout) clearTimeout(timeout);<br>    timeout = setTimeout(() =&gt; fn(...args), delay);<br>  };<br>}</pre><p>完整codepen 操作程式碼可以點<a href="https://codepen.io/cherylruei/pen/jOeQqBy?editors=1011">這裡</a></p><p>了解以後，接下來我們來看這次的<a href="https://leetcode.com/problems/debounce/description/">Leetcode題目</a>，完全是相同的概念，可以直接解題下去!</p><p>Given a function fn and a time in milliseconds t, return a <strong>debounced</strong> version of that function.</p><p>給定我們函式 fn 和時間的設置 t , 回傳同個函式的 debounce 版本。</p><p>A <strong>debounced</strong> function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also recieve the passed parameters.</p><p>debounce 防抖函式是一個可以延遲時間 t (ms) 來執行的，且如果在此時間內又被呼叫一次函式，原本的函式執行動作就會被取消。 debounce 防抖函式應該會接受被傳進來的參數。</p><p>For example, let’s say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms.</p><p>例如: 我們在設置 t = 50ms 時，函式分別在 30ms, 60ms 和 100ms 被呼叫，前兩次函式呼叫都會被取消，然後第三個函式會在 150ms 被執行。<br>如果 設置 t = 35ms 時，在30ms呼叫的函式會被取消，第二個函式會在 95ms (35+ 60) 被執行，第三個函式會在 (35+100) 135ms 時被執行</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wnVQDwHsS5ogorbm.png" /><figcaption>題目提供的圖片參考概念</figcaption></figure><p>The above diagram shows how debounce will transform events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs.</p><p>Please solve it without using lodash’s _.debounce() function.</p><p>以上圖表是告訴我們 debounce 防抖是怎麼轉化這些事件。<br>每一個長方形代表 100ms，而它抖動的時間為 400ms。每個顏色代表每一組的 inputs</p><p>不太懂的話，我們就來看Example 再來畫圖~</p><p><strong>Example 1:</strong></p><pre>Input: <br>t = 50<br>calls = [<br>  {&quot;t&quot;: 50, inputs: [1]},<br>  {&quot;t&quot;: 75, inputs: [2]}<br>]<br>Output: [{&quot;t&quot;: 125, inputs: [2]}]<br>Explanation:<br>let start = Date.now();<br>function log(...inputs) { <br>  console.log([Date.now() - start, inputs ])<br>}<br>const dlog = debounce(log, 50);<br>setTimeout(() =&gt; dlog(1), 50);<br>setTimeout(() =&gt; dlog(2), 75);</pre><pre>The 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms<br>The 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2).</pre><p>從這邊可以看到，第一次呼叫預計要在 50 + 50 ms 以後執行的函式，因為 75ms 出現了第二次呼叫，就取消了原本第一次呼叫要執行的函式。<br>因為後面並沒有再呼叫函式，這次呼叫有在 50+75ms 順利執行，並出來 inputs [2]。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*J4v6JsA2B5Asa_nUduglyg.png" /></figure><p><strong>Example 2:</strong></p><pre>Input: <br>t = 20<br>calls = [<br>  {&quot;t&quot;: 50, inputs: [1]},<br>  {&quot;t&quot;: 100, inputs: [2]}<br>]<br>Output: [{&quot;t&quot;: 70, inputs: [1]}, {&quot;t&quot;: 120, inputs: [2]}]<br>Explanation:<br>The 1st call is delayed until 70ms. The inputs were (1).<br>The 2nd call is delayed until 120ms. The inputs were (2).</pre><p>而這個範例的兩次呼叫，因為沒有在時間範圍內重疊出現，所以都有成功被執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*EJX2rjrv860Q6l5N9SRQlQ.png" /></figure><p><strong>Example 3:</strong></p><pre>Input: <br>t = 150<br>calls = [<br>  {&quot;t&quot;: 50, inputs: [1, 2]},<br>  {&quot;t&quot;: 300, inputs: [3, 4]},<br>  {&quot;t&quot;: 300, inputs: [5, 6]}<br>]<br>Output: [{&quot;t&quot;: 200, inputs: [1,2]}, {&quot;t&quot;: 450, inputs: [5, 6]}]<br>Explanation:<br>The 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2).<br>The 2nd call is cancelled by the 3rd call<br>The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6).</pre><p>因為範例3 呼叫順序是 藍色 → 橙色 → 綠色<br>第一次呼叫的函式要延遲50ms 加上固定延遲的 150ms，在 200ms 被執行<br>第二次呼叫的函式要延遲 300ms 加上固定延遲的150ms，還正要計算第三次呼叫函式就立刻接著來了，直接取消第二次的呼叫。<br>第三次呼叫的函式也是延遲 300ms 加上固定延遲的150ms，在450ms 被執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*yU7rmfjpK2PgMyWU2hPSSQ.png" /></figure><p>解法按照之前的思路<br>宣告 debounce 變數是一個函式，接收執行的函式 fn 和延遲的時間 t<br>用 let 宣告 id 變數 來做為管理 setTimeout 的變數<br>在debonce函式裡，回傳要執行的函式，如果前一次setTimeout的 id 存在，要將它清除。<br>並設置新的 setTimeout，賦值新的 id <br>設置的setTimeout 如果在設定的時間內都不會被刪除的話，就會執行該函式。</p><pre>var debounce = function(fn, t) {<br>  let id <br>    return function(...args) {<br>        if (id) clearTimeout(id)<br>        id = setTimeout(() =&gt; fn(...args), t)<br>    }<br>};</pre><p>補充: 這裡儲存的 id 變數就是用到閉包的概念可以被存取值來操作哦!</p><p>此Leetcode 題放在 <a href="https://replit.com/@cherylrueichun/CloudyLightgrayCoderesource#index.js">replit 連結</a>，可以自己帶不同的參數來玩看看</p><h3>學習參考資料 :</h3><p><a href="https://www.youtube.com/watch?v=cjIswDCKgu0">https://www.youtube.com/watch?v=cjIswDCKgu0</a><br>Learn Debounce And Throttle In 16 Minutes</p><p><a href="https://www.youtube.com/watch?v=yBFHwJgqLD4">https://www.youtube.com/watch?v=yBFHwJgqLD4</a><br>Javascript Debounce Tutorial | JS Debouncing Functions Explained with Examples</p><p><a href="https://www.explainthis.io/zh-hant/interview-guides/javascript-whiteboard/debounce">https://www.explainthis.io/zh-hant/interview-guides/javascript-whiteboard/debounce</a><br>Explain this 筆記: 介紹 Debounce &amp; Throttle</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7371ef984589" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 2623. Memoize 筆記 -Cache]]></title>
            <link>https://medium.com/@cherylrueichun/leecode-js-30-%E6%8C%91%E6%88%B0-2623-memoize-%E7%AD%86%E8%A8%98-b140529d92b1?source=rss-2257fbe733e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b140529d92b1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Cheryl Li]]></dc:creator>
            <pubDate>Sun, 14 May 2023 03:01:23 GMT</pubDate>
            <atom:updated>2023-05-21T14:41:51.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>這題的難度等級為 medium，題目內容為 <a href="https://leetcode.com/problems/memoize/">Memoize</a>:</h4><p>Given a function fn, return a <strong>memoized</strong> version of that function.</p><p>A <strong>memoized </strong>function is a function that will never be called twice with the same inputs. Instead it will return a cached value.</p><p>給定一個函數 fn，會回傳記憶化版本的函式。這個memoized 函式是一個不會被相同的 inputs 呼叫兩次。取代的是，它會直接回傳緩存值。</p><p><strong>=&gt; 這裡也就是說，我們要去針對每一筆 inputs 去記錄它的緩存值，在決定是否要呼叫 fn 之前，要先確認這個 inputs 有沒有被呼叫過。</strong></p><p>You can assume there are <strong>3 </strong>possible input functions: sum<strong>, </strong>fib<strong>, </strong>and factorial<strong>.</strong></p><ul><li>sum<strong> </strong>accepts two integers a and b and returns a + b.</li><li>fib<strong> </strong>accepts a single integer n and returns 1 if n &lt;= 1 or fib(n - 1) + fib(n - 2) otherwise.</li><li>factorial accepts a single integer n and returns 1 if n &lt;= 1 or factorial(n - 1) * n otherwise.</li></ul><p>這裡它給了三個可能會被當參數放進的函式給我們參考，分別是 sum, fib 和 factorial，如果不是很理解，我們可以繼續往下看他給的 example ⬇</p><p>️<strong>Example 1:</strong></p><pre>Input<br>&quot;sum&quot;<br>[&quot;call&quot;,&quot;call&quot;,&quot;getCallCount&quot;,&quot;call&quot;,&quot;getCallCount&quot;]<br>[[2,2],[2,2],[],[1,2],[]]<br>Output<br>[4,4,1,3,2]</pre><pre>Explanation<br>const sum = (a, b) =&gt; a + b;<br>const memoizedSum = memoize(sum);<br>memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.<br>memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.<br>// Total call count: 1<br>memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.<br>// Total call count: 2</pre><p>總共有三個 example，但老實說我寫完以後才真正搞懂題目的設置。<br>所以先說明一下，仔細看它的解釋來理解它的 inputs，我把它列出來應該長的樣子是:</p><pre>const sum = (a, b) =&gt; a + b;<br>const memoizedSum = memoize(sum);<br>console.log([<br>memoizedSum(2, 2),<br>memoizedSum(2, 2),<br>memoizedSum.getCallCount(),<br>memoizedSum(2, 2),<br>memoizedSum.getCallCount(),<br>])</pre><p>call 就是帶進參數去使用 memoizedSum 呼叫，getCallCount() 是它題目底層本身設置還有一個函式，呼叫它可以幫你計算這個函式目前已經被呼叫了幾次。</p><p>我一開始還傻傻地想要讓他遇到空陣列可以呼叫 自己寫的 getCallCount 函式去計算呼叫次數😂</p><p>過程中我有把function名稱拼錯，就出現題目底層設置說這個變數沒有被 defined。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Of9QyTvVLZAMjE-xTZoFMQ.png" /></figure><p>下面兩個 example 一個是階乘，另一個是斐波那契數列，不懂他們其實沒關係，能按照此規律執行就可以完成題目，有興趣再去了解這兩個演算法，寫題也會很有幫助。</p><p><strong>Example 2:</strong></p><pre>Input<br>&quot;factorial&quot;<br>[&quot;call&quot;,&quot;call&quot;,&quot;call&quot;,&quot;getCallCount&quot;,&quot;call&quot;,&quot;getCallCount&quot;]<br>[[2],[3],[2],[],[3],[]]<br>Output<br>[2,6,2,2,6,2]</pre><pre>Explanation<br>const factorial = (n) =&gt; (n &lt;= 1) ? 1 : (n * factorial(n - 1));<br>const memoFactorial = memoize(factorial);<br>memoFactorial(2); // Returns 2.<br>memoFactorial(3); // Returns 6.<br>memoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before.<br>// Total call count: 2<br>memoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before.<br>// Total call count: 2</pre><p><strong>Example 3:</strong></p><pre>Input<br>&quot;fib&quot;<br>[&quot;call&quot;,&quot;getCallCount&quot;]<br>[[5],[]]<br>Output<br>[8,1]</pre><pre>Explanation<br>fib(5) = 8<br>// Total call count: 1</pre><p>開始解題前，先了解一下 memoization 記憶化的用法，其實就是先記憶住函式有執行過的結果，存在緩存資料裡。</p><p><strong>Memoization 是優化的工具，讓程式碼跑得更快、更有效率。</strong></p><p>若遇到相同的 inputs，不需要在函式操作，就可以直接從緩存資料裡按照 key值取出對應的值。</p><p>所以一定要是 Pure function，必須保持 same input, same output ，這個記憶化執行的才有意義。</p><p><strong>Javascript 裡的 Memoization主要根據兩大觀念: 閉包、高階函數</strong></p><p>閉包 (Closures) 函式和 宣告該函式的詞彙環境或說作用域 (Lexcial environment) 的組合，<br>高階函數 (Hign order functions) 這邊提到的主要功能是 function 可以將其 function 當成引數傳入並執行</p><h4>解題的思路:</h4><p>1. 要一個 memoize 的函式，能接受 fn 函式為參數，回傳 function<br>2. 要設一個儲存 cache 的 object ，才能儲存 key (input) 和 value (output)<br>3. 判斷如果此inputs 沒有被使用過，則要呼叫函式，並將 key 值存入 cache object，回傳 fn output<br>4. 判斷如果此inputs 已經被使用來呼叫函式，將key值從 cache物件取出，直接回傳其 value 值</p><p>注意: key 值 只能是字串(string) 形式</p><pre>function memoize(fn){<br>   //宣告 cache 為空物件<br>   const cache = {}<br>   return function(...args) {<br>    // 將 不確定型別的args 使用JSON.stringify() 形式轉成字串<br>    let key = JSON.stringify(args)<br>    // 若 key 有在 cache 裡,直接回傳其 value值 <br>    if (key in cache) {<br>      return cache[key]<br>    }<br>    // 若key不存在，呼叫fn 接住回傳值以後存進 cache<br>    let fnOutput = fn(...args)<br>    cache[key] = fnOutput<br>    return fnOutput<br>  }<br>}</pre><p>其中複習的用法 :<br>1. JSON.stringify() 將字轉成字串當作key，因為key必須要是字串</p><p>2. 使用 in Operator 去確認 key 值是否有存在 obj</p><pre>let user = {<br>   name: &quot;John&quot;,<br>   gender: &quot;male&quot;,<br>   email: &quot;John@example.com&quot;<br>}</pre><pre>console.log(&#39;name&#39; in user) // true</pre><p>另外分享如何在減少記憶體，上面的解題是我一開始寫出來的用法</p><p>相同的思路按我剛剛寫的順序，先判斷 這個 cache[key] 存不存在，若是它等於 undefined，則直接呼叫 fn(…args)，並用 cache[key] 直接接住回傳值。</p><p>如果cache[key]不是 undefined，就可以直接回傳 cache[key]的 value值，節省了變數佔記憶體空間</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZECZOqzljkEs1XcdNkFMg.png" /></figure><p>最後要來介紹一下斐波那契數列 讓我更有感的了解為什麼使用 memoization 可以加速fn 運行空間。</p><p>首先，來看看它是什麼?</p><p>0 1 1 2 3 5 8 13 21 34 55 89 144 233</p><p>上面看出它的規律了嗎?</p><p>斐波那契數列是由義大利數學家里奧納多・斐波那契（Leonardo Fibonacci） 發現，從1開始，連續兩個數字加起來等於第三個數字的數列</p><p>若我們要把它寫成函式去計算，傳入參數n，去算斐波那契數列的第幾個數字是多少</p><pre>function fibonacci(n){<br> if (n &lt; 2) {<br>  return 1<br>  }<br>  return fibonacci(n-2) + fibonacci(n-1)<br>}<br><br>console.log(fibonacci(40))<br>console.log(fibonacci(40))</pre><p>在寫一個 memoization 的版本，加入一個參數 preValue 去存之前的運算結果，設 preValue 初始值為空陣列</p><pre>function fibonacci(n, preValue=[]){<br> if (preValue[n] != undefined) {<br>   return preValue[n]<br>  }<br> //宣告result<br> let result<br> if (n &lt; 2) {<br>  result = 1<br>  }<br>  result = fibonacci(n-2, preValue) + fibonacci(n-1, , preValue)<br>  //算出result 以後,存進preValue<br>  preValue[n] = result<br>  return result<br>}<br><br>console.log(fibonacci(40))<br>console.log(fibonacci(40))</pre><p>同樣兩個程式碼貼到dev tool 去運行看看速度，電腦跑太快的話，n 可以放到 60, 80, 100 試試，只是小心當機😂</p><p>如果看得頭昏的，可以把程式碼貼到以下連結去看程式碼運行步驟，就會很清楚程式碼是怎麼拿到預先計算好的值來加快計算的速度了~</p><p><a href="https://pythontutor.com/visualize.html#mode=display">https://pythontutor.com/visualize.html#mode=display</a></p><p>參考資源:</p><p><a href="https://leetcode.com/problems/memoize">https://leetcode.com/problems/memoize</a><br><a href="https://www.youtube.com/watch?v=TWUV_LRVX24&amp;t=937s">https://www.youtube.com/watch?v=TWUV_LRVX24&amp;t=937s</a><br><a href="https://www.youtube.com/watch?v=WbwP4w6TpCk">https://www.youtube.com/watch?v=WbwP4w6TpCk</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b140529d92b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>