<?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 Jean Pan on Medium]]></title>
        <description><![CDATA[Stories by Jean Pan on Medium]]></description>
        <link>https://medium.com/@jeanpan?source=rss-e9f40ce5bf3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G1o42EqZohP9PB_hGocpXw.jpeg</url>
            <title>Stories by Jean Pan on Medium</title>
            <link>https://medium.com/@jeanpan?source=rss-e9f40ce5bf3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeanpan/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[看懂損益表]]></title>
            <link>https://medium.com/%E8%8F%9C%E9%9B%9E%E4%BA%BA%E7%94%9F/%E7%9C%8B%E6%87%82%E6%90%8D%E7%9B%8A%E8%A1%A8-d138773b21b2?source=rss-e9f40ce5bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d138773b21b2</guid>
            <category><![CDATA[損益表]]></category>
            <dc:creator><![CDATA[Jean Pan]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 09:45:46 GMT</pubDate>
            <atom:updated>2020-07-04T13:27:06.055Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>非專業分享，記錄一下我是怎麼查看和理解損益表的!</blockquote><p>要知道一間公司到底有沒有在賺錢就是要看損益表 (Income Statement)</p><p>我主要是用 <a href="https://finance.yahoo.com/">Yahoo! Finance</a>, 如果想看中文可以到 <a href="https://hk.finance.yahoo.com/">Yahoo! HK Finance</a>。那就拿麥當勞 McDonald’s Corporation (MCD) 為例吧!</p><ol><li>在 Yahoo! HK Finance 中搜尋股票代號或公司名稱</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIkxT3BJpzzzsb0gXzwWmg.png" /></figure><p>2. 點選到 <strong>金融</strong> (financials)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpOfHpc14fSAVZtXPVYINg.png" /></figure><p>3. 點選 顯示: 損益表 (Income Statement)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utUcagFKqGG-9jiIbtE6Cw.png" /></figure><p>那接下來就從一列一列的細節來了解</p><p>先看過去十二個月 (TTM) 那欄就好</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*BQnYn_G_wHwHMjTu3IeS-g.png" /></figure><ul><li><strong>總收益</strong> (Total Revenue)<br>公司總收入, 也就是我們常說的 營收</li><li><strong>收益成本</strong> (Cost of Revenue)<br>收益的成本, 像是材料、食材成本</li><li><strong>毛利</strong> (Gross Profit)<br>總收益減去收益成本</li><li><strong>營運成本</strong> (Operating Expenses) 像是支付員工的薪水, 公司廣告的營運成本</li><li><strong>經營收入或虧損</strong> (Operating Income or Loss)<br>毛利減去營運總成本</li><li><strong>利息支出</strong> (Interest Expense)<br>屬於營業外收支, 舉例來說公司可能會把經營收入拿去做其他的投資</li><li><strong>其他收益總數/支出淨額</strong> (Total Other Income/Expenses Net)<br>也是屬於營業外收支</li><li><strong>稅前收益</strong> (Income Before Tax)<br>經營收入減去營業外收支</li><li><strong>淨收益</strong> (Net Income) <br>也就是稅前收益減去所得稅費用，此金額也是股東有權利分配享有的營業利潤 (也就是下一列的可分配給益通股股東的淨收入 Net Income available to common shareholders)</li><li><strong>基本每股盈利</strong> (Basic EPS) <br>也就是公司為每一股可以賺多少錢 EPS = 淨收益 / 在外流通股數<br>想了解更多 EPS 可以參考 Mr. market 大的<a href="https://rich01.com/what-is-eps/">文章</a></li></ul><p>了解這些細節後就可以看過去幾年公司的淨收益有沒有一直再成長而得知公司有沒有持續賺錢。當然有時候只是看淨收益是不夠的，像是公司雖然有在賺錢，但大部分的錢確是營業外收入，這就表示公司其實不務正業… <br>那到底營業外收支是從哪來的，詳細的資訊可能不會列在上表，這時就只能去翻公司的財報了。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d138773b21b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E8%8F%9C%E9%9B%9E%E4%BA%BA%E7%94%9F/%E7%9C%8B%E6%87%82%E6%90%8D%E7%9B%8A%E8%A1%A8-d138773b21b2">看懂損益表</a> was originally published in <a href="https://medium.com/%E8%8F%9C%E9%9B%9E%E4%BA%BA%E7%94%9F">菜雞人生</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[拍拍拍海外求職記]]></title>
            <link>https://medium.com/@jeanpan/%E6%8B%8D%E6%8B%8D%E6%8B%8D%E6%B5%B7%E5%A4%96%E6%B1%82%E8%81%B7%E8%A8%98-c2d8c85c01f5?source=rss-e9f40ce5bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d8c85c01f5</guid>
            <dc:creator><![CDATA[Jean Pan]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 12:51:32 GMT</pubDate>
            <atom:updated>2018-08-03T14:01:38.298Z</atom:updated>
            <content:encoded><![CDATA[<p>一直被腦公逼寫這半年的海外面試過程 🙄… 但比起其他篇大大們詳細的面試過程，這篇比較像是我的碎碎念和簡單的記錄。</p><p><strong>🗣 文長慎入<br></strong>前面是一堆廢話 🤪，只對面試過程有興趣的可以直接跳過後兩段 …</p><h4>不免俗的還是要先背景介紹</h4><p>113 CS 畢業後在台灣 Y 社寫全端兩年半，然後把存款梭哈不務正業的跑去紐約學設計，在紐約沒學到啥反倒是認識了很多珍貴的朋友和更確定自己還是最喜歡寫程式 👩🏻‍💻，一年後放棄 OPT 就回台灣了，回台後在一間新創公司寫前端打打雜。</p><h4>為什麼要找海外工作?</h4><p>當初會放棄 OPT 是因為男友的關係 ( 現在是腦公了 )，那時候他不希望我留在紐約工作，即使那時在紐約有拿到 offer 也很想有在海外工作的經驗，還是毅然決然的放棄回台挽救感情 … 恩我好偉大 ( 自己講被揍飛 👊🏻 )。</p><p>感情是有救回來了啦，但心中總是有點小小的遺憾 … 一直到去年中，腦公拿到一間新加坡新創的 offer，差一點我們就要去新加坡了 ( 這又是另一個故事了 🌝 )，這個轉機讓他終於有了想出國工作的念頭，也開始不排斥我找海外工作。</p><p>不過那時候我並沒有轉職的念頭，完全是一個佛系求職的狀態，不主動投履歷，不準備，不求強，等緣份到了我就會拿到 offer 了 ( 再次被揍飛 👊🏻 )。</p><p>後來是在前司開始有了一些推力，我才決定要給自己一次機會試試海外工作機會；我也給自己一個期限，如果找不到也沒關係，至少試過，不留遺憾。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ6Y-6EHMjwlBUi1zULFKA.jpeg" /><figcaption>面試順便帶腦公去玩 ( 爽的咧他 )</figcaption></figure><h3>面試策略</h3><p>先拿幾間來練習，最後再來試最想去的 S 社和大魔王 G 社! <br>結果根本就還沒有試到 S 社和 G 社我就不想再繼續了哈哈哈 ( 什麼爛策略 )</p><p>其實我投履歷和面試沒幾家，但每次面試都還是覺得很痛苦，後來是跟拿到美國 G 社 offer 的強者學長聊天才發現自己的面試次數相較之下根本就是小巫見大巫，我這個投不到 10 間的有什麼好唉唉叫的 … 而且我算是運氣好了，自己丟履歷的公司幾乎都有面試機會 …</p><h3>面試開始</h3><h4>Amazon</h4><p>工作地點：Vancouver, Canada<br>面試職位：Software Engineer<br>求職管道：在美國工作的強者學長介紹 recruiter，recruiter 跟我要履歷<br>面試流程：<br>1. Online assessment. 70 分鐘寫 2 題. 第一題還蠻簡單的，但第二題就超難，卡超久沒寫完 … 寫線上測驗最花時間的就是把題目看懂，英文敘述落落長，推薦可以用 <a href="https://www.hackerrank.com/">hackerrank</a> 針對這種落落長的題目做練習，另外也建議在寫 OA 的時候一定不要空白，有寫些東西絕對會比一片空白來的好</p><p>2. HR phone screen. 大約 50 分鐘. 就是跟 HR 做自我介紹，回答一些 behavior question，還有一些簡單的技術問題，像是某些演算法的時間複雜度之類的</p><p>3. On-site. 面試地點在香港，A 社提供機票和高級飯店. 有 4 場，每場 1 小時，從早上 9 點一直到下午 1 點. 每一場都面對一位面試官，面試官都是外國人，三位 engineers 和一位 hiring manager，會先花個 15 至 20 分鐘自介和回答 behavior question，其中三場是白板解題，一場 system design；白板解題不會太難，把 <a href="https://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview">CTCI</a> 看完寫完應該就沒問題</p><h4>Grab</h4><p>工作地點：Singapore<br>面試職位：Full-stack Engineer<br>求職管道：在 PTT oversea job 版看到大大的徵才文，投了履歷<br>面試流程：<br>1. Online project. 大概 50 分鐘. 先跟 HR 聊天 15 分鐘，HR 給一個 link 和描述 project 題目後就會把 Skype 掛掉，接著就是要在 35 分鐘內把 project 實作出來</p><p>2. Online technical interview. 2 小時. 前 1 小時考 front-end，後 1 小時考 back-end，結果我太久沒寫 back-end … 整個被洗臉，另外想提一下 front-end 的考法是用 <a href="https://jsfiddle.net/">jsfiddle</a> 線上同步寫 code，但 jsfiddle 的 collaborative tool <strong>超 難 用</strong>，別人的游標會把 code 擋住，別人做 focus 還會造成畫面產生詭異的動畫非常惱人，而且整個畫面超 lag，建議要面試前先試試 jsfiddle collaborative tool 做練習</p><h4>Shopee</h4><p>工作地點：Singapore<br>面試職位：Front-end Engineer<br>求職管道：Recruiter 透過 Linkedin 找到我<br>面試流程：<br>1. Front-end technical interview. 大約 1.5 小時. 跟一位前端工程師面試，考一些前端的基本題</p><p>2. Coding problem. 大約 1.5 小時. 跟一位後端工程師面試，考一些演算法、作業系統、DB 相關問題</p><p>3. Final. 大約 1 小時. 跟一位 manager 面試，一樣考一些演算法、前端和後端實作問題</p><p>相較其他大公司 Shopee 算是考得比較務實一點，解題也不會太難。</p><h4>Microsoft</h4><p>工作地點：蘇州, China<br>面試職位：Software Engineer<br>求職管道：Recruiter 透過 Linkedin 找到我<br>面試流程：<br>1. HR phone screen. 大約 30 分鐘. 一樣是自我介紹和 behavior question，接著 HR 寄了一份考題，寫完後回傳</p><p>2. Audio technical interview. 1 小時. 面試官是一位在蘇州微軟的俄國人工程師，考了兩題 linked-list 相關的題目，直接在 Skype 企業版上寫 code ( 還可以畫圖 )，最後面試官還跟我聊 React 和我寫的 react-native component 聊到不想掛掉 😅</p><p>3. Audio technical interview. 1 小時. 這場跟上一場一樣是 coding problem，只是這場是跟美國微軟的工程師面試，雖然是 coding problem，但不像上一場要把 code 寫出來，這場面試官只聽解題思路，一開始很緊張因為我怕沒有 code 或是畫圖輔助，面試官會聽不懂我的講解，但意外的還蠻順利的，最後面試官還多考了一題 follow-up，在他好心的提示下我也順利的答出來</p><p>4. On-site. 3 場面試，每場 1 小時. 本來 on-site 可以選擇飛去蘇州面試，但因為我台胞證過期，簽證也來不及，所以最後選擇 remote interview ( 其實我也有點懶的飛 )；每一場都有問 behavior questions 和至少一題解題，考了 Binary Search、BST 和 BFS，面試官都是 manager 等級的，其中兩個面試官對於要想離開台灣去蘇洲工作感到很驚訝 … ?</p><h4>Envato</h4><p>工作地點：Melbourne, Australia<br>面試職位：Front-end Engineer<br>求職管道：平常就有在看 <a href="https://tutsplus.com/">Envato tuts+</a> 的文章，剛好有天在官網看到職缺自己投履歷<br>面試流程：<br>1. HR &amp; technical interview. 1.5 小時. 跟 HR 面 30 分鐘，剩下的 60 分鐘跟一位前端工程師面試，問題都是前端相關，從 javascript prototype 一直問到 React &amp; Redux，也被問了 A-B testing</p><p>2. Take home project. 一個禮拜內完成. project 不難，不過我還是花了點時間寫 tests &amp; refactor.</p><p>3. Final. 1.5 小時. 要先跟兩位前端工程師討論上次寫的 take home project，然後再跟 manager 聊聊天</p><h3>總結</h3><p>面試真的很累 … 但堅持下去就對了! 要相信自己 ( 雖然我每次面試時都懷疑人生 )</p><p>謝謝一直對我不離不棄無條件支持我鼓勵我的家人朋友，也謝謝強者學長姊們的幫忙!</p><p>當然最重要還是腦公，謝謝你一切的包容和陪伴，你才最偉大 ❤️</p><p>#womanwhocode 👩🏻‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d8c85c01f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ JavaScript ] Splice, Slice, Split]]></title>
            <link>https://medium.com/@jeanpan/javascript-splice-slice-split-745b1c1c05d2?source=rss-e9f40ce5bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/745b1c1c05d2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[splice]]></category>
            <category><![CDATA[split]]></category>
            <dc:creator><![CDATA[Jean Pan]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 08:42:25 GMT</pubDate>
            <atom:updated>2017-08-12T12:43:13.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IaQrjx5xA2dO3WwOMEScJw.gif" /><figcaption>source : <a href="http://facebook.com/TheBossBaby">http://facebook.com/TheBossBaby</a></figcaption></figure><p>Splice, Slice, Split … they all start with S … Splice and Slice are almost twin … for me, sometimes it’s hard to memorize them, and it’s confusing to use them at the right place.</p><p>Before detailing each of them, let’s have a pizza 🍕 !</p><p>First, let’s say we have a sliced pizza, and we number each piece of them with 1, 2 … to 10, and we have a machine called <strong>splice. </strong>The <strong>splice</strong> machine can help us add or remove a piece of pizza. For example, with <strong>splice(1, 1)</strong>, we remove one piece of pizza starting from first piece ( so the second piece is removed ). Beside the <strong>splice</strong> machine, we have another machine called <strong>slice</strong>. The <strong>slice</strong> machine helps us to extract some pieces of pizza. It first creates a new pizza which is the same as the original one, and take some pieces of pizza out from the new one. For example, with <strong>slice(2, 3)</strong>, we extract one piece of pizza starting from second piece to third piece, but excluding the third one. Finally, we have another machine called <strong>split</strong>, the <strong>split</strong> machine helps us to split the pizza by “something”, for example, we want to split the pizza by sausage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*M61AUDeeywWsdfDFP4yJHg.png" /><figcaption>Pizza example with splice, slice and split.</figcaption></figure><h3>Splice</h3><p>splice() is a method of Array object. It’s a <a href="https://stackoverflow.com/questions/17039756/lisp-destructive-and-non-destructive-constructs">destructive function</a> since it changes the content of the input array.</p><pre>Array.prototype.splice()</pre><blockquote><em>The </em><strong><em>splice()</em></strong><em> method changes the contents of an array by </em><strong><em>removing</em></strong><em> existing elements or </em><strong><em>adding</em></strong><em> new elements</em></blockquote><pre>array.splice(start, [deleteCount], [item1], [item2])</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83b4636086536bc139b8b235a7a8b0fc/href">https://medium.com/media/83b4636086536bc139b8b235a7a8b0fc/href</a></iframe><p>Example : simulate <strong>shift() </strong>with <strong>splice()</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e727ba83f15579dc84dc826aa0145e7/href">https://medium.com/media/8e727ba83f15579dc84dc826aa0145e7/href</a></iframe><h4><strong>begin</strong> ( option )</h4><ul><li>undefined : slice begins from index 0</li><li>&gt;= 0 : zero-based index at which to begin</li><li>&lt; 0 : an offset from the end of the sequence</li></ul><h4><strong>end </strong>( option )</h4><ul><li>undefined : extracts through the end of the sequence</li><li>&gt;= 0 : zero-based index before which to end</li><li>&lt; 0 : an offset from the end of the sequence</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7c1d274b14e47f0b90ca99eccf76e54/href">https://medium.com/media/d7c1d274b14e47f0b90ca99eccf76e54/href</a></iframe><p><strong>Example</strong> : convert Array-like objects / collections to a new Array</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57b0e8d9e229077b4dea058784bc6ac/href">https://medium.com/media/c57b0e8d9e229077b4dea058784bc6ac/href</a></iframe><h3>Slice</h3><p><strong>slice()</strong> is a method of Array Object and String Object. It is non-destructive since it return a new copy and it doesn’t change the content of input array. <strong>slice()</strong> is normally used in function programming to avoid <strong>side-effect</strong>.</p><pre>Array.prototype.slice()</pre><blockquote><em>The </em><strong><em>slice()</em></strong><em> method returns </em><a href="https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy"><em>a shallow copy</em></a><em> of a portion of an array into a new array object selected from </em><strong><em>begin</em></strong><em> to </em><strong><em>end</em></strong><em> ( end is not included ). The original array will not be modified.</em></blockquote><pre>String.prototype.slice()</pre><blockquote><em>The </em><strong><em>slice()</em></strong><em> method extracts a section of a string and return it as </em><strong><em>new string</em></strong><em>.</em></blockquote><pre>array.slice(begin, end)</pre><pre>string.slice(begin, end)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a104a82339a02c39912df5901b4ec0d/href">https://medium.com/media/4a104a82339a02c39912df5901b4ec0d/href</a></iframe><h3>Split</h3><p><strong>split()</strong> is a method of String Object. It splits a string by separator into a new array.</p><pre>String.prototype.split()</pre><blockquote><em>The </em><strong><em>split()</em></strong><em> method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.</em></blockquote><pre>string.split([separator[, limit]])</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0a58c8074159e5d5497bf63cf4e17f/href">https://medium.com/media/bd0a58c8074159e5d5497bf63cf4e17f/href</a></iframe><p><strong>Example</strong> : check if the string is palindrome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d6a28ccd36a8488265b4b5811b98253/href">https://medium.com/media/8d6a28ccd36a8488265b4b5811b98253/href</a></iframe><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Tcq31xB3xia1gcjBCMD5SQ.png" /></figure><p><strong>Splice()</strong> is used to add or remove an element in a array, and it would modify the origin array. <strong>Slice()</strong> is used to extract elements from an array and return a new array, and it would not modify the origin array. <strong>Split()</strong> is used to convert the input string into an array by the separator, and since string is immutable, it would not modify the origin string. Be careful when using splice because it might cause side-effect.</p><h3>Reference</h3><p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice</a></p><p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice</a></p><p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/slice">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/slice</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745b1c1c05d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is CORS ( Cross-Origin Resource Sharing ) ?]]></title>
            <link>https://medium.com/@jeanpan/what-is-cors-cross-origin-resource-sharing-9f0c463621c6?source=rss-e9f40ce5bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f0c463621c6</guid>
            <category><![CDATA[cross-origin]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[back-end-development]]></category>
            <dc:creator><![CDATA[Jean Pan]]></dc:creator>
            <pubDate>Fri, 04 Aug 2017 15:57:41 GMT</pubDate>
            <atom:updated>2017-08-12T12:46:42.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Before talking about CORS, let’s start with <strong>cross-origin access</strong>. A web document makes a <strong>cross-origin access</strong> when it requests a resource from a different domain, protocol, or port. <br>For example, a web document served from <strong>http://domain-a.com</strong> makes an image request for <strong>http://domain-b.com.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*wnTTrWj5tn6VCQJHk9PHKQ.png" /><figcaption><a href="https://mdn.mozillademos.org/files/14295/CORS_principle.png">https://mdn.mozillademos.org/files/14295/CORS_principle.png</a></figcaption></figure><p>For security reason, browsers restrict the way of cross-origin access according to the <strong>same-origin policy.</strong></p><h3>Same-origin Policy</h3><p>The same-origin policy controls interactions between two different origins, and these interactions can be placed in three categories :</p><ul><li>Cross-origin <strong>write</strong> is allowed : links, redirects and form submissions.</li><li>Cross-origin <strong>embed</strong> is allowed : JavaScript tag &lt;script src=”…”&gt;&lt;/script&gt;, CSS link &lt;link rel=”stylesheet” href=”…”&gt;, images &lt;img&gt;, media files &lt;video&gt; and &lt;audio&gt;, plug-ins &lt;object&gt;, &lt;embed&gt; and &lt;applet&gt;</li><li>Cross-origin <strong>read</strong> is <strong>not allowed</strong> : XMLHttpRequest, Fetch API</li></ul><p>When developing front-end code for requesting data from different domain with XMLHttpRequest or Fetch API, you might encounter the problem of cross-origin, as the following screenshot. The error shows browser doesn’t allow cross-origin access because it’s a cross-origin read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*1ZmQMfSpGFCsT3FVJ0W-0g.png" /><figcaption>same-origin policy</figcaption></figure><p>One of the solution to allow cross-origin access is using <strong>CORS</strong>.</p><h3>CORS ( Cross-Origin Resource Sharing )</h3><p>The CORS mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.</p><h4><strong>How to make the CORS work ?</strong></h4><p>To make the CORS work, we can add HTTP headers that allow servers to describe a set of origin that are permitted to read that information using a web browser, and for different types of request, we have to add different headers. The request can be mainly divided into the simple request and the preflighted request.</p><p><strong>Simple Requests<br></strong>A request wouldn’t trigger a CORS preflight is so-called Simple Request. A simple request should meet all the following conditions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zc6_PKS-532eEVFGgToC4Q.png" /></figure><p>For a simple request, to make the CORS work, web server should set a HTTP header :</p><pre>Access-Control-Allow-Origin: *</pre><p>Setting this header means that the resource can be accessed by any domain. If we want to restrict to one specific domain, we can set it as :</p><pre>Access-Control-Allow-Origin: http://specific.domain.example</pre><p><strong>Preflighted Requests<br></strong>A preflighted request first send an HTTP request by the <strong>OPTIONS</strong> method to the server to determine whether the actual request ( the following request ) is safe to send. A preflighted request should meet all the following conditions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjwtIJNU0UXrJhoX-gsing.png" /></figure><p>For a preflighted request, to make the CORS work, web sever should set some HTTP headers :</p><pre>Access-Control-Allow-Origin: *</pre><pre>Access-Control-Allow-Methods: POST, GET, OPTIONS</pre><pre>Access-Control-Allow-Headers: X-PINGOTHER, Content-Type</pre><pre>Access-Control-Max-Age: 86400</pre><p>In addition to <strong>Access-Control-Allow-Origin</strong>, we should also set <strong>Access-Control-Allow-Methods</strong> to specify the method can be used for the the actual request, and <strong>Access-Control-Allow-Headers</strong> to confirm these headers are permitted to be used with the actual request, and finally <strong>Access-Control-Max-Age</strong> to give the value in seconds for how long the response to the preflight request can be cached.</p><p>Based on the request, we set different response headers on web server to make CORS work. However, can we do cross-domain without CORS ?</p><h4>Without CORS ?</h4><p>As mentioned above, the reason we can’t do cross-domain access is the same-origin policy, but some interactions are typically allowed, like &lt;script&gt; tag. So, we can use &lt;script&gt; tag to fulfill the cross-domain access by providing a callback function as the parameter in the request URL, and the server invokes the function by wrapping the returned result as the argument of the function. Actually, this is how the well-known <a href="https://en.wikipedia.org/wiki/JSONP"><strong>JSONP</strong></a> works.</p><h3>CSRF ( Cross-Site Request Forgery )</h3><p>According the same-origin policy, we know that cross-origin writes are typically allowed which might cause the security issue.</p><p>Assume that there is a bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like :</p><pre>POST /transfer HTTP/1.1</pre><pre>Host: bank.example.com</pre><pre>Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly</pre><pre>Content-Type: application/x-www-form-urlencoded<br></pre><pre>amount=100.00&amp;routingNumber=1234&amp;account=9876</pre><p>Now, assume you already authenticate to the bank’s website and then, without logging out, visit an evil website. The evil website contains an HTML page with the following form :</p><pre>&lt;form action=&quot;https://bank.example.com/transfer&quot; method=&quot;post&quot;&gt;</pre><pre>  &lt;input type=&quot;hidden&quot; name=&quot;amount&quot; value=&quot;100.00&quot;/&gt;</pre><pre>  &lt;input type=&quot;hidden&quot; name=&quot;routingNumber&quot; value=&quot;evilsRoutingNumber&quot;/&gt;</pre><pre>  &lt;input type=&quot;hidden&quot; name=&quot;account&quot; value=&quot;evilsAccountNumber&quot;/&gt;</pre><pre>  &lt;input type=&quot;submit&quot; value=&quot;Win Money!&quot;/&gt;</pre><pre>&lt;/form&gt;</pre><p>You click the button to WIN MONEY!, then you have unintentionally transferred $100 to the malicious user.</p><h4>How to prevent CSRF attack ?</h4><p>To prevent CSRF attack, check for an unguessable <strong>token</strong> in the request. For example, there is a randomly generated token represents in the HTTP parameter named <strong>_csrf</strong> :</p><pre>POST /transfer HTTP/1.1</pre><pre>Host: bank.example.com</pre><pre>Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly</pre><pre>Content-Type: application/x-www-form-urlencoded</pre><pre>amount=100.00&amp;routingNumber=1234&amp;account=9876&amp;_csrf=<strong>&lt;secure-random&gt;</strong></pre><h3>Conclusion</h3><p>To allow cross-origin access, we can use CORS. Based on the type of request, we have to set different response Headers in server to bypass the restriction, and if the request is not simple request, there is a preflight request first. Without CORS, we can utilize the embedding resource to make the cross-origin access work. Finally, be aware of CSRF attack and prevent it with checking a unguessable token in the request.</p><h3>Reference</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS">https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS</a></p><p><a href="https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html">https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f0c463621c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga pattern & redux-saga]]></title>
            <link>https://medium.com/@jeanpan/saga-pattern-redux-saga-e694a31576ab?source=rss-e9f40ce5bf3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e694a31576ab</guid>
            <category><![CDATA[notes]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[saga]]></category>
            <dc:creator><![CDATA[Jean Pan]]></dc:creator>
            <pubDate>Sun, 23 Oct 2016 08:53:18 GMT</pubDate>
            <atom:updated>2017-07-12T15:44:00.296Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is my understanding of saga pattern &amp; redux-saga. Please feel free to let me know if there is anything wrong.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*D5Fih25inCnZQdur7SXBLg.png" /><figcaption><a href="http://kotaku.com/adventure-time-explained-1703199261">http://kotaku.com/adventure-time-explained-1703199261</a></figcaption></figure><h3>Saga Pattern</h3><p>The term <em>saga</em> was introduced by Hector Garcia-Molina to define a mechanism to handle system failures in <em>long lived transaction.</em></p><p>From <a href="http://kellabyte.com/2012/05/30/clarifying-the-saga-pattern/">Clarifying the Saga Pattern</a>: <em>A Saga is a distribution of long-living transactions where steps may interleave, each with associated compensating transactions providing a compensation path across databases in the occurrence of a fault that may or may not compensate the entire chain back to the originator.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUfYVaCXhQHWqM13_6sLhQ.png" /><figcaption><a href="http://kellabyte.com/2012/05/30/clarifying-the-saga-pattern/">http://kellabyte.com/2012/05/30/clarifying-the-saga-pattern/</a></figcaption></figure><p>Above figure shows saga compensating due to a failed transaction (T4).</p><p>If all the transactions succeed: <em>T1 — T2 — T3 … — Tn</em> but if Tn failed : <em>T1 — T2 — T3 … — Tn — Cn — C(n-1)… — C1</em></p><p>Watch this talk to learn more about saga pattern.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxDuwrtwYHu8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxDuwrtwYHu8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxDuwrtwYHu8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb47e6b85d3a5963b1b834fe5de32ad/href">https://medium.com/media/8cb47e6b85d3a5963b1b834fe5de32ad/href</a></iframe><h3>redux-saga</h3><p><em>redux-saga</em> is a redux middleware for handling <strong>side effects.</strong></p><h4>How does redux-saga work ?</h4><p><em>redux-saga</em> is implemented with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">generator functions</a>. Generator functions can be paused and resumed and <em>yield</em> multiple values.</p><p>To understand how <em>redux-saga</em> works, let’s see the example directly and compare with <a href="https://github.com/gaearon/redux-thunk"><em>redux-thunk</em></a>.</p><p><strong>Example</strong> : Request data from a url when an UI component is clicked</p><p><strong><em>redux-thunk</em></strong></p><pre>function fetchUrl(url) {<br>  return (dispatch) <strong>=&gt;</strong> {<br>    dispatch({<br>      type: &#39;FETCH_REQUEST&#39;<br>    });<br><br>    fetch(url).then(data <strong>=&gt;</strong> dispatch({<br>      type: &#39;FETCH_SUCCESS&#39;,<br>      data<br>    }));<br>  }<br>}</pre><p>Dispatch <em>fetchUrl</em> when UI component is clicked.</p><pre>dispatch(<br>  fetchUrl(url)<br>);</pre><p>To avoid React components being pollute with business logic, <em>redux-thunk</em> is the simplest way to do that, However, it may have some problem …</p><ul><li>Difficult to test : to test the task logic, need to mock all invoked functions.</li><li>Difficult to coordinate concurrent tasks : how to cancel the pending fetch ?</li><li>Scattered business logic</li></ul><p><strong><em>redux-saga</em></strong></p><p>UI components dispatch plain object actions instead invoking the tasks directly.</p><pre>dispatch({<br>  type: &#39;FETCH_REQUEST&#39;,<br>  url: /* ... */}<br>);</pre><p>Create a saga that <em>watches</em> for the dispatched action and <em>forks</em> the task.</p><pre>import { take, fork, call, put } from &#39;redux-saga/effects&#39;;<br><br>// The watcher: watch actions and coordinate worker tasks<br>function<strong>*</strong> watchFetchRequests() {<br>  while(true) {<br>    const action <strong>=</strong> yield take(&#39;FETCH_REQUEST&#39;);<br><br>    yield fork(fetchUrl, action.url);<br>  }<br>}<br><br>// The worker: perform the requested task<br>function<strong>*</strong> fetchUrl(url) {<br>  const data <strong>=</strong> yield call(fetch, url);<br><br>  yield put({<br>    type: &#39;FETCH_SUCCESS&#39;,<br>    data<br>  });<br>}</pre><p>Note all function from <em>redux-saga</em> is pure functions and yields plain Javascript object called effect. For example, <em>call(fetchUrl, url)</em> returns <em>{ type: CALL, function: fetchUrl, args: [url] }</em>. The effects are created through functions but are executed in the middleware.</p><p>The separation between effect creation and execution makes testing simple.</p><pre>const generator <strong>=</strong> fetchUrl(&#39;http://api&#39;);</pre><pre>const expected = call(fetch, &#39;http://api&#39;);<br>const actual = generator.next().value;<br>assert.deepEqual(expected, actual);</pre><p>Because of generators, we have much more flexibility to coordinate concurrent tasks.</p><pre>import { take, fork, cancel, call, put } from &#39;redux-saga/effects&#39;;</pre><pre>// cancel any pending fetch whenever request a new fetch<br>function<strong>*</strong> watchFetchRequests() {<br>  let currentTask;<br><br>  while(true) {<br>    const action <strong>=</strong> yield take(&#39;FETCH_REQUEST&#39;);<br>    <br>    if(currentTask) {<br>      yield cancel(currentTask);<br>    }<br><br>    currentTask <strong>=</strong> yield fork(fetchUrl, action.url);<br>  }<br>}</pre><h4>Why redux-saga ?</h4><ul><li><strong>Declarative effects</strong>: all operations in <em>redux-saga</em> yield plain Javascript objects, which makes it easier to test the business logic.</li><li><strong>Advanced async control flow</strong> : simply describe async flow with sync style and familiar control flow constructs.</li><li><strong>Concurrency management</strong> : provide primitives and operators to manage concurrency between tasks; able to <em>fork</em> multiple background tasks in parallel and <em>cancel</em> a running task.</li><li><strong>Side effect handler </strong>: all side effects are moved into sagas, UI components do not perform any business logic but only dispatch actions to notify what happened.</li></ul><h3>Conclusion</h3><p><strong>Saga pattern</strong> is a design pattern to handle system failures in long lived transaction by dividing the long lived transaction into a set of independent sub-transactions with compensating sub-transactions.</p><p><strong><em>redux-saga</em></strong> is a redux middleware for handling side effects which make React Redux App more testable, maintainable, and reusable.</p><h4>Reference</h4><ul><li><a href="http://kellabyte.com/2012/05/30/clarifying-the-saga-pattern/">Clarifying the Saga pattern</a></li><li><a href="http://survivejs.com/blog/redux-saga-interview/">Saga Middleware for Redux to Handle Side Effects : Interview with Yassine Elouafi</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e694a31576ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>