<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>De-bug: 一鍵跑版</title>
  <subtitle>{ web, computer, data }</subtitle>
  <link href="/atom.xml" rel="self"/>
  
  <link href="http://abalone0204.github.com/"/>
  <updated>2016-09-26T13:55:44.058Z</updated>
  <id>http://abalone0204.github.com/</id>
  
  <author>
    <name>Tsung-Chen Ku</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>創業的第零步：公司設立</title>
    <link href="http://abalone0204.github.com/2016/09/21/corp-gov-shit/"/>
    <id>http://abalone0204.github.com/2016/09/21/corp-gov-shit/</id>
    <published>2016-09-21T13:27:49.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>如果你要創業的話，你可能會設想遇到的問題有：資金、團隊⋯⋯，</p>
<p>但一定很難想像最煩人的難關會卡在政府那裡，</p>
<p>而且居然是卡在「設立公司」這麼基本的節骨眼上。</p>
<p>前幾天在<a href="https://goo.gl/gQzzd7" target="_blank" rel="external">facebook 上 po 了一篇敘述這一切有多荒謬的文章</a>，</p>
<p>我設立登記的是「閉鎖型股份有限公司」，</p>
<blockquote>
<p>如果你還不知道什麼是閉鎖型，</p>
<p>可以參考 <a href="http://www.inside.com.tw/2016/03/24/tailor-your-close-company" target="_blank" rel="external">inside 上的這篇</a></p>
</blockquote>
<a id="more"></a> 
<p><img src="http://twimg.edgesuite.net/images/ReNews/20151221/640_adee966a8f66e7e870331cb9aa61544d.jpg" alt="鐵飯碗"></p>
<blockquote>
<p><a href="https://www.youtube.com/watch?v=EXzreQfWgj8" target="_blank" rel="external">圖片來源</a></p>
</blockquote>
<p>不管是在股權架構還是從募資上來說，</p>
<p>都看的出來政府想要鼓勵創新的決心，</p>
<p>只是如果不是自己親身去辦，</p>
<p>還真的沒辦法瞭解踏出這個「創業的第零步」有多困難。</p>
<p>很多人常會抱怨台灣的政府制度跟不上，</p>
<p>但實際上這些困難點主要來自於公務體系的僵化，</p>
<p>這現象如果沒有被解決，</p>
<p>就算政府推動再先進的制度也毫無意義，</p>
<p>接著會照著下面的架構來敘述這個「意想不到的難題」。</p>
<ul>
<li><p><a href="#前言">前言</a></p>
<ul>
<li><p><a href="#「為什麼不找會計師辦就好？」">為什麼不找會計師辦就好</a></p>
</li>
<li><p><a href="#「為什麼設立公司很重要？」">為什麼設立公司很重要</a></p>
</li>
</ul>
</li>
<li><p><a href="#會遇到什麼樣的困難">會遇到什麼樣的困難</a></p>
<ul>
<li><p><a href="#閉鎖型股份有限公司在這樣的流程中沒有想像中靈活">閉鎖型股份有限公司在這樣的流程中沒有想像中靈活</a></p>
</li>
<li><p><a href="#僵化的處理方式">僵化的處理方式</a></p>
<p><a href="#1-公文的格式真的很重要嗎？">1. 公文的格式真的很重要嗎</a></p>
<p><a href="#2-補正來來回回的問題">2. 補正來來回回的問題</a></p>
<p><a href="#3-前後說法完全不同">3. 前後說法完全不同</a></p>
<p><a href="#4-不同窗口對於案件狀況理解不足">4. 不同窗口對於案件狀況理解不足</a></p>
<p><a href="#5-回覆期限">5. 回覆期限</a></p>
</li>
</ul>
</li>
<li><p><a href="#結論：一個鼓勵卡位的制度只會養出怪物">結論：一個鼓勵卡位的制度只會養出怪物</a></p>
</li>
</ul>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>試想如果你有一個覺得很棒的主意，</p>
<p>再加上研究後發現政府有許多鼓勵新創產業的政策，</p>
<p>一切都讓你迫不急待，</p>
<p>但當你開始辦<code>「公司設立登記」</code>時，</p>
<p>你會發現我們的制度，或是代表制度的窗口，並沒有想像中這麼鼓勵我們，</p>
<p>甚至是排斥我們去做任何事情。</p>
<p>今天要講的是各種制度上的荒謬，以及申辦公司設立登記會遇到的狗屁倒灶，</p>
<p>期待以後要創業的人看完以後知怎樣避免這些鳥事；</p>
<p>但更期待當局者能讓制度更完善，</p>
<p>畢竟台灣不是一個資源豐富的地方，</p>
<p>我們完全沒有必要在這種沒有必要的地方讓做事情變得更艱難。</p>
<p>看到後來你真的會發現，制度的設計其實並沒有太大的問題，</p>
<p>有問題是公務人員裁量的部份。</p>
<blockquote>
<p>或者該說公務人員長官裁量的部份。</p>
<p>e.g: </p>
<p>你會發現你做的事情可能第一次是對的、第二次又錯了。</p>
</blockquote>
<h2 id="「為什麼不找會計師辦就好？」"><a href="#「為什麼不找會計師辦就好？」" class="headerlink" title="「為什麼不找會計師辦就好？」"></a>「為什麼不找會計師辦就好？」</h2><p>最多人聽到設立公司這麼麻煩之後會問這句話，</p>
<p>而網路上教學大多也是準備好資料，</p>
<p>然後丟給會計事務所去幫你代辦。</p>
<blockquote>
<p>舉例：</p>
<p><a href="https://goo.gl/o3TpYT" target="_blank" rel="external">在台灣開公司要經過哪些程序？</a></p>
</blockquote>
<p>我比較想問的是：「為什麼這麼基本的東西要找會計師？」</p>
<p>儘管這筆開銷是小錢，</p>
<p>但老實說，除了資本額簽證之外，</p>
<p>其他應該都是創業者自己能搞定而且該了解的。</p>
<p>股東會、董事會、股權結構的設計、章程，</p>
<p>以及你所登記地址的營業產業別是否有限制，</p>
<p>或是你的公司業務算不算是特許行業，</p>
<blockquote>
<p>我想我們都該同意會計師不會比你更了解你的公司</p>
</blockquote>
<p>如果沒有親身經歷一遍是沒辦法體會的。</p>
<p>重點在我們根本不該習慣一個這麼基本的東西，</p>
<p>居然複雜到要請人來代辦才搞得定，</p>
<p>這樣還要公務員幹嘛？有會計師就好了啊！</p>
<h2 id="「為什麼設立公司很重要？」"><a href="#「為什麼設立公司很重要？」" class="headerlink" title="「為什麼設立公司很重要？」"></a>「為什麼設立公司很重要？」</h2><p>只講最重要也最普遍的一點：因為資金，</p>
<p>其他諸如開發票、買東西報帳這些都算是小事情，</p>
<blockquote>
<p>你一定會發現有很多事是沒有公司的話，連做的資格都沒有的。</p>
</blockquote>
<p>創業需要申請一些補助案，</p>
<p>而不管還是民間或私人的補助案大多都需要先有公司，才能開始動，</p>
<p>或是拿到補助款；</p>
<p>更別說你如果需要募資，你也得要有間公司給人家當股東啊！</p>
<p>公司開張第一天就是錢在燒，所以錢當然要越快進來越好，</p>
<p>「設立公司」這件事情不該是一個瓶頸，</p>
<p>否則拖延了一兩個月後，公司產品的風頭可能就過了，</p>
<p>好不容易找到的 VC 也跑了。</p>
<blockquote>
<p>對了，其實給會計師辦也不見得會比較快，</p>
<p>不過可以確認的是如果你不是自辦的話，公務員會對你比較友善一點 XD</p>
</blockquote>
<h1 id="會遇到什麼樣的困難"><a href="#會遇到什麼樣的困難" class="headerlink" title="會遇到什麼樣的困難"></a>會遇到什麼樣的困難</h1><p>接著就來談談我在過去兩個月的神奇旅程：</p>
<h2 id="閉鎖型股份有限公司在這樣的流程中沒有想像中靈活"><a href="#閉鎖型股份有限公司在這樣的流程中沒有想像中靈活" class="headerlink" title="閉鎖型股份有限公司在這樣的流程中沒有想像中靈活"></a>閉鎖型股份有限公司在這樣的流程中沒有想像中靈活</h2><p>我不能說閉鎖型股份有限公司是個完美的制度，</p>
<p>但它確實對新創事業有很大的幫助，</p>
<p>前提是：<strong>政府的承辦人員也要這樣覺得</strong>。</p>
<p>當我準備好資料準備送件時，旁邊有個服務人員有空幫我檢查，</p>
<p>途中不停的問我：「閉鎖型真的有比較好嗎？」、「為什麼要辦這個？」</p>
<p>當然，基於好奇我也問了他閉鎖型的缺點是什麼，</p>
<p>結果居然被兇了：「反正不是比較新的就比較好啦！」</p>
<p>檢查完後，到了櫃台也再度被詢問：「為什麼要辦閉鎖型？」</p>
<p>後來我才理解，並不是因為閉鎖型有什麼麻煩，</p>
<p>而是我們去辦了他們不熟悉的業務，造成他們的麻煩。</p>
<h2 id="僵化的處理方式"><a href="#僵化的處理方式" class="headerlink" title="僵化的處理方式"></a>僵化的處理方式</h2><p>如果只是被問幾下、酸幾句話就結束，</p>
<p>那我覺得也是人之常情，畢竟如果可以簡單，誰想要複雜？</p>
<p>但最麻煩的其實是在公文來回的時間消耗，</p>
<p>下面就來一一列舉：</p>
<h3 id="1-公文的格式真的很重要嗎？"><a href="#1-公文的格式真的很重要嗎？" class="headerlink" title="1. 公文的格式真的很重要嗎？"></a>1. 公文的格式真的很重要嗎？</h3><p>可能有人會說一天要看幾千份公文，格式正確當然很重要。</p>
<p>你可能會覺得格式跑一點沒差，資料對比較重要。</p>
<p>但格式是否「正確」屬於公務人員可以裁量的部分，</p>
<p>大多都是只要一兩行跨頁或是稍微歪掉，</p>
<p>就算你上面的資料全部都是正確的也沒有用：</p>
<blockquote>
<p>假如你用 google drive 來開，</p>
<p>或甚至你用的作業系統不是 windows，</p>
<p>這樣的事情其實是很常見的。</p>
</blockquote>
<p><img src="http://i.imgur.com/y9BDFnd.jpg" alt="大俠請重新來過"></p>
<p>老實說我們到底審查的是那些框框格子，</p>
<p>還是框框和格子裡的字呢？</p>
<p>旁邊雖然有一台電腦可以印，但使用電腦的隊伍常常是大排長龍。</p>
<p>有個很直觀的做法是印一些空白表格，</p>
<p>讓民眾有錯直接手改來填就好了。</p>
<p>但這個意見此時是完全行不通的，</p>
<p>那個告訴我閉鎖型公司很麻煩的公務員說：</p>
<p>「上面有規定，申請表一定要全都電腦印刷。」</p>
<p>好一個上面有規定，一定要用電腦印出來紙筆寫的東西，</p>
<p>這就是我們數位化之後的政府嗎？</p>
<p>至於那個一站式填表單的系統有多難用我也不想再多說，</p>
<p>最白癡的地方是你並不是在線上把表格填完，</p>
<p>而是把表格下載下來，然後再上傳檔案上去。</p>
<blockquote>
<p>有蓋章的部分還是要印出來再掃描才行。</p>
</blockquote>
<h3 id="2-補正來來回回的問題"><a href="#2-補正來來回回的問題" class="headerlink" title="2. 補正來來回回的問題"></a>2. 補正來來回回的問題</h3><p>假如格式終於沒問題了，</p>
<p>你要面臨的就是你資料不齊、不正確時需要做的事情。</p>
<p>在這個流程中，這件事叫做「補正」，</p>
<p>這一步才是惡夢的開始。</p>
<ul>
<li><p>首先是你要看懂補正的內容，有些公文簡直不像是要寫給人看的。</p>
</li>
<li><p>有錯不會一次全檢查出來，會下次再給你驚喜。</p>
</li>
</ul>
<p>舉例來說：</p>
<p>你第一次送的案件有兩個錯誤，承辦人員請你回去補正；</p>
<p>你把錯誤改正、送件後，他可能又會檢查出一個第一次送件就有的錯誤；</p>
<p>而有些錯誤其實公務人員是有裁量空間的，</p>
<p>有幾次需要補正案的原因是因為章程中要有股份轉讓限制， </p>
<p>實際上章程一直都有，只是我們的限制跟範本章程的不一樣，</p>
<p>處理的窗口還要我們改成跟範本一樣，</p>
<p>啊靠，都要照範本走的話幹嘛還自己定章程？</p>
<p>其實很多錯誤都是帶著印章去可以改完的，</p>
<p>只是公務員會用前一項的藉口來跟你說：「要用電腦印出來才行」，</p>
<p>所以你就得回家隔天再來辦一次。</p>
<h3 id="3-前後說法完全不同"><a href="#3-前後說法完全不同" class="headerlink" title="3. 前後說法完全不同"></a>3. 前後說法完全不同</h3><p>同一個公務員，上一次和這一次說的話可能會完全不同。</p>
<p>以上這兩點看似有點太抽象，</p>
<p>我就直接舉這次遇到的例子吧！</p>
<p>這次遇到的事情是章程上有「錯誤」需要補正，</p>
<p>我當然是詢問能不能補上修改後的章程或是蓋章更改就行。</p>
<p>「不行喔！你們章程要改的話，要再開一次董事會來修章程才行。」</p>
<p>要改幾個字就可以搞定的東西，</p>
<p>要再重新開會、會議記錄、新舊章程比對⋯⋯</p>
<p>只是這些紙本上的東西的確麻煩，</p>
<p>但最要命的還是依公司法規定，</p>
<p>要在會議召開的十天前通知我的董事才能開董事會，</p>
<p>而董事最快也是在公司設立時才選出來，</p>
<p>這也就代表著送件的日期又要再度往後挪。</p>
<p>我：「一定要這麼麻煩嗎？這好像不太合理」</p>
<p>結果就是收到一個斬釘截鐵的答案，跟我說：「一定要照這樣走。」</p>
<p>大概過了一個禮拜多，等到時間可以讓我們再次送件時，</p>
<p>仍然是有錯誤，我和我的夥伴們這時候已經快崩潰了，</p>
<p>因為這代表著要再多等十天。（這時候已經一個月過去）</p>
<p>結果承辦人員想了一下說：「不然你們撤件重辦好了？」</p>
<p>這樣就可以直接送新的章程來，當作之前的都沒送過。</p>
<p>到這裡我已經開始發現人員的問題實在太大了，</p>
<p>一下可以、一下不行，如果一開始就可以的話為什麼不要說呢？</p>
<p>這時候我們還是忍下來了，</p>
<p>因為真的只想快點把這個狗屁倒灶給結束。</p>
<p>不過我也想到幫忙資本額簽證的會計師跟我說過：</p>
<p>「如果送件日離公司發起日超過一定時間要罰錢。」</p>
<p>去看了一下申請須知：</p>
<blockquote>
<p>應於董事長就任或取得許可文件後15日內申請設立登記，逾期申請，將依公司法第387條第6項，處董事長新臺幣1萬元以上5萬元以下罰鍰。</p>
</blockquote>
<p>於是我們當場詢問了承辦人員這樣會不會有問題，</p>
<p>他也是拍胸脯跟我們保證說他那邊有紀錄，這樣做不會罰錢。</p>
<h3 id="4-不同窗口對於案件狀況理解不足"><a href="#4-不同窗口對於案件狀況理解不足" class="headerlink" title="4. 不同窗口對於案件狀況理解不足"></a>4. 不同窗口對於案件狀況理解不足</h3><p>再來就是不同的人，會給你不同的答案。</p>
<p>乍看之下蠻直觀，但跑這種公文時，你不會喜歡驚喜的。</p>
<p><img src="https://media.giphy.com/media/KV46eX1r1u4ms/giphy.gif" alt="甚麼叫驚喜"></p>
<p>接續上面的事情，這次將更改後的章程給在場的人員檢查。</p>
<p>：「我可以幫你送件，但是你距離董事長就任後已經超過十五天，這樣一位董事要罰一萬塊喔！你能接受嗎？」</p>
<p>接受你老師個教師節快樂啦！</p>
<p>於是我跟他說明：「上一次承辦人員跟我們說你們那邊有紀錄⋯⋯」</p>
<p>接著我的發言被打斷，他表示：「規定就是這樣，沒辦法。」</p>
<p>另一位公務員看著我們情緒有點激動，也過來打圓場：</p>
<p>「我想這是服務人員和民眾間常有的美麗的誤會。」</p>
<p>「他上次可能不是那個意思，應該是說你還是能送件，但是要快一點的話就要罰鍰。」</p>
<p>哇操勒，都給你講就好了，美麗誤會這種屁話都講得出來。</p>
<p>最後，我還是不信邪的抽了號碼牌去櫃檯問，</p>
<p>請上次的承辦人員出來面對，</p>
<p>沒想到他一口就說：「沒問題呀！這個不用罰錢，我們這邊有紀錄。」</p>
<blockquote>
<p>千萬記得負責你案件的承辦人員是誰，</p>
<p>有事情問他最準。（相對最準）</p>
</blockquote>
<h3 id="5-回覆期限"><a href="#5-回覆期限" class="headerlink" title="5. 回覆期限"></a>5. 回覆期限</h3><p>辦完後，會有一個 QR code 讓你上網去查詢進度，</p>
<p>有寫一個回覆的期限是十天。</p>
<blockquote>
<p>正常來講兩三天內就應該結束。</p>
</blockquote>
<p>但我們最後一次就傻傻等了十天，案件進度仍然是審核中，</p>
<p>於是我們就打了電話去詢問。</p>
<p>得到的結果是：「很早就送去長官桌上等他看了，可是長官好像出去。」</p>
<p>⋯⋯所以我們又莫名其妙蒸發掉了十天。</p>
<p>如果以後有要辦這種東西的話，</p>
<p>最好是第二天就開始打給承辦人詢問。</p>
<p>所幸提出申訴之後，</p>
<p>很多東西真的是只要用筆改一改，</p>
<p>簽名蓋章就可以解決了。</p>
<h1 id="結論：一個鼓勵卡位的制度只會養出怪物"><a href="#結論：一個鼓勵卡位的制度只會養出怪物" class="headerlink" title="結論：一個鼓勵卡位的制度只會養出怪物"></a>結論：一個鼓勵卡位的制度只會養出怪物</h1><p>也許我可能特別衰小，</p>
<p>但我相信在跑公司設立 RPG 的人中，</p>
<p>我一定不是被公務員刁難的特例。（包括會計師）</p>
<p>甚至，我也認為「公司設立」並不是一個最麻煩的東西。</p>
<p>有位現在也在公家機關服務的朋友告訴我會這樣的原因，</p>
<p>是因為怕送上去的東西被長官挑剔，</p>
<p>所以他們當然不會以民眾方便為主，而是看長官看不看得順眼。</p>
<p>這也就是為什麼他們那麼在乎格式和一些用字的原因。</p>
<p>另外，</p>
<p>許多的審查真的嚴格到像把想開公司的人當成罪犯一樣，</p>
<p>而這樣的防堵機制有堵住什麼嗎？</p>
<p>很巧的是我在第二次去送件時，</p>
<p>就遇到一位氣挫挫的老先生說他被人冒名開了一間公司，</p>
<p>記得很清楚他說：</p>
<p>「他來很多次都沒有人要幫他處理，一定要等事情真的要鬧大才有人理嗎？」</p>
<p>可見這個防堵機制既不夠安全，又麻煩，</p>
<p>同時也點出了這些基層公務人員的通病，</p>
<p>平時亂弄一通，一定要等到人真的要跟你翻臉或是投訴了，</p>
<p>才開始認真幫你做事情。</p>
<p>後來投訴之後才明白，</p>
<p>台北市的承辦人員其實也不太熟悉閉鎖型，連規費也是收錯的。</p>
<blockquote>
<p>不過他全部推給櫃台人員就是了，</p>
<p>有一部份的人其實不是公務員，而是約聘，</p>
<p>老實說，整體而言給我一種把錯推給約聘人員的感覺，唉</p>
</blockquote>
<p>這就是我們的公家機關，</p>
<p>因為會升官的不是認真做事的人，而是不會犯錯的人，</p>
<p>而不做事，就自然不會犯錯，</p>
<p>這也是為什麼一看到你是不熟悉的業務就一拖再拖的關鍵原因。</p>
<p>還有另一個問題是所謂的「鐵飯碗」，</p>
<p>基本上考上公務員以後，沒有淘汰制度，</p>
<p>也就是說劣質的公務員你也完全拿他沒辦法，</p>
<p>是個在根本裡就追求卡位的制度。</p>
<blockquote>
<p>我知道連續三年考績丙等會免職，</p>
<p>但實際執行起來是個鄉愿的笑話，有興趣可以 google 一下，</p>
<p>考核官通常都會讓考績丙等輪流當，這樣就不會有人被免職。</p>
</blockquote>
<p>我們這些公家機關服務的使用者，</p>
<p>遇到不合理的事情當然不能跟他摸摸鼻子算了，</p>
<p>這次經驗以後，讓我沒辦法輕易相信這些公務人員說的話，</p>
<p>我希望有一天我們政府機關的行政素質是能夠讓人民信任的，</p>
<p>而不是將公家機關與低效率、劣質聯想在一起。</p>
<blockquote>
<p>世大運表示：唉</p>
<p>推薦報導者文章：<a href="https://www.twreporter.org/a/civil-servants-sum" target="_blank" rel="external">誰讓台灣公僕變庸才</a>，</p>
</blockquote>
<p>總之，底下的執行人員如果是這個樣子，</p>
<p>那不管我們的制度和法規再怎麼先進都沒有用；</p>
<p>如果我們國家真的有要鼓勵創新的話，</p>
<p>先教會這些承辦人員如何讓設立公司變得簡單一點再來說吧！</p>
<p>希望當局者看到以後能有所改善，</p>
<p>不要再讓創業者消耗時間在這種莫名奇妙的地方了。</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;如果你要創業的話，你可能會設想遇到的問題有：資金、團隊⋯⋯，&lt;/p&gt;
&lt;p&gt;但一定很難想像最煩人的難關會卡在政府那裡，&lt;/p&gt;
&lt;p&gt;而且居然是卡在「設立公司」這麼基本的節骨眼上。&lt;/p&gt;
&lt;p&gt;前幾天在&lt;a href=&quot;https://goo.gl/gQzzd7&quot;&gt;facebook 上 po 了一篇敘述這一切有多荒謬的文章&lt;/a&gt;，&lt;/p&gt;
&lt;p&gt;我設立登記的是「閉鎖型股份有限公司」，&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;如果你還不知道什麼是閉鎖型，&lt;/p&gt;
&lt;p&gt;可以參考 &lt;a href=&quot;http://www.inside.com.tw/2016/03/24/tailor-your-close-company&quot;&gt;inside 上的這篇&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
    
    </summary>
    
    
      <category term="corp" scheme="http://abalone0204.github.com/tags/corp/"/>
    
      <category term="gov" scheme="http://abalone0204.github.com/tags/gov/"/>
    
  </entry>
  
  <entry>
    <title>我的前端工程師之路：找工作</title>
    <link href="http://abalone0204.github.com/2016/07/30/front-end-career-job/"/>
    <id>http://abalone0204.github.com/2016/07/30/front-end-career-job/</id>
    <published>2016-07-30T17:32:23.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>本著取之於網路，回饋於網路的心境，</p>
<p>來拋磚引玉地分享一下一個前端工程師找工作的心得，</p>
<p>主要想分享一下整個「找工作的流程」，</p>
<p>中間也會穿插一下對於徵才者的一些看法。</p>
<p>希望讓求職或徵才的人，都能更了解要怎麽對待前端工程師 XD</p>
<a id="more"></a>
<p>題外話是之前有寫過一篇關於前端工程師入門學習的：</p>
<blockquote>
<p>PTT 文章代碼：#1MdHy0Kj</p>
<p>網誌連結：<a href="http://abalone0204.github.io/2016/01/18/way-to-fed/" target="_blank" rel="external">http://abalone0204.github.io/2016/01/18/way-to-fed/</a></p>
</blockquote>
<p>網路上還有很多其他優秀的前端學習資源，</p>
<blockquote>
<p>推一下保哥的：<a href="http://blog.miniasp.com/post/2016/02/02/JavaScript-novice-advice-and-learning-resources.aspx" target="_blank" rel="external">我要成為前端工程師！給 JavaScript 新手的建議與學習資源整理</a>。</p>
</blockquote>
<p>只是到底要學習到怎樣的程度才能找到想要的工作，</p>
<p>這中間的隔閡，似乎還是很容易讓人迷惘，</p>
<p>所以今天這篇就自己的經驗來來分享，</p>
<p>身為一個普通新鮮人是怎樣準備「找工作」這件事情，</p>
<p>老實說我覺得重點永遠都不該是什麼研究履歷怎樣排版、怎麼猜 HR 或面試官看履歷的眼動，</p>
<p>甚至問學什麼比較有前途，</p>
<p>我不是說這些事情不重要，這些事情你當然還是得做，</p>
<p>只是如果你只是做了這些而已，往往都是治標不治本的方法。</p>
<p>做一件事情有分「術」跟「道」，</p>
<p>「術」是具體的做法；「道」則是做事的過程和背後的哲學。</p>
<p>而前面講的這些具體作法，我把它們歸類為求職「術」（方法），</p>
<p>這些「術」，不懂寫程式的獵頭可能都比你瞭解，</p>
<p>所以身為一個實事求是軟體開發者，</p>
<p>我們應該要找到自己為了什麼工作，</p>
<p>以及想做什麼工作的本質，</p>
<p>也就是探詢自己的求職之「道」，</p>
<p>懂了之後再搭配方法（術），找工作這件事自然也就水到渠成，</p>
<p>就算有問題，也會比較知道問題出在哪裡。</p>
<p>也許我工作經驗還不足，有想地不夠的地方，</p>
<p>但希望能幫助到還在迷惘的大家，</p>
<p>當然，也希望能省掉一點面試者和被面試者的時間（XD。</p>
<p>註：<br>  這裡的前端工程師指的是不負責出圖，<br>  而是要跟設計師協作、寫 html、CSS、JavaScript 的 web 前端工程師。                                    </p>
<p>整篇文章的結構大概是這樣子：</p>
<ul>
<li><p>我的背景介紹</p>
</li>
<li><p>找工作之前</p>
<ul>
<li>為什麼要當前端工程師</li>
</ul>
</li>
<li><p>開始找工作</p>
<ul>
<li><p>評估自己的能力</p>
</li>
<li><p>找到想去的地方及準備</p>
</li>
<li><p>面試完以後</p>
</li>
<li><p>開價</p>
</li>
</ul>
</li>
<li><p>自己的經驗分享</p>
</li>
<li><p>結論</p>
</li>
</ul>
<h1 id="背景介紹"><a href="#背景介紹" class="headerlink" title="背景介紹"></a>背景介紹</h1><p>非四大的學士，不是本科系，</p>
<p>2014 年中開始學習寫程式，</p>
<p>之前完全沒有寫程式的經驗，到現在差不多寫了兩年。</p>
<p>學習的路上碰到蠻多困難，也常常卡關，</p>
<p>覺得自己資質在眾工程師間絕對是屬於中下的，</p>
<p>當年要學寫程式時，我的朋友告訴我：</p>
<p>「寫程式太吃天份了啦！現在才起步太晚了。」</p>
<p>那時候的我看完了 vgod 的「神乎其技的程式設計之道」，</p>
<p>儘管滿腔熱血，</p>
<p>但也清楚這世界上有像 vgod 這種天份好、夠努力，</p>
<p>更別說對 CS 充滿熱情的人在；</p>
<p>只是後來仔細想想，哪個領域不是這樣子？</p>
<p>再者，開始工作和學習也發現：</p>
<p>其實許多人的努力根本就還沒達到要談天份的程度，</p>
<p>就算不跟一些怪物比，這世界還是充滿機會的 XD</p>
<p>而且連我都能做到的事情，相信大概八成以上的人都能輕鬆做到。</p>
<p>這篇文章寫的很粗淺，</p>
<p>主要的目的還是讓新手能省掉一堆繞遠路的時間。</p>
<h1 id="為什麼要當前端工程師"><a href="#為什麼要當前端工程師" class="headerlink" title="為什麼要當前端工程師"></a>為什麼要當前端工程師</h1><p>首先要問自己的問題是：</p>
<p>「為什麼要當前端工程師？」</p>
<p>為什麼你要來寫程式？為什麼你不去做後端？</p>
<p>為什麼你不想做 Data Engineer？</p>
<p>這不是一個答錯就找不到工作的題目，</p>
<p>但是從來沒有思考過這個問題，那其實就是在思考上懶惰，</p>
<p>現實做了再多努力也很容易只是徒勞。</p>
<p>而且這個問題的答案也是當你遇到挫折時，</p>
<p>真正有辦法支持你繼續走下去，而不是得過且過的根。</p>
<p>在這裡也分享我對這個問題的想法，</p>
<p>對我來說初期選擇網頁前端的原因是：</p>
<ul>
<li>可以看到東西，比較有成就感。</li>
</ul>
<p>後來也發現前端雖然很好入門，</p>
<p>但是前端仍然那麼缺人的原因，</p>
<p>是勞力的供需雙方都出了問題。</p>
<p>首先是「勞力的供給者（求職者本身）」的問題：</p>
<p>  正因為網頁前端算是個「好入門」的領域，</p>
<p>  所以許多人不把自己當作真的「軟體工作者」，</p>
<p>  以為我們只要照著需求拉拉頁面就好，</p>
<p>  有的也為了薪水所以跟風跳了過來卻發現薪水不如預期，</p>
<p>  這時候就不免得問自己如果這個工作門檻這麼低，</p>
<p>  被取代性這麼高，</p>
<p>  到底哪來的自信覺得這樣有辦法坐領高薪？</p>
<p>  許多「前端工程師」忽略了瀏覽器本身是多麽複雜的軟體，</p>
<p>  也忽略了你將來可能要協作的會是一個複雜的系統，</p>
<p>  少了一些電腦科學和軟體工程的知識當基石，</p>
<p>  面對問題時你會少了很多想像力（這裡指對於解決問題的方法）。</p>
<p>  蠻常聽到一些人在抱怨說學校裡教的理論脫節，</p>
<p>  老實說，技術的東西會隨著時間迭代演進，</p>
<p>  也許教授沒有告訴你這個跟你未來要做的事情有什麼關係，</p>
<p>  捫心自問一下，</p>
<p>  其實我們是在根本不夠熟悉理論前就嫌他不實用而已。</p>
<p>  Computer Science 一直都是一門實用的科學，</p>
<p>  但如果只是為了考試而念，那當然就不實用啦！</p>
<p>  前端的生態大概每幾個月就會跑出一大堆新東西，</p>
<p>  (像是最近很紅的：<code>Vue.js</code>)</p>
<p>  當追隨各種 framework 或是工具時，</p>
<p>  很容易顯得浮躁，會學的不好甚至盲從，</p>
<p>  更重要的是看一下這個「工具」能解決什麼問題，</p>
<p>  細細探究下去會發現「工具」為什麼要這樣設計的哲學，</p>
<p>  也會發現其中有許多原本以為很「理論」的東西被實作在裡面，</p>
<p>  而這些「研究」就是在鍛鍊選擇和學習工具時的品味，</p>
<p>  長期來看，這讓你自己更快速地建立自己的知識體系，</p>
<p>  也更快速地提升自己的價值。</p>
<p>  只是許多人忽略了這點，</p>
<p>  忙著去追逐一些絢麗的畫面、火熱的框架，</p>
<p>  這就是對自己的職業定位不夠清楚的緣故。</p>
<p>再來是「徵才者」的問題：</p>
<p>  這裡會比較單純一點，</p>
<p>  因為大多都是徵才方不知道怎樣面試一個前端，</p>
<p>  或者不了解前端的重要性。</p>
<p>  有些人心裡覺得：</p>
<p>  「啊不就畫面拉一拉、改一改，有什麼難的？」</p>
<p>  或是：</p>
<p>  「有必要搞那麼多 Framework 或是 pattern 嗎？什麼 MVC、MVVM 的。」</p>
<p>  但實際上 UI 實做起來的程式碼很容易就不合邏輯，</p>
<p>  要寫出能夠維護、好擴充的程式碼更是需要實務和一定的「品味」，</p>
<p>  舉例來說可以看看下面這個<a href="https://github.com/staltz/flux-challenge" target="_blank" rel="external">Flux challenge</a>，</p>
<p>  這是 Cyclejs 的作者對於 Flux 這個單向資料流框架發起的挑戰：</p>
<p>  不用下去實作，光是看一下就會發現要良好地控制資料流、畫面的 state ，</p>
<p>  以及設計一個精巧的 template 有多困難。</p>
<p>  正因為對求職者期待錯誤，薪水自然也錯誤，</p>
<p>  到最後如果好運把東西做出來，那可能也跟屎有七八分相像。</p>
<p>  當你真的開始重視前端的複雜度和專業時，</p>
<p>  自然面試的水平以及來應試者的水平就會上升，</p>
<p>  好的企業跟求職者是相輔相成的。</p>
<p>講完雙方，言歸正傳一下，</p>
<p>對於我來說，</p>
<p>後端 API 的邏輯是理性的，</p>
<p>設計師圖稿的美感是感性的，</p>
<p>而前端就是站在理性跟感性中間的介面設計者，</p>
<p>處於這個位置，不管你面向哪邊都能夠看到許多有趣的東西，</p>
<p>而前端本身又一直是一個「生機蓬勃」的領域，</p>
<p>這是我為什麼選擇這個職業的原因，</p>
<p>但這也是我認為前端工程師容易浮燥、忘記如何追求知識本質的原因，</p>
<p>這個之後再提。</p>
<h1 id="開始找工作"><a href="#開始找工作" class="headerlink" title="開始找工作"></a>開始找工作</h1><h2 id="評估自己的能力"><a href="#評估自己的能力" class="headerlink" title="評估自己的能力"></a>評估自己的能力</h2><p>這裡不空談什麼人格特質，</p>
<p>只談兩件事情，一為學歷，二為技術力。</p>
<p>學歷：</p>
<p>  首先是大家最愛討論的學歷，</p>
<p>  老實說，如果不是大公司或是比較傳統的企業，</p>
<p>  前端對於這一塊需求還好。</p>
<p>  儘管學歷可能不會是一個好的評斷標準，</p>
<p>  但在履歷數量大的時候直接用學歷篩，</p>
<p>  對於想偷懶的徵才者來說蠻方便的。</p>
<p>  另外，學歷是最現實的東西，</p>
<p>  假如你跟我一樣學歷不好看，卻又非得進擺明需要四大碩本科學歷的大公司不可，</p>
<p>  儘管上網問完有些人會告訴你有作品集比較重要 blabla 之類的，</p>
<p>  但八成的情況是這些意見比較多是屬於安慰性質而已，</p>
<p>  還是務實一點努力去考碩士或是換個目標吧 XD</p>
<p>  把時間花在猶豫和求安慰真的是最可惜的一件事情。</p>
<p>  如果你只是單純想要學習的話，你並不需要成為學生，</p>
<p>  可以先看看<a href="http://goo.gl/6eSXoK" target="_blank" rel="external">這篇文章</a></p>
<p>技術力：</p>
<p>  前端的東西太多太雜，我不會一一細列，</p>
<p>  但對於你每個想火力展示的技術，</p>
<p>  我認為都可以分為以下三個等級：</p>
<h3 id="Level-0-用過，看過-document-上的-get-started。"><a href="#Level-0-用過，看過-document-上的-get-started。" class="headerlink" title="Level 0: 用過，看過 document 上的 get started。"></a>Level 0: 用過，看過 document 上的 get started。</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">基本上處於這個階段的技能，別硬要放上履歷表，</div><div class="line">而是問問自己除了好玩之外為什麼要學這個？</div><div class="line">最好能講出這技術背後的想法為何，</div><div class="line">如果連你仔細思考後都無法回答這問題，</div><div class="line">那真的得問問自己為什麼要把時間分配在這上面。</div><div class="line">舉例：</div><div class="line">  我對於 Cycle.js 這個 framework 就是如此，</div><div class="line">  當初只是為了瞭解處處是 Observable 到底是怎樣的體驗。</div><div class="line"> （意外相當不錯 XD，只是基於現實考量沒有用它）</div><div class="line">  有興趣可以看看我的 Blog 上有些簡單的學習紀錄。</div></pre></td></tr></table></figure>
<h3 id="Level-1-有應用在實務上過。（指上-production）"><a href="#Level-1-有應用在實務上過。（指上-production）" class="headerlink" title="Level 1: 有應用在實務上過。（指上 production）"></a>Level 1: 有應用在實務上過。（指上 production）</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">通常服務一上到 production 環境後會遇上各式各樣的毛，</div><div class="line">而且到這等級，好運一點的話你會有作品可以 Demo，</div><div class="line">再怎麼不濟也要好好回想自己曾經遇到哪些 issue 或 bug，</div><div class="line">甚至是比較麻煩的地方，將這些經驗分享給其他人，</div><div class="line">大多都能得到不錯的回饋。</div><div class="line">在這一階段的技術能證明你能獨立作業並有實質產出。</div></pre></td></tr></table></figure>
<h3 id="Level-2-摸透技術的本質"><a href="#Level-2-摸透技術的本質" class="headerlink" title="Level 2: 摸透技術的本質"></a>Level 2: 摸透技術的本質</h3><p><img src="http://i.imgur.com/Q101c5V.png" alt="摸底"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">這裡指的摸透，不只是有豐富的實務經驗，</div><div class="line">同時也對這個技術背後設計的哲學有深入了解，</div><div class="line">能去進行底層的擴充和更改。</div><div class="line">如果真的到達這境界，也應當要能理解其發展出來的歷史背景，</div><div class="line">很多時候會發現這些東西跟商業或是人的關聯性，</div><div class="line">讓你能更站在作者的角度去思考。</div><div class="line">到達這一階段的人，通常能分享知識並提升身邊的人素質。</div><div class="line"></div><div class="line">舉例：</div><div class="line">  我在看過 「Secret of the JavaScript Ninja」這本書前，</div><div class="line">  曾經傲慢地覺得 jQuery 實在沒存在的必要，</div><div class="line">  但細究當時的背景，</div><div class="line">  一個有辦法跨越各個瀏覽器以及提供一個簡潔的介面來做 ajax 是很了不起的事情，</div><div class="line">  更別提 jQuery 在原始碼中有許多程式設計的典範，</div><div class="line">  以及為了工程需求而做的折衷，</div><div class="line">  這些都不是一個沒摸透 JavaScript 本質的人能寫出來或是理解的。</div></pre></td></tr></table></figure>
<p>至於到底要放哪些在履歷表上，或是該怎麼展現，</p>
<p>如果你還是沒辦法靠自己完成，</p>
<p>相信我，對自己有了上述的理解，</p>
<p>你也更容易讓別人願意幫助你。</p>
<blockquote>
<p>假如只說個我會 jQuery、React、Angular，</p>
<p>除非通靈，不然沒人知道你的「會」是到哪個程度，</p>
<p>身為一個工程師，連自己的規格都描述不清楚那是非常不專業的事情。</p>
</blockquote>
<h2 id="找到想去的地方及準備"><a href="#找到想去的地方及準備" class="headerlink" title="找到想去的地方及準備"></a>找到想去的地方及準備</h2><p>假如你已經很有經驗，獵人們自然會排隊幫你找工作；</p>
<p>反之你就得自己做打算，</p>
<p>但公司種類簡直跟前端框架一樣也是百百種，</p>
<p>如果有任何文章提出一個應付所有公司的解法，那一定是在扯淡。</p>
<p>這階段真正要解決的問題是：</p>
<p>「你到底想要在哪裡工作？」</p>
<p>很多人會抱怨把 104 打開或者是投履歷都沒人理或者沒回，</p>
<p>其中一個很大的問題是因為這是個「海投」的策略。</p>
<p>將心比心的問題，身為一個求職者，</p>
<p>你會希望自己被好好對待，</p>
<p>可是「海投」卻是一個讓你沒辦法好好對待每個機會的策略，</p>
<p>這不見得對於每個人都成立，但我認為對方如果要付出面試時間，</p>
<p>自己也應該準備足夠，讓對方沒有在浪費時間的感覺，</p>
<p>正因為每個選擇都要付出很多時間，</p>
<p>所以有沒有想清楚是不是非這間公司不可就顯得非常重要。</p>
<p>接著繼續解開「到底想在哪工作」這個問題，</p>
<p>前端工程師目前在台灣是一個有點尷尬的職位，</p>
<p>光是看許多人套 bootstrap 就稱自己 fullstack，</p>
<p>就知道蠻多公司不重視前端這個工作，</p>
<p>所以挑選時，除了各方上網搜尋意見之外，</p>
<p>也別忘記去公司的網頁 inspect element 看看 XD</p>
<p>不要想著進去一間公司就要待到老死，這樣對你和公司都是壞事，</p>
<p>（想待到老死去考國營就好了，不用在這塵世間浮沈）</p>
<p>先設定一個目標和時間，比如說待兩年，</p>
<p>然後問問自己這兩年你要完成什麼事情，待在這間公司有辦法幫你達到嗎？</p>
<blockquote>
<p>很多職涯相關的文章已經講說面試要準備問題問面試官講到爛掉，</p>
<p>但每次提供的問題都蠻垃圾的，有時候會有點分不清楚內容農場跟媒體的差別。</p>
<p>總之「要問面試官什麼」的根本就是上述那個問題，</p>
<p>所有你想要的，都應該 contribute 到你想完成的那件事情上，</p>
<p>而有了這個問題當作基礎，就很好延伸思考了。</p>
</blockquote>
<p>當你現在準備和了解的越少，</p>
<p>你未來可能要付出的代價越大。</p>
<h2 id="開價"><a href="#開價" class="headerlink" title="開價"></a>開價</h2><p>談薪水其實已經偏向「術」，只是這個階段實在太重要 XD，</p>
<p>所以特別講一下。</p>
<p>一定要開一個讓自己覺得有尊嚴的薪水，</p>
<p>不要因為很怕自己不值得這個錢而開一個自己無法接受的低價錢，</p>
<p>不然你進去才一直覺得公司欠你，心態會漸漸扭曲。</p>
<p>另外這裡沒辦法寫的很具體，</p>
<p>是因為我實在無法評斷會某技能，就值多少錢，</p>
<p>一來，會到什麼程度只有自己最清楚，也關係到面試怎麼展現；</p>
<p>二來，地區、產業、公司的不同，都會大大影響。</p>
<p>如果前面的準備有做好，</p>
<p>這時候應該對自己的喊價應該要充滿信心才對。</p>
<h2 id="面試完以後"><a href="#面試完以後" class="headerlink" title="面試完以後"></a>面試完以後</h2><p>一面試完，</p>
<p>要先思考的問題就是：</p>
<p>「你有多想跟面試你的那些（個）人一起工作？」。</p>
<p>就算未來不是你真正 co-work 的人，</p>
<p>我相信待在同一間公司的人都會有某些相同的特質。</p>
<p>面試要考倒一個人是相當容易的，</p>
<p>所以要自己過濾一下哪些明顯是在刁難。</p>
<p>（履歷上完全沒提到自己會，卻又故意問非常深入的部分。<br> 比如說應徵前端結果問你熟不熟 CSP 和 Actor model的差別）</p>
<p>再來就是檢討自己有哪些不足的，簡單分可以分成兩種：</p>
<p>一，短期內學習就有效果的。（e.q：某個東西的 API 不熟悉，或是某個名詞你不知道是啥）</p>
<p>二，需要長期養成基礎的，要再擬個計畫來補強。（e.q：演算法不熟）</p>
<p>接著再更改履歷，</p>
<p>強烈建議用 git 來管理自己的履歷，</p>
<p>你也更容易從中看到每個版本的自己有什麼進步，</p>
<p>而針對不同的公司只要新開一個 branch 就好了。</p>
<p>每次面試完以後，我也會回到再度「評估自己的能力」一次，</p>
<p>如果你準備的夠足夠，</p>
<p>面試完時通常都能獲得更多，</p>
<p>因為你去的都是你認可的公司，同時你每次也是全力以赴。</p>
<h1 id="自己的經驗分享"><a href="#自己的經驗分享" class="headerlink" title="自己的經驗分享"></a>自己的經驗分享</h1><p>這裡首先來分享自己曾經忽略的幾個點。</p>
<blockquote>
<p>什麼資料結構、演算法，或是作業系統就不再提。</p>
</blockquote>
<ul>
<li>SEO：<ul>
<li>有些公司會需要前端工程師來處理 SEO 相關的東西，其實是蠻合理的。<br>推薦一下<a href="https://github.com/kuitos/kuitos.github.io/issues/33" target="_blank" rel="external">這篇文章</a>，看完你會知道為什麼我認為這跟前端有關了：</li>
</ul>
</li>
</ul>
<ul>
<li><p>網路：</p>
<ul>
<li>這裡的用「網路」是有點太 general，不過我找不到更簡單的詞來說明。<br>舉例來說熟悉 http 中各個 method 的特性和 status code 會蠻有幫助，<br>了解網路相關的知識也容易讓你對產品做出更多優化。（cdn, gzip）</li>
</ul>
</li>
<li><p>瀏覽器：</p>
<ul>
<li>了解瀏覽器是怎麼運作的，<br>推薦一下<a href="http://goo.gl/WFb7T" target="_blank" rel="external">這篇文章</a>，應該很多人看過了 XD</li>
</ul>
</li>
</ul>
<p>然後是一些迷思：</p>
<h2 id="1-寫文章或是經營-github-上的-side-project"><a href="#1-寫文章或是經營-github-上的-side-project" class="headerlink" title="1. 寫文章或是經營 github 上的 side project"></a>1. 寫文章或是經營 github 上的 side project</h2><p>我的經驗是如果單純為了找工作才刻意去做這些事情，</p>
<p>那很可能會無法持之以恆，</p>
<p>我寫的所有技術筆記都是為了讓自己以後忘記時有東西可以參考，</p>
<p>同時我也認為我們平常工作上靠 google 得到那麼多資訊，</p>
<p>自己應該有一些回饋的責任，</p>
<p>而且如果搜尋問題的前幾個結果能是繁體中文的文章，</p>
<p>那會是一件很莫名令人開心的事情。(XD)</p>
<p>總之如果這些事情是你真心認為想做再去做才有意義。</p>
<h2 id="2-參加社群"><a href="#2-參加社群" class="headerlink" title="2. 參加社群"></a>2. 參加社群</h2><p>人脈真的很重要，而分享和吸收新知也相當有意義。</p>
<p>我記得第一次參加大型技術 conference 時，</p>
<p>看著世界上許多人技術和商業都如此強勁，</p>
<p>真的會起到相當大的激勵作用。</p>
<p>不過就這陣子的觀察，有些活動很近似於大拜拜的行為，</p>
<p>好像參拜完大神會得到靈魂上的昇華一樣，</p>
<p>這不是一個很健康的現象。</p>
<p>參與社群時不應該時時想著從中得到什麼，</p>
<p>假如得到了什麼，更要思考著該怎麼樣去做有效地回饋才是。</p>
<h2 id="3-是否有必要去上職訓、資策會⋯⋯等等課程"><a href="#3-是否有必要去上職訓、資策會⋯⋯等等課程" class="headerlink" title="3. 是否有必要去上職訓、資策會⋯⋯等等課程"></a>3. 是否有必要去上職訓、資策會⋯⋯等等課程</h2><p>我沒有上過任何上述的課程，這裡也不想談論自學和上課哪個好。</p>
<p>但這些課程中，大多都是在業界實戰過的老師，</p>
<p>出來的學生素質會參差不齊的原因很有可能是因為：</p>
<p>他們沒真正想過「為什麼想成為前端工程師」，</p>
<p>去上課可能是一個更有效率建立知識系統的選擇，</p>
<p>但把上課當成一個速成脫離低薪的「速解法」，</p>
<p>就很容易高不成低不就，甚至怪這些課程沒有用。</p>
<h1 id="結論"><a href="#結論" class="headerlink" title="結論"></a>結論</h1><p>最後想要分享一下之前在 twitter 上看到的這段話：</p>
<p>「<br>  你使用的語言被人嘲笑<br>  職業被藐視<br>  解決問題的努力被視為噱頭<br>  自詡不弄髒手的人輕視你面對的問題<br>  執行引擎到處是實作者從未重視過的 Bug<br>  所有跨平台的承諾都在增加你要解決的問題<br>  UX認為要的效果很簡單<br>  QA給你的回報難對上問題<br>  最後，報酬通常低於平均水準</p>
<p>  你說，你想成為前端工程師<br>」 </p>
<ul>
<li><a href="https://goo.gl/FsIVoA" target="_blank" rel="external">@GregWang</a></li>
</ul>
<p>網頁前端的迭代速度跟特別的技能樹，</p>
<p>讓這個職業既有吸引力又讓人容易感到挫折，</p>
<p>希望透過這個分享讓大家更了解前端工程師，</p>
<p>也讓對前端有興趣卻不敢踏出那一步的人可以試試看。</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="http://huli.logdown.com/posts/703835" target="_blank" rel="external">[心得] 十年程式自學之路 - huli</a></p>
</li>
<li><p><a href="http://abalone0204.github.io/2016/01/18/way-to-fed/" target="_blank" rel="external">我的前端工程師之路</a></p>
</li>
<li><p><a href="http://blog.vgod.tw/2008/07/05/%E8%BF%BD%E6%B1%82%E7%A5%9E%E4%B9%8E%E5%85%B6%E6%8A%80%E7%9A%84%E7%A8%8B%E5%BC%8F%E8%A8%AD%E8%A8%88%E4%B9%8B%E9%81%93%E4%B8%80%EF%BC%89/" target="_blank" rel="external">追求神乎其技的程式設計之道 - vgod</a></p>
</li>
<li><p><a href="http://www.iswifting.com/2016/03/25/do-professional-code/" target="_blank" rel="external">做博士还是做一个专业的程序员？</a></p>
</li>
<li><p><a href="https://github.com/kuitos/kuitos.github.io/issues/33" target="_blank" rel="external">Web语义化标准解读</a></p>
</li>
<li><p><a href="http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/" target="_blank" rel="external">How Browsers Work: Behind the scenes of modern web browsers</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;本著取之於網路，回饋於網路的心境，&lt;/p&gt;
&lt;p&gt;來拋磚引玉地分享一下一個前端工程師找工作的心得，&lt;/p&gt;
&lt;p&gt;主要想分享一下整個「找工作的流程」，&lt;/p&gt;
&lt;p&gt;中間也會穿插一下對於徵才者的一些看法。&lt;/p&gt;
&lt;p&gt;希望讓求職或徵才的人，都能更了解要怎麽對待前端工程師 XD&lt;/p&gt;
    
    </summary>
    
    
      <category term="front-end" scheme="http://abalone0204.github.com/tags/front-end/"/>
    
      <category term="career" scheme="http://abalone0204.github.com/tags/career/"/>
    
  </entry>
  
  <entry>
    <title>Text Mining &amp; Analysis： week 2</title>
    <link href="http://abalone0204.github.com/2016/07/21/illinois-text-mining-week-2/"/>
    <id>http://abalone0204.github.com/2016/07/21/illinois-text-mining-week-2/</id>
    <published>2016-07-21T16:09:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>這是一篇關於 Coursera 上：<a href="https://www.coursera.org/learn/text-mining/home/welcome" target="_blank" rel="external">Text Mining and Analytics (伊利諾伊大學香檳分校)</a>的筆記。</p>
<p>主要在探討 text mining 和 分析，</p>
<p>經過我整理之後應該會變得好懂很多。</p>
<p>這是第二個禮拜課程的筆記，</p>
<p>假如你還沒看過第一個禮拜，</p>
<p>可以先看這裡：</p>
<ul>
<li><a href="http://abalone0204.github.io/2016/07/15/illinois-text-mining-week-1/" target="_blank" rel="external">Text Mining &amp; Analysis： week 1</a></li>
</ul>
<a id="more"></a>
<h1 id="Outline"><a href="#Outline" class="headerlink" title="Outline"></a>Outline</h1><p>這一週裡面會包含三個主題：</p>
<ul>
<li><p>Syntagmatic relation discovery</p>
</li>
<li><p>Topic Mining and analysis</p>
</li>
<li><p>Probabilistic Topic Models</p>
</li>
</ul>
<h1 id="前情提要"><a href="#前情提要" class="headerlink" title="前情提要"></a>前情提要</h1><p>在開始之前先快速複習一下上禮拜學習的東西，</p>
<p>試著去解釋和回答以下幾個問題，</p>
<p>如果還會遲疑的話可能要回到<a href="http://abalone0204.github.io/2016/07/15/illinois-text-mining-week-1/" target="_blank" rel="external">第一篇</a>稍微看一下：</p>
<ul>
<li><p>deep techniques 和 shallow techniques 的 trade-off 是什麼</p>
</li>
<li><p>了解為什麼 NLP 是困難的</p>
</li>
<li><p>Paradigmatic relation 以及 Syntagmatic relation</p>
</li>
<li><p>Paradigmatic 以及 BM25 加上 tf-idf </p>
</li>
</ul>
<p>這一章節可能會有比較多特別的名詞或公式，</p>
<p>不過拆開來一步步理解，</p>
<p>他們其實都是蠻直觀的概念，</p>
<p>我以前也是因為這堆符號嚇到被老師當掉過，</p>
<p>實際去學才發現，</p>
<p><del>嗯老師考卷還是出太難馬的幹</del></p>
<p>其實背後的本質就是簡單的數學而已。</p>
<h1 id="Syntagmatic-relation-discovery"><a href="#Syntagmatic-relation-discovery" class="headerlink" title="Syntagmatic relation discovery"></a>Syntagmatic relation discovery</h1><p>要找到 Syntagmatic relation，</p>
<p>要觀察的就是 co-occurence，（同時出現的機率）。</p>
<h2 id="Intuition"><a href="#Intuition" class="headerlink" title="Intuition"></a>Intuition</h2><p>為了培養一下對於挖掘組合性關係（Syntagmatic relation）的直覺，</p>
<p>直接來看下面這個問題，</p>
<p>有以下三個字，</p>
<p>你覺得哪個字最好去預測它在文本中會不會出現呢？</p>
<blockquote>
<p>這裡的文本指的可能是 pseudo document、句子、段落</p>
</blockquote>
<p>$$ W_1 = “meat”$$</p>
<p>$$ W_2 = “the”$$</p>
<p>$$ W_3 = “unicorn”$$</p>
<p>答案會是 “the”，因為它到處都是嘛！</p>
<p>再來可能會是 unicorn，因為這不是個常用的單字，出現機率可能很低。</p>
<blockquote>
<p>矽谷表示： __</p>
</blockquote>
<p>最後則是 meat，因為他出現的機率最為「難預測」，</p>
<p>你很難精確說明怎樣的情形「一定會」出現 meat，</p>
<p>也很難解釋什麼條件下「一定不會」出現 meat。</p>
<p>上述的情境其實可以當作一個 function 來看，</p>
<p>輸入是某個字（meat, the, unicorn），</p>
<p>輸出則是它會不會出現在文本中，</p>
<p>會就是 1，不會就是 0。</p>
<p>而上述的這個概念就是「隨機變數（Random Variable）」，</p>
<blockquote>
<p>沒錯，我一開始也很疑惑，</p>
<p>但隨機變數就是一個函數，</p>
<p>數學家才不管什麼可維護性，naming 這種東西就是他們說了算，懂？</p>
</blockquote>
<p>將一個機率空間中的值（子集合）對應到一個實數上（這裡是 0 或 1），</p>
<p>這就是 random variable。</p>
<p>$$<br>X_w = 0 \, or \, 1<br>$$</p>
<p>如果 w 存在文本中就等於 1，反之則為 0。</p>
<p>所以 <code>X_w</code> 如果越隨機，就越難預測，</p>
<p>問題來了，該怎麼去量化誰「比較隨機」呢？</p>
<h2 id="Entropy"><a href="#Entropy" class="headerlink" title="Entropy"></a>Entropy</h2><p>要靠的是 Entropy(熵)，不要被這個名詞嚇到了，</p>
<p>其實它也只是一個值，算出來越高，</p>
<p>代表這個 random variable 越隨機，這也就代表越難預測。</p>
<p>來看它的公式怎麼寫：</p>
<p>$$<br>\sum_{v = 1 \, or \, 0} -p(X_w=v)log_2 p(X_w=v)<br>$$</p>
<blockquote>
<p>這裡為了方便計算，要假設 log_2(0) 為 0。</p>
</blockquote>
<p>接著拿執硬幣的機率來舉例，</p>
<p>假設有個公正的硬幣，兩面出現的機會相等，都是 0.5；</p>
<p>另一個只會擲出反面的硬幣，</p>
<p>哪一個會算出較高的熵？</p>
<p>首先把公式列出來看：</p>
<p>$$<br>entropy = -p(x=正面)log_2(p(x=正面))-p(x=反面)log_2(p(x=反面))<br>$$</p>
<p>再來先帶入公正的硬幣：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">p(x=正面) = 0.5</div><div class="line"></div><div class="line">p(x=反面) = 0.5</div></pre></td></tr></table></figure>
<p>$$<br>H(X) = -\frac{1}{2} log_2(\frac{1}{2})-\frac{1}{2} log_2(\frac{1}{2}) = 1<br>$$</p>
<p>而帶入</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">p(x=正面) = 0</div><div class="line"></div><div class="line">p(x=反面) = 1</div></pre></td></tr></table></figure>
<p>$$<br>H(X) = -0 \times log_2(0)- 1 \times log_2(1) = 0<br>$$</p>
<p>看的出來公平硬幣的熵較高，</p>
<p>而在數學上證明了這個直覺是對的，</p>
<p>公平硬幣比起只會出現一面的硬幣來的隨機多了！</p>
<h2 id="Conditional-Entropy"><a href="#Conditional-Entropy" class="headerlink" title="Conditional Entropy"></a>Conditional Entropy</h2><p>很快地會發現，前面講的只是單一個字會不會出現的隨機性，</p>
<p>換言之這裡只計算了 occurence；</p>
<p>但我們真正想要知道的是跟其他字同時出現的 co-occurence 啊！</p>
<p>這時候就是 conditional entropy 上場的時候。</p>
<p>當知道字句中有 “eats” 這個字存在時，</p>
<p>出現 “meat” 的機率可以表示為下面這樣</p>
<p>$$<br>P(X_m = 1 \mid X_e = 1)<br>$$</p>
<p>所以直接把 entropy 公式中的<code>P(X_m)</code>換成 <code>P(X_m | X_e)</code>即可算出 conditional entropy：</p>
<p>$$<br>H(X_m \mid X_e = 1) = -p(X_m \mid X_e =1 )log_2(p(X_m \mid X_e =1 ))<br>$$</p>
<p>而 <code>H(X_m)</code> 會是 <code>H(X_m | X_e=1)</code> 的上界</p>
<blockquote>
<p>因為 <code>H(X_m)</code> = <code>H(X_m | X_e=1)</code> + <code>H(X_m | X_e=0)</code></p>
</blockquote>
<p>這裡隱含著的道理就是「做的任何事情都是要降低不確定性」，</p>
<p>conditional entropy 不會超過原本的 entropy，</p>
<p>所謂的文本探勘，就是一個降低不確定性的過程，</p>
<p>而我們也發相資料間要彼此相關，才能夠有效的降低不確定性。</p>
<p>有了這個數學上的直覺、清楚我們目標在哪後再繼續。</p>
<h1 id="Mutual-Information"><a href="#Mutual-Information" class="headerlink" title="Mutual Information"></a>Mutual Information</h1><h2 id="Concept"><a href="#Concept" class="headerlink" title="Concept"></a>Concept</h2><p>上述知道使用 conditional entropy 可能會降低不可預測性後，</p>
<p>就要來問：要怎麼量化減少的程度為多少？</p>
<p>這時候就會用到 mutual information，</p>
<p>它代表的意義就是當我們知道其中一個詞時，</p>
<p>到底降低了多少的不確定性，</p>
<p>而兩個詞之間，相關的程度到底是多少？</p>
<p>這時候就要來介紹 Mutual Information，</p>
<p>Mutual information 用數學符號表示：</p>
<p>$$<br>I(X;Y) = H(X) - H(X|Y) = H(Y) - H(Y|X)<br>$$</p>
<p>圖大概是長這個樣子：</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Entropy-mutual-information-relative-entropy-relation-diagram.svg/512px-Entropy-mutual-information-relative-entropy-relation-diagram.svg.png" alt="mutual info"></p>
<p>而 <code>I(X;Y)</code> 有三個特性：</p>
<ul>
<li><p>大於等於 0</p>
</li>
<li><p>對稱性：</p>
</li>
</ul>
<p>$$<br>I(X;Y) = I(Y;X)<br>$$</p>
<ul>
<li>只有 X 與 Y 互相獨立時，<code>I(X;Y)</code>會等於 0(完全相關時，則為 1)</li>
</ul>
<p>這樣講可能還是不太能理解，所以我舉數學之美中的例子。</p>
<p>Bush，是翻作布希總統還是灌木叢總統呢？</p>
<p>要讓機器分辨這件事情，</p>
<p>如果有人沒理解過 NLP，會說如果後面是接總統或職稱，那就是總統，</p>
<p>不是的話，那就是灌木叢，</p>
<p>事實上我們都知道這樣的做法會讓語法的計算多到無法進行計算，或計算過於緩慢；</p>
<p>因此我們應該要利用的就是 Mutual Information，</p>
<p>我們先找到文本中提到布希是指總統時的文本，</p>
<p>並計算其中 Mutual information 最高的字：總統、美國、國會⋯⋯等 <code>(a)</code>，</p>
<p>而灌木叢也是同理：森林、野生、土壤⋯⋯ <code>(b)</code>。</p>
<p>最後在計算時，只要看上下文中的詞，是 <code>a</code> 還是 <code>b</code>比較多就可以了。</p>
<p>前面是從熵的角度去切入，</p>
<p>更 practical 一點的做法是用機率的角度去看，</p>
<p>這裡介紹 KL-divergence 這個公式，</p>
<p>（或稱作 relative entropy 相對熵）</p>
<p><img src="http://i.imgur.com/BOQuu10.png" alt="kl-div"></p>
<blockquote>
<p>格式請見諒，mathjax 在同一行要使用 X_{..}系列時會出錯</p>
</blockquote>
<p>如果你想知道這個公式的數學意義下面會有解釋，</p>
<p>但其實你只要記住：</p>
<ul>
<li><p>相對熵越大，兩個函數差異越大，反之亦然。</p>
</li>
<li><p>假如今天輸出的是兩個分配，只要取值都大於 0 ，那麼相對熵也可以表示這兩個分配的差異。</p>
</li>
</ul>
<p>kl-divergence 最值得注意的是 log2 裡面的這一項：</p>
<p>$$\frac{p(X_w1 = u,\, X_w2 = v)}{p(X_w1 = u) p(X_w2 = v)}$$</p>
<p>如果<code>X_w1</code> 跟 <code>X_w2</code>是相互獨立的話，</p>
<p>分子分母會相同，</p>
<p>因此這一項會趨近於 1，</p>
<p>再取 log 後就會變成 0，</p>
<p>這樣在計算 divergence 時就會把這一項相互獨立的給去掉。</p>
<p>算 mutual information 的意義在於：</p>
<p>「因為我們想了解如果知道其中一個字，</p>
<p>到底能下降多少的不確定性？」</p>
<p>而兩個字出現的機率如果是完全獨立，（意思即 w2 出不出現都跟 w1沒差）</p>
<p>那 mutual information 自然要等於零，</p>
<p>因為知道其中一個字完全不會影響另一個出現的機率，</p>
<p>自然也不會降低任何不確定性了。</p>
<h2 id="Joint-和-Independent-Optional"><a href="#Joint-和-Independent-Optional" class="headerlink" title="Joint 和 Independent(Optional)"></a>Joint 和 Independent(Optional)</h2><blockquote>
<p>這裡是對獨立事件的小小補充，</p>
<p>講的並不嚴謹，</p>
<p>如果你對於 joint probability 和獨立事件沒有問題的話，可以跳過這一段</p>
<p>或是指正一下我哪裡的說明有誤 XD</p>
</blockquote>
<p>如果你沒有修過機率論的話可能會覺得：</p>
<p>「欸？ <code>p(X_w1 = u, X_w2 = v)</code> 不就等於<code>p(X_w1 = u) * p(X_w2 = v)</code>嗎？」</p>
<p>但很可惜事實並非如此，用符號來表示並不直觀，</p>
<p>幸運的是機率這種東西用舉例的來觀察就會很直覺，</p>
<p>我們舉下面這個例子來說：</p>
<p>我們有四個 document，</p>
<p>X 則是 document 中有出現 w1或 w2 的隨機變數，</p>
<p>有出現 = 1，沒出現 = 0。</p>
<table>
<thead>
<tr>
<th>document</th>
<th>X_w1</th>
<th>X_w2</th>
</tr>
</thead>
<tbody>
<tr>
<td>d1</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>d2</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>d3</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>d4</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
<p><code>p(X_w1 = 1)</code> = 0.75<br><code>p(X_w1 = 0)</code> = 0.25<br><code>p(X_w2 = 1)</code> = 0.75<br><code>p(X_w2 = 1)</code> = 0.25</p>
<p>而 <code>p(X_w1 = 1, X_w2 = 1)</code>則為 0.5，</p>
<p>但 <code>p(X_w1 = 1)</code> 與 <code>p(X_w2 = 1)</code>直接相乘卻是 0.1875，</p>
<p>由此可見這兩個在有相依性存在的情況下，</p>
<p>可能會不相等 XD。</p>
<p>但假設今天是擲一枚公正硬幣兩次的話：</p>
<p><code>p(x1=正面)</code> * <code>p(x2=正面)</code> = 0.25</p>
<p><code>p(x1=正面, x2= 正面)</code> = 0.25</p>
<p>因為投擲一枚硬幣兩次是獨立事件，</p>
<p>而在更上面的例子中，</p>
<p><code>p(X_w1)</code>與 <code>p(X_w2)</code>並沒有完全獨立。</p>
<blockquote>
<p>基本上有這個概念就已經夠了，</p>
<p>如果你還是很有興趣可以去翻翻機率論，</p>
<p>我大學時候修過，覺得真的⋯⋯很快樂 ^_^。</p>
</blockquote>
<h2 id="Computing-for-syntagmatic-relation"><a href="#Computing-for-syntagmatic-relation" class="headerlink" title="Computing for syntagmatic relation"></a>Computing for syntagmatic relation</h2><h3 id="Maximum-Likelihood-Estimation"><a href="#Maximum-Likelihood-Estimation" class="headerlink" title="Maximum Likelihood Estimation"></a>Maximum Likelihood Estimation</h3><p>前面對 Mutual information 有了概念以後，</p>
<p>下來就是真的去計算它，</p>
<p>並且利用它來找出 syntagmatic relation 了。</p>
<p>我們要用的方法是 Maximum Likelihood Estimation（最大概似估計）。</p>
<p>這名字聽起來一樣很炫砲，</p>
<p>但它的想法其實超簡單！</p>
<blockquote>
<p>只要不是出現在數理統計裡的話</p>
</blockquote>
<p>舉一個常見的例子：擲硬幣。</p>
<p>擲硬幣可以表示成一個 random variable: <code>x</code>，</p>
<p>假設這個 <code>x</code> 的機率分佈是 <code>p(x)</code>。</p>
<p>但其實我們不知道這個機率是不是公正的，</p>
<p>先進行了一次觀察，</p>
<p>而在這次觀察中擲了一萬次，<del>然後就媽媽手</del></p>
<p>結果發現很剛好的有 5000次正面、5000次反面，</p>
<p>因此觀察後得到了一個 <code>p&#39;(x)</code>，</p>
<p>假設觀察後的 <code>p&#39;(x)</code> 跟真正的 <code>p(x)</code> 分佈一致，</p>
<p>那 <code>p(x)</code> 產生 <code>p&#39;(x)</code> 的「可能性」就是「最大」的。</p>
<p>用「觀察出來的機率分佈」去推論「真正的機率分佈」，</p>
<p>並最大化觀察結果等於真實機率分布的可能性，</p>
<p>這就是「Maximum Likelihood Estimation」的精神啦！</p>
<p>有了上述直覺後，再看看更嚴謹的數學定義，</p>
<p>我們會寫出一個 likelihood function：</p>
<p>$$<br>arg \, max_p p(x) = argmax \prod_i p1(x_i)<br>$$</p>
<p>我們要找可以最大化這個 function 的機率分佈： p。</p>
<blockquote>
<p><code>argmax</code>：</p>
<p>這個符號的意思就是要找出輸入後能夠最大化後方這個算式值的 arguments，</p>
<p>有時候很佩服數學家想得到這麼奇葩的符號表示法 QQ</p>
</blockquote>
<p>再來看最後一個簡單例子，是從<a href="http://ccckmit.wikidot.com/st:maximumlikelihood" target="_blank" rel="external">陳鍾誠老師的網站上引用的</a>。</p>
<p>可以表現如何套用這個公式並且指出 Maximum likelihood estimation 的問題。</p>
<p>假設我們擲了一枚硬幣十次，有六次為正面，四次為反面。（這個擲十次硬幣其實就是一個 random variable: X）</p>
<p>我們看看下面三個機率模型可能產生 X 的機率有多少。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">p1(正) = 0.5 ; p1(反) = 0.5</div><div class="line">p2(正) = 0.2 ; p2(反) = 0.8</div><div class="line">p3(正) = 0.4 ; p3(反) = 0.6</div></pre></td></tr></table></figure>
<p>把上面的機率模型帶進去 likelihood function：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">p1(x)= 0.5^4 ∗ 0.5^6 = 0.00097656</div><div class="line">p2(x)= 0.2^4 ∗ 0.8^6 = 0.00041943</div><div class="line">p3(x)= 0.4^4 ∗ 0.6^6 = 0.00119439</div></pre></td></tr></table></figure>
<p>會發現 <code>p3</code> 這個得到的值最高，</p>
<p>可是對於投硬幣來說，其實 <code>p1</code> 才是更正確的模型才對，</p>
<p>這也就是 MLE(maximum likelihood estimation）的缺點，</p>
<p>如果樣本數太小或是有很嚴重偏誤的話，我們很容易見樹不見林 XD。</p>
<p>總而言之，簡單地去推論 <code>P(X_w1=1)</code>、<code>P(X_w2=1)</code>、<code>P(X_w1=1, X_w2=1)</code>出現的機率：</p>
<p><img src="http://i.imgur.com/j0nTpXS.png" alt="Esi of p"></p>
<blockquote>
<p>為什麼找這三個是因為找出來後，</p>
<p>其他都可以從這三個機率去推導</p>
</blockquote>
<p>我們就從這些觀察值中去假設機率是這樣，</p>
<p>就是用到了前面敘述的「最大概似估計方法」。</p>
<p>不過這樣的做法有個顯而易見的小缺點，</p>
<p>當我們觀察的樣本中，有些字可能從來沒出現過時，</p>
<p>它的機率會被估計成 0，</p>
<p>但我們的樣本可能相對很小，</p>
<p>直接就這樣斷定這個字不可能出現絕非好事。</p>
<p>所以要來介紹一下一個小技巧：<strong>Smoothing</strong></p>
<h3 id="Smoothing"><a href="#Smoothing" class="headerlink" title="Smoothing"></a>Smoothing</h3><p>smoothing 的做法很簡單，</p>
<p>就是對於每個情況發生的次數，</p>
<p>都加上一個小小的 constant。</p>
<p><img src="http://i.imgur.com/SF3lVWQ.png" alt="smoothing"></p>
<p>如此就算我們觀察的樣本中完全沒有出現過某個情況，</p>
<p>這個情況也會有一個小小的次數在，</p>
<p>而不是直接斷定其機率為 0。</p>
<blockquote>
<p>雖然機率為 0 也不代表不可能發生，</p>
<p>但這就不在這篇文章討論範圍內了。</p>
</blockquote>
<h2 id="Summary-of-Syntagmatic-mining-and-Analysis"><a href="#Summary-of-Syntagmatic-mining-and-Analysis" class="headerlink" title="Summary of Syntagmatic mining and Analysis"></a>Summary of Syntagmatic mining and Analysis</h2><p>複習一下三個從訊息論來的概念</p>
<ul>
<li><p>Entropy(<code>H(X)</code>)：量化隨機變數 X 的不確定性</p>
</li>
<li><p>Conditional Entropy(<code>H(X|Y)</code>)：在給定 Y 提件下隨機變數 X 的不確定性</p>
</li>
<li><p>Mutual Information（<code>I(X;Y)</code>）：描述 知道 Y 或 X 其中一個後，會降低多少預測的不確定性</p>
</li>
</ul>
<p>在這階段得到的 word association 是相當 general 的，</p>
<p>不管後續要做什麼應用，</p>
<p>都有辦法跟其他算法結合。</p>
<p>掌握了這些基石後，</p>
<p>就可以來應用在稍微 deep 一點的技巧上了。</p>
<h1 id="Topic-Mining-amp-Analysis"><a href="#Topic-Mining-amp-Analysis" class="headerlink" title="Topic Mining &amp; Analysis"></a>Topic Mining &amp; Analysis</h1><p>前面一個禮拜多有了對詞的基本了解後，</p>
<p>要來做進階一點的分析和挖掘：Topic mining。</p>
<h2 id="What-is-topic"><a href="#What-is-topic" class="headerlink" title="What is topic?"></a>What is topic?</h2><p>topic 其實就是一堆文字中的「主旨」(main idea)。</p>
<p>隨著資料顆粒度不同，會有所改變。</p>
<blockquote>
<p>句子、文章、書籍的 topic 萃取會大大不同</p>
</blockquote>
<h2 id="How-to-discover-topics"><a href="#How-to-discover-topics" class="headerlink" title="How to discover topics"></a>How to discover topics</h2><h3 id="Intuition-1"><a href="#Intuition-1" class="headerlink" title="Intuition"></a>Intuition</h3><p><img src="http://i.imgur.com/oac33PW.png" alt="topic tasks"></p>
<ol>
<li><p>先找到有哪些 topics</p>
</li>
<li><p>將文本資料（document）涵蓋各個 topic 的機率找出來。</p>
</li>
</ol>
<p>有了這個直覺後來更嚴謹的定義一下要做什麼，</p>
<ul>
<li><p>Input:</p>
<ul>
<li><p>text documents 的集合 <code>C={d_1, ..., d_N}</code></p>
</li>
<li><p>Number of topics</p>
</li>
</ul>
</li>
<li><p>Output</p>
<ul>
<li><p>k topics: <code>{theta_1, ..., theta_k}</code></p>
</li>
<li><p>Coverage of topcis in each <code>d_i</code>: <code>{pi_i1, ..., pi_ik}</code></p>
</li>
</ul>
</li>
</ul>
<p>$$<br>j = 1, 2 … k<br>$$</p>
<p>$$<br>i = 1, 2 … N<br>$$</p>
<p>$$<br>\sum \pi_{ij} = 1<br>$$</p>
<p>再來的問題就是怎麼找出 theta 了</p>
<h3 id="Term-as-Topic"><a href="#Term-as-Topic" class="headerlink" title="Term as Topic"></a>Term as Topic</h3><p>最直觀的方法就是從所有文本中，</p>
<p>挑出可以當作 Topic 的「詞」(word = term)。</p>
<ul>
<li><p>Parse 所有的 text 拿到 candidate terms</p>
</li>
<li><p>設計一個 scoring function 來判定各個 candidate term 是不是適合當作 topic</p>
</li>
<li><p>選擇 k 個有最高分的 terms，但盡可能最小化冗餘</p>
<ul>
<li>冗餘的意思有點太抽象，意思就是有幾個 topic 如果都長得很像，比如說「車子」、「汽車」、「車車」，那只要選擇一個當作 topic 就好</li>
</ul>
</li>
</ul>
<p>接著就直接來看看 term as topic 的做法。</p>
<p>最簡單的方式就是直接計算次數，觀察其佔的比例：</p>
<p><img src="http://i.imgur.com/m66yQ2f.png" alt="comp by freq"></p>
<p>簡單的說 <code>pi</code> 就是每個 term 在每個 document(<code>d_i</code>) 中所佔的比率，</p>
<p>而 <code>theta</code> 就是各個 term 了。</p>
<p>最後算出來的 <code>pi_ij</code> 就會是<code>theta_j</code>/(<code>document_i</code>中所有 term 出現的次數)，</p>
<p>其實看的就是選的這個字在某份文件中跟其他 topics（這裡是 terms）所佔的比率，</p>
<p>最高的話，就判定它可能會是屬於 topic。</p>
<p>但是直接拿實際例子來檢驗，</p>
<p>馬上會發現一個大問題：</p>
<p>以下節錄自一則 NBA 球賽的報導：</p>
<blockquote>
<p>Cavaliers vs. Golden State Warriors: NBA playoff finals … basketbal … <code>travel</code> to Cleveland … <code>star</code> …</p>
</blockquote>
<p>$$<br>\theta_1 = “sports”<br>$$</p>
<p>$$<br>\theta_2 = “travel”<br>$$</p>
<p>$$<br>\theta_3 = “science”<br>$$</p>
<p>出現 “sports”的次數為 0，</p>
<p>而出現 “travel” 的次數為 1。</p>
<p>所以這個運動新聞的 topic 在上述方法中反而會被歸類到 sports 去。</p>
<p>很明顯的，不能只看 “Sports” 這個字，</p>
<p>應該要把相關的字也加進來才對。</p>
<p>但如果把 related word 也加進來，</p>
<p>那 <code>star</code> 這個字就會有點 tricky 了，</p>
<p>因為 <code>star</code> 有模糊的空間可以被解釋，</p>
<p>除了表示明星之外，它也可能是指真正的星星，</p>
<p>會與 <code>science</code> 產生聯繫（天文物理學）。</p>
<p>總結一下 term as topic 會遇到的問題</p>
<ul>
<li><p>Lack of expressive power</p>
<ul>
<li>只能找出簡單的 topic，太過複雜就無法（前面都是以單一個詞來切分 topic）</li>
</ul>
</li>
<li><p>Incompleteness in vocabulary coverage</p>
<ul>
<li>對於找出相關的字這件事表現不佳</li>
</ul>
</li>
<li><p>Word sense ambiguity</p>
<ul>
<li>無法處理詞彙間的 ambiguity （最後說到的 <code>star</code> 問題）</li>
</ul>
</li>
</ul>
<h1 id="Probabilistic-Topic-Models"><a href="#Probabilistic-Topic-Models" class="headerlink" title="Probabilistic Topic Models"></a>Probabilistic Topic Models</h1><p>假如 term as topic 行不通就兩手一攤說沒辦法那也太遜，</p>
<p>所以馬上要來優化前面的 topic mining 方法：</p>
<p>回顧一下上面提到 term as topic 會遇到的問題，</p>
<p>以及概念上應該要如何解決：</p>
<ul>
<li><p>Lack of expressive power</p>
<ul>
<li>只能找出簡單的 topic，太過複雜就無法</li>
</ul>
</li>
</ul>
<blockquote>
<p>解決方法： <code>Topic: {Multiple Words}</code></p>
<p>一個字當 topic 不夠，你有試過好多個一起嗎？</p>
</blockquote>
<ul>
<li><p>Incompleteness in vocabulary coverage</p>
<ul>
<li>對於找出相關的字這件事表現不佳</li>
</ul>
</li>
</ul>
<blockquote>
<p>解決方法： 對於 word 加上權重</p>
</blockquote>
<ul>
<li><p>Word sense ambiguity</p>
<ul>
<li>無法處理詞彙間的 ambiguity （最後說到的 <code>star</code> 問題）</li>
</ul>
</li>
</ul>
<blockquote>
<p>解決方法： Split an ambiguous word</p>
</blockquote>
<p>首先要做的事情就是小小的改變一下選取的 term: <code>theta</code>，</p>
<p>它不再是一個個的單詞，</p>
<p>而是一個詞的機率分配，這絕對是概念上的一個大進步，</p>
<p>先記著 <code>theta</code> 代表的是機率分配這件事，</p>
<p>直接看下方這張圖：</p>
<p><img src="http://i.imgur.com/fA4tAEF.png" alt="prob"></p>
<p>舉 “Sports” 為例子，這代表 “Sports”這個分配底下，</p>
<p>裡面會出現詞的機率就是長這個樣子。</p>
<blockquote>
<p>這裡的機率分配已經做過 smoothing 的處理，所以不會有 0</p>
</blockquote>
<p>$$<br>V = set(w_1, w_2, …)<br>$$</p>
<p>這其實就是字典檔，裡面裝滿了各種 words(<code>w</code>)。</p>
<p>而令人好奇的是 <code>p(w | theta)</code>代表的意義是什麼，</p>
<p>舉例子可能會清楚一點，</p>
<p><code>theta_1</code> = topic 為 “Sports” 的機率分配，</p>
<p><code>p(&quot;game&quot; | theta_1)</code>的意思就是在知道屬於 <code>theta_1</code> 的條件下，</p>
<p>“game” 這個字出現的機率。</p>
<p>也因此把每個 topic 當條件下出現的機率加總起來就會是 1。</p>
<p>上面那張圖中也把跟 topic 較不相關的字標成黑色，</p>
<p>可以看到它們在所屬 topic 下出現的機率明顯是較低的。</p>
<p>看一下這種把 <code>theta</code>當分配來看待的做法有沒有解決上述問題：</p>
<ul>
<li>Lack of expressive power</li>
</ul>
<blockquote>
<p>解決方法： 一個 topic 底下已經可以有多個字，這些字組合起來可以變成一個相當複雜的 topic</p>
</blockquote>
<ul>
<li>Incompleteness in vocabulary coverage</li>
</ul>
<blockquote>
<p>解決方法： 現在每個字在所屬 topic 中都有其自己的權重</p>
</blockquote>
<ul>
<li>Word sense ambiguity</li>
</ul>
<blockquote>
<p>解決方法：現在在不同 topic 中出現的同樣字會有不同的機率</p>
</blockquote>
<p>其實我也蠻驚訝只是換個表現的方式，</p>
<p>就能夠帶來這樣的成效，</p>
<p>下面就正式用機率模型的方式來表現 topics：</p>
<p><img src="http://i.imgur.com/Ji9yzux.png" alt="prob model"></p>
<blockquote>
<p>注意：theta 是一個 term 的「分布」</p>
</blockquote>
<p>而 <code>pij</code> 就是該 topic 在這個 <code>document_j</code> 中的「覆蓋率」，</p>
<p>假如 <code>pij</code> 的覆蓋率越高，代表它越可能是屬於 <code>theta_i</code> 這個 topic。</p>
<h2 id="Generative-Model"><a href="#Generative-Model" class="headerlink" title="Generative Model"></a>Generative Model</h2><p>雖然前面已經提到用機率模型的方式來呈現 topics，</p>
<p>但是要被分析的原始文本資料（text data），本身是沒有機率分布的，</p>
<p>所以要自己「生成」一個有機率分佈的 model 給它們，</p>
<p>這也就是我待會要介紹的概念： Generative model。</p>
<p><img src="http://i.imgur.com/f0eu5c1.png" alt="generative model"></p>
<p>概念就是如上圖這個樣子，有以下幾個步驟：</p>
<ul>
<li><p>Modeling of Data Generation: <code>P(Data |Model, lambda)</code></p>
</li>
<li><p>lambda 是所有會產生 text data 的參數：</p>
<ul>
<li><p>包括<code>{theta_1,...theta_k}, {pi_11, ..., pi_1k}... {pi_N1, ... , pi_Nk}</code></p>
</li>
<li><p>要求得的答案是：知道哪些參數後，能夠讓我們在知道這些參數的條件下，讓產生出 <code>Data</code>的機率最大化。</p>
</li>
<li><p>如果是上面圖來說的話，就是 <code>lambda*</code> 這個 parameter</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>上述資料的 lambda 是一維的，只是為了方便圖像化，</p>
<p>事實上的 model 不太可能長這麼簡單 XD</p>
</blockquote>
<h2 id="Statistical-Language-Models-以下都以-LM-簡稱"><a href="#Statistical-Language-Models-以下都以-LM-簡稱" class="headerlink" title="Statistical Language Models(以下都以 LM 簡稱)"></a>Statistical Language Models(以下都以 LM 簡稱)</h2><ul>
<li><p>其實就是一連串字的機率分配</p>
<ul>
<li><p><code>p(&quot;Today is Wednesday&quot;)</code> ~= 0.001</p>
</li>
<li><p><code>p(&quot;Today Wednesday is &quot;)</code> ~= 0.00000000001</p>
</li>
</ul>
</li>
<li><p>上下文相關（ context dependent）</p>
</li>
<li><p>就是一種用機率方法來生成文字的 model，所以也可以稱作是 “Generative model”</p>
<p>介紹完概念，就直接來看有哪些 model 可以用。</p>
</li>
</ul>
<h2 id="Unigram-LM"><a href="#Unigram-LM" class="headerlink" title="Unigram LM"></a>Unigram LM</h2><p>這是一個最簡單的 model，</p>
<p>它假設產生的每個 word 都是相互獨立的。</p>
<blockquote>
<p>假如你學過 naive Bayes 就會發現這比 naive 還要更 naive</p>
</blockquote>
<p>例子：</p>
<p>$$<br>p(“today \, is \, Wed”) = p(“today”)p(“is”)p(“Wed”)<br>$$</p>
<p>再來看關於 Unigram LM 更實際的例子：</p>
<p><img src="http://i.imgur.com/RHhv2lr.png" alt="unigram sampling"></p>
<p>topic 1 是 text mining，</p>
<p>下方的 model 就是已知在這個 topic 的條件下，</p>
<p>各個字出現的機率分配。</p>
<p>從這個分配中去取樣本組成一個 data，</p>
<p>那很自然就會是屬於 text mining 的 document。</p>
<p>(Topic 2 就不再重複敘述)</p>
<p>但反過來從看到 data ，去判定它屬於哪個 topic，</p>
<p>才是我們真正想做的事情。</p>
<p>最直觀的方法就是前面提到的最大概似估計（Mamimum Likelihood Estimation）：</p>
<p><img src="http://i.imgur.com/Rxog1gI.png" alt="estimation of unigram lm"></p>
<p>但最大概似估計有它的限制，</p>
<p>在上面這張圖中的下方是我們去做分析和探勘時，</p>
<p>要一再問自己的兩個問題：</p>
<ul>
<li><p>這就是最好的方法了嗎？</p>
</li>
<li><p>何謂「最好」？</p>
</li>
</ul>
<p>接著繼續探討怎麼去更優化這個估計方式。</p>
<h2 id="Maximum-Likelihood-v-s-Bayesian"><a href="#Maximum-Likelihood-v-s-Bayesian" class="headerlink" title="Maximum Likelihood v.s Bayesian"></a>Maximum Likelihood v.s Bayesian</h2><p>Maximum Likelihood 的問題：</p>
<ul>
<li>樣本數過小時，估計會很不準</li>
</ul>
<blockquote>
<p>舉例：</p>
<p>投擲硬幣兩次都正面，就估計這硬幣出現正面的機率為 1，</p>
<p>可見當觀察的資料過少時，很容易得到有極大偏誤的結果</p>
</blockquote>
<p>在這裡要介紹另一個簡單，但是相當高效的方法：</p>
<p><strong>Bayes Rule</strong>，也就是大家常在說的貝氏定理。</p>
<p>那 Bayes Rule 的核心概念是什麼呢？</p>
<p>直接舉個例子來說明：</p>
<p>假設現在有一個袋子裡面有 5 個球，</p>
<p>其中 4 顆黑球，1 顆白球，</p>
<p>很明顯地，拿出黑球的機率就是 4/5 = 0.8。</p>
<p>注意，這是在「知道所有情況下」才能這樣簡單的就拿到機率，</p>
<p>但是在現實生活的分析中，</p>
<p>常常會不知道所有的情況，</p>
<p>而貝氏機率的哲學就是從結果逆著去推論現實生活中的情況。</p>
<p>舉上述例子就是從袋子裡拿球三次，其中出現一次黑球、兩次白球，</p>
<p>再從這些觀察的結果去推論拿出球顏色的機率分布是什麼，</p>
<p>這就是 Bayes Rule。</p>
<p>這聽起來很像 Maximum likelihood estimation，</p>
<p>不過他們本來就不是相斥的存在，</p>
<p>先耐著性子繼續看下去要怎樣應用它。</p>
<p>假如你不懂條件機率和貝氏定理的話，強烈建議你看一下這篇文章：</p>
<blockquote>
<p><a href="http://mindhacks.cn/2008/09/21/the-magical-bayesian-method/" target="_blank" rel="external">数学之美番外篇：平凡而又神奇的贝叶斯方法</a></p>
<p>看完這篇補充資料前面的例子之後，一定就懂貝氏的概念是什麼了。</p>
<p>這裡不花篇幅去解釋太多，專注在 Bayes 在統計語言模型上的應用</p>
</blockquote>
<p><img src="http://i.imgur.com/OHaWuVi.png" alt="bayes"></p>
<p>從最大化 <code>P( X | theta)</code> 變成最大化<code>P( theta | X)</code> 或是 <code>P(X | theta) * P(theta)</code>，</p>
<blockquote>
<p><code>P( theta| X)</code> 的意思是：</p>
<p>在符合 X 條件下，是屬於 <code>theta</code>這個 topic的機率。</p>
<p>而它也不會跟 <code>P(X | theta) * P(theta)</code>相等，</p>
<p>而是成正比的關係。</p>
</blockquote>
<p>所以關鍵問題就在於如何定義 prior （ <code>p(theta)</code>）。</p>
<p>看完例子後，</p>
<p>我想直接拿課堂簡報中的圖來說明比起直接用最大概似估計，</p>
<p>使用 Bayesian estimation 有什麼樣子的進步：</p>
<p><img src="http://i.imgur.com/NNUJgRL.png" alt="illustration of bayesian"></p>
<p>你會發現最右邊的那個分配就是 MLE 得到的結果，</p>
<p>我們要找的那個是介於 prior 跟 MLE 中間的 posterior mode，</p>
<p>所以這個 estimator 也叫做 MAP(Maximum posteriori estimate)。</p>
<p>除了比直接用 MLE 考慮得更多一些之外，</p>
<p>也更加 general。</p>
<p>前面也有提到貝氏和 MLE 的關係，</p>
<p>這裡其實也有個很直覺得解釋，</p>
<p>那就是如果 <code>P(theta)</code> 是個 uniform 分配（也就是說每個出現的機率都一樣時），</p>
<p>那基本上就等於是沒辦法提供任何訊息，</p>
<p>因此等於就是在求 <code>P(X|theta)</code>，</p>
<p>即原先使用 MLE 的方法。</p>
<h2 id="Mining-One-Topic"><a href="#Mining-One-Topic" class="headerlink" title="Mining One Topic"></a>Mining One Topic</h2><p>接著來運用上述 Bayes rule 的模型，</p>
<p>不過為了專注在概念的解釋上，先用了個簡化的版本，</p>
<p>Mining one topic 的意思是假設只有一個 topic，</p>
<p>所以 input 從原先的: <code>C={d}, V, k</code> ，</p>
<p>變成 <code>C={d}, V</code>（k 固定為 1），</p>
<p>因此也不會有 <code>pi</code> 這個 output，</p>
<p>畢竟在這個例子裡不用去算在每個 document 中的 coverage 。</p>
<blockquote>
<p>只有一個 topic 的話，那代表不管在哪個 d 裡面，</p>
<p>coverage 都會是 100%。</p>
</blockquote>
<p>首先要來定義建立 Language Model 前該有的設定：</p>
<p><img src="http://i.imgur.com/523dHuM.png" alt="language model setup"></p>
<p>比較需要說明的是 Likelihood function，</p>
<p>後續會相當頻繁的遇到這個 function ，</p>
<p>所以理解它背後的含義是相當重要的，更別說它其實是個很直觀的函數 XD</p>
<p>這只是數學符號比較多，但沒有多出什麼新的東西來。</p>
<p>前面有說到我們用的模型是 Unigram LM，</p>
<p>所以假設每個詞出現在 text 中的機率都是相互獨立，</p>
<p>因此才能直接用相乘的來取得。</p>
<p>接著看到 <code>p(x_1 | theta)</code>.. =&gt; <code>p(w_1|theta)^c(w_1, d)...</code> 的轉化，</p>
<p>看起來很嚇人，實際上只是從 random variable 轉化成一般機率的形式而已：</p>
<p><code>x_i</code> 其實是指 <code>w_i</code> 出現在 document: <code>d</code> 中的隨機變數，</p>
<p>是「機率」。</p>
<p>在右上角的 <code>c(w_i, d)</code> 指的是 <code>w_i</code> 真正出現在 data <code>d</code>中的次數，</p>
<p>因為在 Unigram LM 中，每個字出現的機率是相互獨立的，</p>
<p>也就是說同一個字重複出現的機率也是獨立的，</p>
<p>把 <code>p(w_i | theta)</code> 相乘起來就會是這個字出現的機率，</p>
<p>也就成功從 random variable 轉化成一般機率的形式。</p>
<p>弄懂 likelihood 後，</p>
<p>就能直接來找哪些參數 <code>(theta_1,...  theta_M)</code> 可以最大化 <code>p(d| theta)</code>。</p>
<p>$$<br>\prod_{i=1}^M \, \theta_i^{c(w_i, \, d)}<br>$$</p>
<p>為了方便計算，將連乘的部分取對數，</p>
<p>這樣做的好處就是直接化成相加的形式：</p>
<p>$$<br>\sum_{i=1}^M c(w_i, d) log \theta_i<br>$$</p>
<blockquote>
<p>這樣做的意義完全就是為了數學上好算 XD</p>
</blockquote>
<p>記得前面 <code>theta</code> 滿足這個限制後：</p>
<p>$$<br>\sum_{i=1}^M \theta_i = 1<br>$$</p>
<p>再回到原本要解決的問題，</p>
<p>怎麼找到有辦法最大化下面這個函數輸出值的 <code>theta</code> 呢？</p>
<p>$$<br>\sum_{i=1}^M c(w_i, d) log \theta_i<br>$$</p>
<p>答案是—— Lagrange Multiplier Method。</p>
<blockquote>
<p>想瞭解更多關於 Lagrange 的原理可以看這邊</p>
<p> <a href="http://episte.math.ntu.edu.tw/entries/en_lagrange_mul/" target="_blank" rel="external">Lagrange 乘數法</a></p>
<p>我大學最討厭的就是天才少年一號尤拉，以及天才少年二號 Lagrange。</p>
</blockquote>
<p>你可以點上方的參考資料去深入瞭解，</p>
<p>不過你也可以在不知道原理的情況下繼續直接套用公式，</p>
<p>只要懂得簡單的微積分就好 XD</p>
<p>要找參數有辦法使一個凹函數出現最大值，</p>
<p>只要取個微分等於 0，再去解開參數等於多少就可以。</p>
<p>Lagrange 就是將原本的 function 轉化成以下這個形式：</p>
<p>$$<br>\sum_{i=1}^M c(w_i, d) log \theta_i + \lambda( sum \, of \, (\theta_i) - 1)<br>$$</p>
<p>前面有提到：</p>
<p>$$<br>\sum_{i=1}^M \theta_i = 1<br>$$</p>
<p>所以加上 lambda 那一項是不會影響 function 本身的，</p>
<p>但是加上 lambda 之後，我們在微分後可以多做許多事情：</p>
<p><img src="http://i.imgur.com/mHpRT2P.png" alt="cal"></p>
<p>這時候可能你會有個感覺：這只是個數學解題而已嘛！</p>
<p>最後可以得到 <code>theta</code>與 <code>lambda</code> 間的關係，</p>
<p>再度回到上面 theta 加總起來是 1 的等式，</p>
<p>然後把 </p>
<p>$$<br>\theta_i =  - \frac{c(w_i, \, d)}{\lambda}<br>$$</p>
<p>代入</p>
<p>$$<br>\sum_{i=1}^M \theta_i = 1<br>$$</p>
<blockquote>
<p>吃我 der lagrange 喇</p>
</blockquote>
<p>最後再將得到的結果 </p>
<p>$$<br>\lambda = -\sum_{i=1}^N c(w_i, \,d)<br>$$</p>
<p>代入</p>
<p>$$<br>\hat{\theta_i} = \frac{c(w_i,d)}{\lambda}<br>$$</p>
<p><img src="http://i.imgur.com/kHB5jYe.png" alt="cal result"></p>
<blockquote>
<p>上面加了一個小帽子唸作 hat，在統計學裡面這樣標記，</p>
<p>通常表示它是代表「估計」出來的機率，</p>
<p>而非是真正的機率。（真實的機率其實不得而知）</p>
</blockquote>
<p>這個結果相當相當的直覺，</p>
<p>得到的結果其實就是個 normalized count。</p>
<blockquote>
<p>直接拿 word 在 document 中出現的次數除以 document 的總字數。</p>
</blockquote>
<h2 id="Summary-of-one-topic-mining"><a href="#Summary-of-one-topic-mining" class="headerlink" title="Summary of one topic mining"></a>Summary of one topic mining</h2><p>前面敘述的模型有著我們從第一個禮拜就在討論的問題，</p>
<p>就是它沒辦法過濾掉 “the”, “a” 這種每個文章都有的常見字，</p>
<p>這些常見字其實沒有跟 topic 有很高的相關性，</p>
<p>但在 <code>p(w|theta)</code> 時卻會有著不低的機率。</p>
<p><img src="http://i.imgur.com/TonnmLC.png" alt="result"></p>
<p>不過下一個禮拜的課程才會進入要怎麼解決這個問題。</p>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>這一週蠻像以前在學機率論的，不過是簡化版的。</p>
<p>而且相較於以前學習的純理論，到考試再被證明題屌虐一番，</p>
<p>這一次有種 divide and conquer 的感覺，</p>
<p>我們有個很明確的目標和問題要解決，</p>
<p>至少我自己在經過這禮拜課程後，</p>
<p>對於使用統計語言模型以及 topic mining 有了初步的理解，</p>
<p>雖然看到 Lagrange 的時候罵了幾句髒話，</p>
<p>但從基石開始慢慢學起的感覺就是這個樣子，</p>
<p>多了點思考和研究，少了很多很多的浮躁。</p>
<p>也推薦看完後可以去 Coursera 上做做練習題，</p>
<p>看看自己是不是真的懂了。</p>
<p>最後補充一下為什麼有些東西都重複解釋，</p>
<p>其實訊息的冗余對於保存訊息是很有意義的，</p>
<p>當初我們有辦法解密古埃及文，</p>
<p>就是因為羅賽塔石碑上用了三種語言重複了一樣的訊息，</p>
<p>語言學家才能把上面的資訊解密，</p>
<p>這裡的訊息就是對於 text mining 的知識，</p>
<p>我相信這也是相同的道理。</p>
<blockquote>
<p><a href="https://zh.wikipedia.org/wiki/%E7%BE%85%E5%A1%9E%E5%A1%94%E7%9F%B3%E7%A2%91" target="_blank" rel="external">羅賽塔石碑</a></p>
</blockquote>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="https://www.coursera.org/learn/text-mining/home/welcome" target="_blank" rel="external">Coursera: Text Mining and Analytics 來自於 伊利諾伊大學香檳分校</a></p>
</li>
<li><p><a href="http://episte.math.ntu.edu.tw/articles/mm/mm_13_3_01/" target="_blank" rel="external">熵 (Entropy) - 李天岩</a></p>
</li>
<li><p><a href="http://episte.math.ntu.edu.tw/entries/en_lagrange_mul/" target="_blank" rel="external">Lagrange 乘數法</a></p>
</li>
<li><p><a href="http://mindhacks.cn/2008/09/21/the-magical-bayesian-method/" target="_blank" rel="external">数学之美番外篇：平凡而又神奇的贝叶斯方法</a></p>
</li>
<li><p>數學之美：《第 6 章：信息的度量和作用》</p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;這是一篇關於 Coursera 上：&lt;a href=&quot;https://www.coursera.org/learn/text-mining/home/welcome&quot;&gt;Text Mining and Analytics (伊利諾伊大學香檳分校)&lt;/a&gt;的筆記。&lt;/p&gt;
&lt;p&gt;主要在探討 text mining 和 分析，&lt;/p&gt;
&lt;p&gt;經過我整理之後應該會變得好懂很多。&lt;/p&gt;
&lt;p&gt;這是第二個禮拜課程的筆記，&lt;/p&gt;
&lt;p&gt;假如你還沒看過第一個禮拜，&lt;/p&gt;
&lt;p&gt;可以先看這裡：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://abalone0204.github.io/2016/07/15/illinois-text-mining-week-1/&quot;&gt;Text Mining &amp;amp; Analysis： week 1&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
    
    </summary>
    
    
      <category term="textmining" scheme="http://abalone0204.github.com/tags/textmining/"/>
    
      <category term="NLP" scheme="http://abalone0204.github.com/tags/NLP/"/>
    
      <category term="coursera" scheme="http://abalone0204.github.com/tags/coursera/"/>
    
      <category term="topic-mining" scheme="http://abalone0204.github.com/tags/topic-mining/"/>
    
      <category term="PLSA" scheme="http://abalone0204.github.com/tags/PLSA/"/>
    
  </entry>
  
  <entry>
    <title>Text Mining &amp; Analysis： week 1</title>
    <link href="http://abalone0204.github.com/2016/07/15/illinois-text-mining-week-1/"/>
    <id>http://abalone0204.github.com/2016/07/15/illinois-text-mining-week-1/</id>
    <published>2016-07-15T16:20:51.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>最近對於 text mining 的知識頗有有需求，</p>
<p>所以開始上一門 coursera 上的課程，</p>
<p>主要在探討 text mining 和 分析，</p>
<p>會停留在比較 general purpose 的理論和演算法上，</p>
<p>乍看之下其實有點無聊，</p>
<p>但我覺得原因是課堂的教授預設我們有許多預備知識和對數學的靈敏度，</p>
<p>實際上它的內容非常的扎實，而且講解的也很深入，</p>
<p>經過我整理之後應該會變得好懂很多，</p>
<blockquote>
<p>因為我不像那些教授一樣是天才 XDD </p>
<p>大學也沒修過這類型的課程，只是因為興趣所以研究這個。</p>
<p>可能就如同每個在網路上看到這篇文章的人一樣。</p>
</blockquote>
<p>如果是跟我一樣的 NLP 新手，這一系列筆記應該會對你很有幫助，</p>
<p>並且成為你往更深層分析研究的基石。</p>
<a id="more"></a>
<h1 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h1><blockquote>
<p>這裡推薦一下大家去看吳軍教授的「數學之美」，</p>
<p>裡面有提到相當多關於「語言」以及電腦科學在自然語言處理上的介紹。</p>
</blockquote>
<p>語言其實就是承載知識的載體，</p>
<p>仔細想一想我們其實能從大量的文本中整合出各式各樣的主題（topic），</p>
<p>甚至能從中汲取出作者的觀點來，</p>
<p>但是該怎麼做呢？</p>
<p>原本的自然語言處理領域認為，電腦要學會看文字，</p>
<p>應該要跟人類一樣從文法和字母開始學起，</p>
<p>但後來發現地球上有這麼多語言，每種語言又有特殊的文法，</p>
<p>而文法更是會隨著時代改變，</p>
<p>漸漸的，大家發現這條路好像不是這麼行得通。</p>
<blockquote>
<p>更別說有 context dependancy 的語法分析的時間複雜度高達 O(n^6)</p>
</blockquote>
<p>經過數十年在學術上的努力後，</p>
<p>終於發現用統計模型來讓電腦理解語言才是正途，</p>
<p>這也是現在在搜尋引擎中所用的技術之一，</p>
<p>而且無關什麼語言或是什麼樣的句法，</p>
<p>都能夠用統計語言模型的方法來表示。</p>
<blockquote>
<p>我想如果大學教授有跟我提這件事的話，</p>
<p>我現在可能就不會是個寫程式的人，會是個研究統計學的狂熱者了 XD</p>
</blockquote>
<p>這堂課主要就是做初步的去探討怎麼樣把「文本資料」，</p>
<p>轉換成我們能夠做運算的模型，</p>
<p>進而讓電腦理解。</p>
<p>有了這些基礎後，才能更簡單的運用電腦擅於運算的特性，</p>
<p>讓我們更快速的運用這些從文本上挖掘到的知識。</p>
<blockquote>
<p>這是一門專注在 shallow techniques 上面的課，</p>
<p>但內容可一點都不膚淺，後面會再提到何謂 shallow，何謂 deep。</p>
</blockquote>
<h1 id="Overview"><a href="#Overview" class="headerlink" title="Overview"></a>Overview</h1><ul>
<li><p>流程：</p>
<ol>
<li><p>Natural language processing &amp; text representation</p>
</li>
<li><p>Word association mining &amp; analysis</p>
</li>
<li><p>Topic mining &amp; anaylysis</p>
</li>
<li><p>Opinioon mining &amp; sentiment analysis</p>
</li>
<li><p>Text-based prediction</p>
</li>
</ol>
</li>
</ul>
<p>來看一下流程圖：</p>
<p><img src="http://i.imgur.com/jobmiIH.png" alt="flow"></p>
<p>上述的流程中，</p>
<p>你會發現越前面的步驟其實需要越少人工介入，但沒辦法挖掘更深層的資訊，</p>
<p>越趨近於 shallow techniques。（不深嘛）</p>
<p>越後面則是越趨近於 deep techniques。（不淺嘛）</p>
<ul>
<li><p>Shallow techniques ，雖然得到的知識量比較少，但比較 general，不會因為領域不同被侷限，而且通常不需要或只需要相當少的人工介入（這門課裡面講的就是 shallow techniques）。</p>
</li>
<li><p>Deep techniques 需要人工介入，而且有更多局限性，但能獲取到更多的知識。</p>
</li>
<li><p>結合前兩者加上機器學習才能得到 actionable information（知道這些知識後，我們可以採取某些行動或決策）</p>
</li>
</ul>
<p>目前還沒有什麼兩全其美的方法，</p>
<p>在開始文本挖掘之前，建立好這個 trade-off 的概念是相當重要的。</p>
<h1 id="Text-Representation"><a href="#Text-Representation" class="headerlink" title="Text Representation"></a>Text Representation</h1><h2 id="Sequence-of-characters"><a href="#Sequence-of-characters" class="headerlink" title="Sequence of characters"></a>Sequence of characters</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">A dog is chasing a boy on the playground</div></pre></td></tr></table></figure>
<blockquote>
<p>就是一連串的字元組合起來的字串，但對分析並沒有意義，</p>
<p>因為它沒有提供一個電腦能夠解析的結構。</p>
</blockquote>
<h2 id="Sequence-of-words-POS-Part-Of-Speech-tags"><a href="#Sequence-of-words-POS-Part-Of-Speech-tags" class="headerlink" title="Sequence of words + POS(Part-Of-Speech) tags"></a>Sequence of words + POS(Part-Of-Speech) tags</h2><blockquote>
<p>這是這一門課主要探討的範圍，其他可以稍微看看就好 XD</p>
<p>這一層是所有 text mining 的基石，後續的分析和 mining 都能與此有所關連</p>
</blockquote>
<p>為了得到更結構化的資料，我們可以試看看 POS(Part Of Speech) tags，</p>
<p>來為每個詞貼上一個 tag 看看，這個 tag 就是這個詞的詞性：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">A: Det</div><div class="line"></div><div class="line">Dog: N</div><div class="line"></div><div class="line">is: Aux</div><div class="line"></div><div class="line">chasing: Verb</div><div class="line"></div><div class="line">a: Det</div><div class="line"></div><div class="line">boy: N</div><div class="line"></div><div class="line">on: PPrep</div><div class="line"></div><div class="line">the: Det</div><div class="line"></div><div class="line">playground: N</div></pre></td></tr></table></figure>
<p>POS tag 的優劣分析</p>
<ul>
<li><p>Pros:</p>
<ul>
<li><p>word 是人們溝通的基本單位</p>
</li>
<li><p>有了這個結構之後我們能統計每個字出現的次數</p>
</li>
<li><p>能夠被應用到 topic analysis 上</p>
</li>
</ul>
</li>
<li><p>Cons:</p>
<ul>
<li><p>不夠 general，像是中文就不是這樣認字。（中文字和中文字中間不會用空格分開）</p>
</li>
<li><p>解法：中文會需要自己的斷詞（e.q: 結巴）</p>
</li>
</ul>
</li>
</ul>
<h2 id="Syntatic-structures"><a href="#Syntatic-structures" class="headerlink" title="Syntatic structures"></a>Syntatic structures</h2><ul>
<li>一個表示語法的樹狀圖，這裡不會探討太多這部分，將會以統計模型表示語言的方式為主</li>
</ul>
<h2 id="Entities-and-relations"><a href="#Entities-and-relations" class="headerlink" title="Entities and relations"></a>Entities and relations</h2><ul>
<li><p>拆出這個句子裡有哪些「實體」與「關係」</p>
</li>
<li><p>e.q：我吃香蕉</p>
</li>
</ul>
<p>這裡的實體就是<code>我</code>、<code>香蕉</code>，</p>
<p>而我們的關係是 <code>吃</code>與<code>被吃</code>。</p>
<h2 id="Logic-predicates"><a href="#Logic-predicates" class="headerlink" title="Logic predicates"></a>Logic predicates</h2><ul>
<li>寫成 logic predicate：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Dog(d1). Boy(b1). Playground(p1). Chasing(d1, b1, p1)</div></pre></td></tr></table></figure>
<ul>
<li>經由 logic predicates 我們能做到一些更智能的判斷，而且電腦也開始懂我們在說什麼了。</li>
</ul>
<h2 id="Speech-acts"><a href="#Speech-acts" class="headerlink" title="Speech acts"></a>Speech acts</h2><ul>
<li><p>瞭解這句話的「意圖」（intent）是什麼，光用想的就非常困難</p>
</li>
<li><p>e.q：</p>
<ul>
<li>「假的！」這句話在海濤法師出來以前可能真的是指「這個東西不真實」，但現在卻不然</li>
</ul>
</li>
</ul>
<h2 id="Recap"><a href="#Recap" class="headerlink" title="Recap"></a>Recap</h2><ul>
<li><p>越往下是越深層的分析和挖掘</p>
<ul>
<li><p>需要更多人工判斷</p>
</li>
<li><p>精確度其實是降低的</p>
</li>
<li><p>但是也越接近人類知識的表達</p>
</li>
</ul>
</li>
<li><p>繼續研究下去之前我們得了解會有這樣的 trade-off</p>
<ul>
<li><p>所以要想辦法在人的參與和機器學習間做優化</p>
<ul>
<li><p>想想要怎樣讓人工的部分更簡單、省事</p>
</li>
<li><p>利用上述的結果來得到更精確的學習結果、讓人工參與部分減少</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>這堂課主要就是以 shallow techniques 為主，</p>
<p>Shallow techniques 有以下幾個特點：</p>
<ul>
<li><p>General and robust</p>
</li>
<li><p>No/little manual effort</p>
</li>
<li><p>“Surprisingly” powerful</p>
</li>
<li><p>Can be combined with more sophisticated representations</p>
</li>
</ul>
<h1 id="Word-Association-Mining-and-Analysis"><a href="#Word-Association-Mining-and-Analysis" class="headerlink" title="Word Association Mining and Analysis"></a>Word Association Mining and Analysis</h1><p>有了基本的文字探勘概念以後，</p>
<p>要先了解的就是詞和詞之間的關係，</p>
<p>並且把它們用數學的方式來表達。</p>
<h2 id="Outline"><a href="#Outline" class="headerlink" title="Outline"></a>Outline</h2><ul>
<li><p>什麼是 word association</p>
</li>
<li><p>為什麼要挖掘 word association</p>
</li>
<li><p>如何挖掘 word association</p>
</li>
</ul>
<h2 id="什麼是-word-association"><a href="#什麼是-word-association" class="headerlink" title="什麼是 word association"></a>什麼是 word association</h2><p>簡單說就是詞跟詞之間的關係，</p>
<p>有以下兩種：</p>
<ul>
<li><p>Paradigmatic Relation（聚合關係）</p>
<ul>
<li><p><code>A</code>,<code>B</code>兩個詞可以互相替換，那兩者就有 paradigmatic relation</p>
</li>
<li><p>從 similar context 去找: high context similarity =&gt; high paradigmatic relation</p>
</li>
<li><p>e.q: “cat” and “dog”</p>
</li>
</ul>
</li>
<li><p>Syntagmatic Relation（組合關係）</p>
<ul>
<li><p><code>A</code>,<code>B</code>兩個詞可以互相結合，那兩者就有 Syntagmatic relation</p>
</li>
<li><p>從 correlated occurence 去找: high co-occurences but relatively low individual occurences =&gt; high syntagmatic relation</p>
</li>
<li><p>e.q: “cat” nad “sit”, “car” and “drive”</p>
</li>
</ul>
</li>
</ul>
<h2 id="為什麼要挖掘-word-association"><a href="#為什麼要挖掘-word-association" class="headerlink" title="為什麼要挖掘 word association"></a>為什麼要挖掘 word association</h2><p>才能了解各個 document 間的關係，</p>
<p>容易去做 topic analysis，</p>
<p>要做更深層的分析前都得先做這一步。</p>
<h2 id="挖掘-Paradigmatic-Relation（聚合關係）"><a href="#挖掘-Paradigmatic-Relation（聚合關係）" class="headerlink" title="挖掘 Paradigmatic Relation（聚合關係）"></a>挖掘 Paradigmatic Relation（聚合關係）</h2><p>前面我們稍微理解了 Paradigmatic 以及 Syntagmatic 兩者的定義，</p>
<p>現在要來更深入的了解 Paradigmatic Relation。</p>
<p>首先要了解的概念是 Pseudo document，</p>
<p>讓我們用不同的方式來理解 context（上下文）。</p>
<p>Pseudo document，其實就是各式各樣的 bag of words，</p>
<p>裡面裝著各種「字」。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">cat: </div><div class="line">  My ___ eats fish on Saturday.</div><div class="line">  My ___ eats turkey on Sunday.</div></pre></td></tr></table></figure>
<p>Pseudo document 的表示方式就是像下面敘述的這樣：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">Left1(&quot;cat&quot;) = &#123;&quot;my&quot;, &quot;his&quot;, &quot;big&quot;, &quot;a&quot;, &quot;the&quot;,...&#125;</div><div class="line"></div><div class="line">Right1(&quot;cat&quot;) = &#123;&quot;eats&quot;, &quot;ate&quot;, &quot;is&quot;, &quot;has&quot;, ....&#125;</div><div class="line"></div><div class="line">Window10(&quot;cat&quot;) = &#123;&quot;my&quot;, &quot;his&quot;, &quot;big&quot;, &quot;eats&quot;, &quot;fish&quot;, &quot;Saturday&quot;, &quot;Sunday&quot;...&#125;</div></pre></td></tr></table></figure>
<p>第一項 <code>Left1(&quot;cat&quot;)</code> 就是 cat 左邊的一個字能放什麼，</p>
<p><code>Right1</code> 則依此類推，</p>
<p>甚至我們也可以用 <code>Window10(&quot;cat&quot;)</code>來表示 10 個字裡面出現 cat 的 pseudo document，</p>
<blockquote>
<p>沒錯，window 10 </p>
</blockquote>
<p>所以 pseudo document 裡的字，</p>
<p>跟我們的目標字（這裡是 cat）相鄰或不相鄰都是可以的。</p>
<p>有了這些裝在袋子裡的字，我們就有了更堅實的基礎去比較 context 間的相似度。</p>
<p>以下用 Sim 這個 function 來表示 “Cat” 跟 “Dog” 的 context 相似度：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">Sim(&quot;cat&quot;, &quot;dog&quot;) =</div><div class="line">  Sim(Left1(&quot;cat&quot;), Left1(&quot;dog&quot;))</div><div class="line">    + Sim(Right1(&quot;cat&quot;), Right1(&quot;dog&quot;)) +</div><div class="line">    ...</div><div class="line">    + Sim(Window8(&quot;cat&quot;), Window8(&quot;dog&quot;))</div></pre></td></tr></table></figure>
<p>context 有著越高的相似度，代表 “cat” 跟 “dog” 兩個字越有聚合關係。</p>
<blockquote>
<p>這裡並不是說一定要全部都算進去，我們也可以拿其中幾個袋子就好</p>
</blockquote>
<p>而要選擇用哪些袋子來分析相似度，更是大大影響了我們分析的結果，</p>
<p>假如我們使用的是 <code>Window10(&quot;cat&quot;)</code>，這個相對較寬鬆的條件，</p>
<p>我們得到的是更 general 的訊息，可能能有更廣泛的應用；</p>
<p>假如我們使用的是 <code>Left1(&quot;cat&quot;)</code> 這樣的 context 時，</p>
<p>只會知道 “cat” 左邊會出現什麼詞</p>
<p>得到的可能會是更趨近語法分析上的訊息，相較更侷限一些。</p>
<h3 id="Vector-space-model"><a href="#Vector-space-model" class="headerlink" title="Vector space model"></a>Vector space model</h3><p><img src="http://i.imgur.com/7Pw5kex.png" alt="vsm"></p>
<p>數學的美妙在於能把複雜的東西簡單化，</p>
<p>這裡我們很驚訝地發現能夠用 vector space 的方式來表現 context similarity</p>
<p>但問題來了，我們要怎樣去計算 <code>d1</code> 跟 <code>d2</code> 這兩個向量呢？</p>
<h3 id="Expected-Overlap-of-Words-in-Context-EOWC"><a href="#Expected-Overlap-of-Words-in-Context-EOWC" class="headerlink" title="Expected Overlap of Words in Context (EOWC)"></a>Expected Overlap of Words in Context (EOWC)</h3><p>其中一個相當直觀的方法是 Expected Overlap of Words in Context (EOWC)</p>
<blockquote>
<p>我實在不會把這個翻譯成中文 XD，以下簡稱它為 EOWC，</p>
<p>名字中有著 expected，假如你還記得高三的統計學，</p>
<p>就可以猜的到它可能隱含著期望值的概念在裡面</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">c(w_i ,d1) = Count of word w_i in d1</div><div class="line"></div><div class="line">|d1| = Total counts of words in d1 (d2 的部分就不重複了)</div></pre></td></tr></table></figure>
<p>$$<br>d1=(x_1, …x_N), \quad x_i = \frac{c(w_i ,d1)}{|d1|}<br>$$</p>
<p>$$<br>d2=(y_1, …y_N), \quad y_i = \frac{c(w_i ,d2)}{|d2|}<br>$$</p>
<p>$$<br>sim(d1,d2) = d1.d2 = \sum_{i=1}^{N}(x_i \times y_i)<br>$$</p>
<p>x_i 會是每個字(w_i)在各自的 pseudo document 裡面出的次數（count），</p>
<p>再去除以 document 裡面的總次數。</p>
<p>我們得到的值就會是 w_i 這個字，出現在這個 pseudo document 中的頻率。</p>
<blockquote>
<p>這是個 normalize 過的數值，所以將 x_1 加到 x_N 會是 1</p>
</blockquote>
<p>兩個向量的 dot product 就會是 similarity。</p>
<blockquote>
<p>dot product 的算法是這樣子， a = (1,2,1), b = (3, 3, 3)</p>
<p>a.b = 1<em>3+2</em>3+1*3 = 12</p>
</blockquote>
<p>聽起來是蠻直觀的，</p>
<p>這代表兩個 document 中出現的詞相同頻率越高，</p>
<p>兩個 context 就越相近。</p>
<p>儘管 EOWC 給了我們對相似度相當直觀的感受，</p>
<p>還是要小心這裡面有兩個問題：</p>
<ul>
<li><p>假如有其中一個詞的頻率在各個 document 出現次數超級高，那就會判定這兩個 context 有很高的相似度，就算其他詞重複頻率都很低也是一樣，這可能不會是我們想要的結果。 </p>
<ul>
<li>舉個很簡單的例子，假設藍綠兩派支持者互相叫囂，內文可能充斥著大量個幹幹幹幹，但彼此針對其攻擊對象的角度可能會很不同，但因為幹出現的頻率實在太高，所以 EOWC 會判定這兩個 context 有著高相似度。</li>
</ul>
</li>
<li><p>對所有字都一視同仁。</p>
<ul>
<li>舉例來說 “the” 跟 “cat”， “cat”能帶給我們的資訊會比 “the” 來的多，但他們的權重卻是一樣的。</li>
</ul>
</li>
<li><p>鑑於以上原因，我們再來看看有沒有什麼更好的方法。</p>
</li>
</ul>
<h3 id="Improving-EOWC-with-Retrieval-Heuristics"><a href="#Improving-EOWC-with-Retrieval-Heuristics" class="headerlink" title="Improving EOWC with Retrieval Heuristics"></a>Improving EOWC with Retrieval Heuristics</h3><p>兩個問題的解法：</p>
<ul>
<li><p>It favors matching one frequent term very well over matching more distinct terms.</p>
<ul>
<li>Sublinear transformation of Term Frequency (TF)</li>
</ul>
</li>
<li><p>It treats every word equally (overlap on “the” isn’t as<br>so meaningful as overlap on “eats”).</p>
<ul>
<li>Reward matching a rare word: IDF term weighting</li>
</ul>
</li>
</ul>
<p>先來看怎麼解決單一個詞擁有超高重複次數的問題，</p>
<p>TF transformation 其實就是把原本對應到的次數，轉換成另一個更合理的次數而已。</p>
<p>舉例來說：</p>
<p>我們可以把超過 1 的都 mapping 到 1 去， 0 的就是 0。</p>
<p>光用想的都知道上面這一個會丟失掉許多資料給我們的訊息，</p>
<p>所以接下來我們找到一個更合理的方式來做 TF transformation ，</p>
<p>叫做： BM25 Transformation。</p>
<blockquote>
<p>小小科普一下，雖然 tf-idf 應該是大一就會的東西 XD</p>
<p>BM25 通常指的是 Okapi BM25，是一個搜尋引擎中的 ranking function，</p>
<p>BM 指的是 best match，它是由 BM11 以及 BM15 結合起來的，</p>
<p>不過起始點由 0 移至 1，所以從 26 變成了 25，</p>
<p>這就是 BM25 的由來。</p>
<p>還想更瞭解 BM11 和 BM15 的話可以看下方的補充資料：</p>
<p><a href="http://xapian.org/docs/bm25.html" target="_blank" rel="external">The BM25 Weighting Scheme</a></p>
</blockquote>
<p>假設輸入為 x，輸出為 y：</p>
<p>$$<br>y = BM25(x)<br>$$</p>
<p>更進一步看 BM25 這個算法的話：</p>
<p>$$<br>y = \frac{(k+1)x}{x+k}<br>$$</p>
<p>k 是我們可以自訂的數字，</p>
<p>可以簡單的看出來這個 y 最多無法超過 k+1，</p>
<p>如此便有效的將太多次數的詞都降到 k+1 了，</p>
<p>那問題就來了，k 要訂多少才合理呢？</p>
<p>暫且擱置這個問題，先來看原本 EOWC 的第二個問題：</p>
<blockquote>
<p>It treats every word equally (overlap on “the” isn’t as<br>so meaningful as overlap on “eats”).</p>
</blockquote>
<p>太常在所有文章中都出現的字，它的重要性應該要降低，</p>
<p>而鮮少出現的字應該要被提高，我們用的方法則是 IDF。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">W 是我們要分析的詞</div><div class="line">M 為 documents 的總數</div><div class="line">k 為 W 出現在 documents 中的次數</div></pre></td></tr></table></figure>
<blockquote>
<p>舉個小例子：</p>
<p>假設全部有 A, B, C 三個 documents，</p>
<p>而 W 出現在 A, B 兩個 documents，</p>
</blockquote>
<p>情況會是 ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">W = W</div><div class="line">M = 3</div><div class="line">k = 2</div></pre></td></tr></table></figure>
<p>再來看 IDF 的公式：</p>
<p>$$<br>IDF(W) = log(\frac{M+1}{k})<br>$$</p>
<blockquote>
<p>IDf = Inverse Document Frequency</p>
<p>原本是 字在所有 document 中出現的次數/ document 的總數</p>
<p>IDF 是將其反過來看，所以稱為 inverse document frequency</p>
</blockquote>
<p>可以看到，當 k 越大時， IDF 就會越小，</p>
<p>當 k 到達最大值（M），代表每個 document 都有出現 W ，</p>
<p>IDF(W)會趨近於零，讓 “the” “的” 這種每個 document 都可能會出現的字權重降低，</p>
<p>對於第二個問題而言，是一個相當簡單卻有效的方法。</p>
<p>最後，我們要將這兩個方法加進我們的 EOWC 中來優化它。</p>
<p>一口氣看這些公式會有點嚇人，</p>
<p>我偏好一步一步來理解它。</p>
<p>首先要來定義幾個符號：</p>
<p>$$d1=(x_1, …x_N)$$</p>
<blockquote>
<p>d1 就是 pseudo document，</p>
<p>裡面的 x 是一個個的 word</p>
</blockquote>
<p>$$b \in [0,1]$$</p>
<p>$$k \in [0,+\infty)$$</p>
<p>$$|d1| = length\,of\,d1$$</p>
<p>有了上述的定義後，先不要去深究他們有什麼意義，</p>
<p>因為要放在下面這個公式中，他們的定義才有用：</p>
<p>$$<br>BM25(w_i, d1) = \frac{(k+1)c(w_i, d1)}{c(w_i,d1)+k(1-b+b\times\frac{|d1|}{average(|d|)})}<br>$$</p>
<p>看似好像多了很多奇怪的符號，</p>
<p>但只要把上面那個 BM25 拿來對照一下：</p>
<p>$$<br>y = BM25() = \frac{(k+1)x}{x+k}<br>$$</p>
<p>就會發現其實它只是把 <code>c(w_i, d1)</code> 帶入 <code>x</code> 中，</p>
<p><code>k</code> 仍然是拿來控制整個 tf 轉換過後的上界；</p>
<p>你唯一需要注意的新東西是 <code>b</code>，</p>
<p>$$<br>k(1-b+b\times\frac{|d1|}{average(|d|)})<br>$$</p>
<p><code>average(|d|)</code>是為了 normalize 過長的 document，</p>
<p>我們希望不要因為不同長度的 document ，</p>
<p>得到差異過大的結果，</p>
<p>我的經驗是理解到他在做 normalize 之後，</p>
<p>就不要在糾結在上面太多，</p>
<p>就像很多時候我們取 log 就是真的讓圖比較平滑或好看而已（或者是在輸入是 1 的時候能得到 0 值）。</p>
<p>再來就看我們怎麼對 doument 裡面的每個 word 做 normalize 以及轉化：</p>
<p>$$<br>SUM =\sum^{N}_{j=1}(BM25(w_j, d1))<br>$$</p>
<p>$$<br>x_i = \frac{BM25(w_i, d1)}{SUM}<br>$$</p>
<p>$$<br>\sum^{N}_{i=1}x_i = 1<br>$$</p>
<p>分母是每個字的得分，分子則是該字的得分，</p>
<p>這樣做的好處是相加起來會等於 1，</p>
<p>裡面隱含著就是機率模型的概念。</p>
<blockquote>
<p>d2 的話就把 x 代換成 y，這裡不再重複寫一次</p>
</blockquote>
<p>最後就可以來算 similarity 了：</p>
<p>$$<br>sim(d1,d2) = \sum_{i=1}^{N}(IDF(w_i) \times x_i \times y_i)<br>$$</p>
<p>新的算法中在一定程度上矯正了前面敘述到的兩個問題:</p>
<ul>
<li><p>tf =&gt; 將在單一個 doucment 中重複次數過高的字給 normalize</p>
</li>
<li><p>idf =&gt; 將在每個 document 中都出現的字的權重給降低</p>
</li>
</ul>
<p>因為算是中的三個元素都介於 0 到 1，</p>
<p>所以結果也會落在 0 跟 1 之間。</p>
<h3 id="One-more-thing-Syntagmatic-Relations-optional"><a href="#One-more-thing-Syntagmatic-Relations-optional" class="headerlink" title="One more thing: Syntagmatic Relations(optional)"></a>One more thing: Syntagmatic Relations(optional)</h3><p>這一小節會更加的抽象一點，最後來看個有趣的小知識，</p>
<p>BM25 其實也能應用在 syntagmatic relation 上面，</p>
<p>前面有說到組合關係能夠從 correlated occurence 去找：</p>
<p>$$<br>IDF-weighted \quad d_1=(x_1 \times IDF(w_1), …, x_N \times IDF(w_N))<br>$$</p>
<p>原本的 x_i 只能表現他在同一個 docoument 裡面出現的頻率有多高，</p>
<p>（這裡是指經過 normalized BM25  transformation 的值）</p>
<p>但是我們不能說這個 x_i 與其對應的 w_i 是相關的（correlated），</p>
<p>因為有許多 common words（e.q: “the”, “的”) 也被包含在裡面，</p>
<p>但是我們前面有學過 idf 這個轉換法，</p>
<p>假如我們對每個 <code>x_i</code> 去乘上對應的 <code>idf(w_i)</code>，</p>
<p>就能得到去掉常用出現的字之後，真正與 w_i 相關的值了。</p>
<p>我第一時間看到這裡有點疑惑， </p>
<p>Syntagmatic relation 不是從 word 同時出現的機率去挖掘的嗎？</p>
<p>假設我們要看 a 出現的話，b 同時出現的機率是多少，</p>
<p>其實我們得到每個 word 在每個 document 中出現的機率後，</p>
<p>就能算出在 a 字出現的條件下，b 也同時有出現的機率了，</p>
<p>就只是要算個條件機率而已 XD，相當的直觀！</p>
<blockquote>
<p>這裡也只是我自己的推論，有錯的話也請不吝告知了</p>
</blockquote>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>總計六個禮拜的課程，目前是第一個禮拜。</p>
<p>其實寫筆記想要寫到其他人看得懂比上課來的吃力一些，</p>
<p>但同時帶給我的好處就是更深入了解自己所研究的內容，</p>
<p>雖然 tf-idf 是這樣簡單的東西，</p>
<p>但實際上了解它背後的概念，會發現它能運用的場合非常的廣泛。</p>
<p>Text mining 並不是一門太空人般的學問，</p>
<p>畢竟我們生活離不開文字的溝通、訊息的傳遞，</p>
<p>當你有能力去知識的載體上挖更多知識時，</p>
<p>何樂而不為呢？</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="http://xapian.org/docs/bm25.html" target="_blank" rel="external">The BM25 Weighting Scheme</a></p>
</li>
<li><p>數學之美 - 吳軍</p>
</li>
<li><p><a href="https://www.coursera.org/learn/text-mining/home/welcome" target="_blank" rel="external">Coursera: Text Mining and Analytics 來自於 伊利諾伊大學香檳分校</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;最近對於 text mining 的知識頗有有需求，&lt;/p&gt;
&lt;p&gt;所以開始上一門 coursera 上的課程，&lt;/p&gt;
&lt;p&gt;主要在探討 text mining 和 分析，&lt;/p&gt;
&lt;p&gt;會停留在比較 general purpose 的理論和演算法上，&lt;/p&gt;
&lt;p&gt;乍看之下其實有點無聊，&lt;/p&gt;
&lt;p&gt;但我覺得原因是課堂的教授預設我們有許多預備知識和對數學的靈敏度，&lt;/p&gt;
&lt;p&gt;實際上它的內容非常的扎實，而且講解的也很深入，&lt;/p&gt;
&lt;p&gt;經過我整理之後應該會變得好懂很多，&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;因為我不像那些教授一樣是天才 XDD &lt;/p&gt;
&lt;p&gt;大學也沒修過這類型的課程，只是因為興趣所以研究這個。&lt;/p&gt;
&lt;p&gt;可能就如同每個在網路上看到這篇文章的人一樣。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;如果是跟我一樣的 NLP 新手，這一系列筆記應該會對你很有幫助，&lt;/p&gt;
&lt;p&gt;並且成為你往更深層分析研究的基石。&lt;/p&gt;
    
    </summary>
    
    
      <category term="textmining" scheme="http://abalone0204.github.com/tags/textmining/"/>
    
      <category term="NLP" scheme="http://abalone0204.github.com/tags/NLP/"/>
    
      <category term="coursera" scheme="http://abalone0204.github.com/tags/coursera/"/>
    
      <category term="tf-idf" scheme="http://abalone0204.github.com/tags/tf-idf/"/>
    
  </entry>
  
  <entry>
    <title>淺入淺出 eslint 與實作</title>
    <link href="http://abalone0204.github.com/2016/07/11/eslint-fxcking-setup/"/>
    <id>http://abalone0204.github.com/2016/07/11/eslint-fxcking-setup/</id>
    <published>2016-07-11T11:47:04.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>相信團隊為了提升程式碼的品質，</p>
<p>第一步通常會是制定 style guide，</p>
<p>但 style guide 越定越複雜後，要靠人工去檢查就顯得有點不切實際。</p>
<p>這時候就需要靠程式自動來做語法上的檢查及 highlight，</p>
<blockquote>
<p>更殘酷一點可以讓不符合 coding style 的 code 無法被 commit</p>
</blockquote>
<p>這就是 linter 的功用。</p>
<p>而這篇會以我最近在實務上以 eslint + webpack + githook 來做舉例。</p>
<p>我知道網路上有許多充滿獨到經驗的 javascript linter，最有名應該就是 airbnb 的），</p>
<p>直接拿來用當然也 ok，不過，我們固然要學工具，</p>
<p>工具背後的想法才是我們更該了解的。</p>
<p>這一篇並不是什麼懶人教學，複製貼上就能用的 eslint extends，</p>
<p>而是一步一步地去理解 eslint 到底能做到什麼事情，</p>
<p>也許你看完以後還是會選擇直接使用 airbnb 或是其他人寫好的 linter，</p>
<p>但這時候的你，</p>
<p>已經完全有能力參考前人經驗並制定出一套符合你們團隊需求的 linter，</p>
<p>甚至去看他們的設定時，能夠對他們為什麼這樣做更有想法。</p>
<p>希望你看完之後，學會的並不是 eslint 這個工具而已，</p>
<p>而是未來你要做類似東西時內心已經有一個架構在。</p>
<p>雖然站在巨人肩膀上能夠看的更遠，</p>
<p>但能夠自己造出一個鋼彈再站上去，那他媽完全是不一樣帥氣的事情。</p>
<a id="more"></a>
<h1 id="Catalogue"><a href="#Catalogue" class="headerlink" title="Catalogue"></a>Catalogue</h1><ul>
<li><p><a href="#為什麼之前不用-linter？">為什麼之前不用 linter？</a></p>
</li>
<li><p><a href="#Intro-amp-Philosophy">Intro &amp; Philosophy</a></p>
</li>
<li><p><a href="#Configuration-of-ESLint">Configuration of ESLint</a></p>
<ul>
<li><p><a href="#What-can-I-configure">What can I configure?</a></p>
</li>
<li><p><a href="#Parser-Options-amp-Parser">Parser Options &amp; Parser</a></p>
</li>
<li><p><a href="#Environments">Environments</a></p>
</li>
<li><p><a href="#Globals">Globals</a></p>
</li>
<li><p><a href="#Plugins">Plugins</a></p>
</li>
<li><p><a href="#Rules">Rules</a></p>
</li>
<li><p><a href="#Extends">Extends</a></p>
</li>
<li><p><a href="#Others">Others</a></p>
</li>
</ul>
</li>
<li><p><a href="#Practical-Usage">Practical Usage</a></p>
<ul>
<li><p><a href="#Integration-with-webpack">Integration with webpack</a></p>
</li>
<li><p><a href="#Integration-with-git-hooks">Integration with git hooks</a></p>
</li>
<li><p><a href="#Other-solution">Other solution</a></p>
</li>
</ul>
</li>
<li><p><a href="#Conclusion">Conclusion</a></p>
</li>
</ul>
<hr>
<h1 id="為什麼之前不用-linter？"><a href="#為什麼之前不用-linter？" class="headerlink" title="為什麼之前不用 linter？"></a>為什麼之前不用 linter？</h1><p>我得承認在寫這篇文章前，</p>
<p>我並沒有使用 linter 的習慣，</p>
<p>因為說真的，在專案長到一定大小前，</p>
<p>linter 更像是 nice to have 而不是 must have 的東西，</p>
<p>儘管我們知道越早用它越好⋯⋯</p>
<p>大家可能在國文課本都看過方孝儒的指喻，</p>
<p>其實髒髒的 code 這件事就像指喻一樣「始以為不足治，而終至於不可為。」。</p>
<p><img src="http://i.imgur.com/yTf6igd.jpg" alt="finter"></p>
<p>之前不去使用 <code>eslint</code> 的藉口都是沒空仔細研究，</p>
<p>的確，現實生活中的時程可能不允許你直接花大把時間在 linter 上，</p>
<p>所以這篇文章是從幾個禮拜的零碎時間中擠出來的。</p>
<h1 id="Intro-amp-Philosophy"><a href="#Intro-amp-Philosophy" class="headerlink" title="Intro &amp; Philosophy"></a>Intro &amp; Philosophy</h1><p>首先要理解的是：linter 做的事情其實是「靜態的語法分析」。</p>
<p>這意味著我們不需要去執行 script，就能標記出不符合 coding styles 的地方。</p>
<p>另外，</p>
<p><code>eslint</code>的所有規則(rule)都是 <code>pluggable</code> 的，</p>
<p>沒有什麼東西是「太重要」而不能把它關掉，</p>
<p>包括你去下載別人的 eslint 設定，</p>
<p>你也可以把不適合你團隊的 rule 給關掉。</p>
<p>最後，</p>
<p><code>eslint</code> 的 rules 是 “agenda free”，</p>
<p>官方並沒有提倡哪種 coding style 是好的，</p>
<p>你想怎麼樣組合你的 rules 就怎麼樣做。</p>
<h1 id="Configuration-of-ESLint"><a href="#Configuration-of-ESLint" class="headerlink" title="Configuration of ESLint"></a>Configuration of ESLint</h1><h2 id="What-can-I-configure"><a href="#What-can-I-configure" class="headerlink" title="What can I configure?"></a>What can I configure?</h2><p>官方文件中有介紹許多種 config 的方式，</p>
<p>可以從 command line、package.json 裡面設定，</p>
<p>但其實最常看到的還是從 <code>.eslintrc</code>去設定，</p>
<p>所以這篇也會以 <code>.eslintrc</code>，並且以 json 格式為主。</p>
<p>在寫 config 之前，你要先了解你可以對什麼東西設定 config，</p>
<p>其實只有 3 + 1 個東西而已：</p>
<ul>
<li><p><strong>Environments</strong></p>
<ul>
<li>設定環境，不同的環境中會有不同的全域變數（global variable），eslint 中有提供各種不一樣的 enviroments，很少需要自己寫一個。</li>
</ul>
</li>
<li><p><strong>Globals</strong> </p>
<ul>
<li><p>前面有提到過，linter 做的是「靜態」的語法分析，所以它對你程式的運行環境是一無所知的，你必須自己把一些全域變數給加上去。</p>
</li>
<li><p>e.q: 開發 chrome extension 時，你要 call chrome 的 API 必須從 <code>chrome</code> 這個 global variable。</p>
</li>
</ul>
</li>
<li><p><strong>Rules</strong></p>
<ul>
<li>規則 XD 就是你 style guide 的規定，除了指定哪些規範要遵守之外，你也可以去決定違反的 error level。</li>
</ul>
</li>
</ul>
<blockquote>
<p>有點像是違反這條規則的嚴重程度，</p>
<p>有些比較輕微的你可以設定噴 warning 嚇嚇他就好，</p>
<p>但有一些你覺得寫出這些 code 來真是天理難容，你可以直接拿 error 噴死他。</p>
</blockquote>
<ul>
<li><p><strong>Parser</strong></p>
<ul>
<li><p>這裡我把它放在多出來的 1，因為我們通常指定完 parser 之後就不會再其上面更改太多設定，甚至根本不需要指定 XD</p>
</li>
<li><p>的確，你有可能這輩子都不會寫 parser，但我相信探究技術的本質是一個技術人該有的初心，軟體工程師對於知識不該有太浮躁的心 ：）</p>
</li>
<li><p>總之知其然而知其所以然是相當重要的，不管你有沒有修過編譯器（compiler），接下來會馬上科普地介紹 parser 是什麼，以及我們知道這些之後可以做什麼</p>
</li>
</ul>
</li>
</ul>
<h2 id="Parser-Options-amp-Parser"><a href="#Parser-Options-amp-Parser" class="headerlink" title="Parser Options &amp; Parser"></a>Parser Options &amp; Parser</h2><p>這一小節會解釋如果你要啟用 jsx, es6 或 es7 語法你該做些什麼。</p>
<p>但要先解釋一下 Parser 是什麼？</p>
<blockquote>
<p>如果你已經知道 Parser 在做什麼，</p>
<p>可以直接跳過分隔線中間的這一小段科普文</p>
</blockquote>
<hr>
<p>我們都知道電腦看不懂我們寫的 code：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = <span class="number">1</span> + <span class="number">2</span></div></pre></td></tr></table></figure>
<p>Parser 會把我們的程式碼 parse 成 AST(Abstract Syntax Tree)，</p>
<p>讓我們的程式碼能夠簡單的去操作這個 tree，</p>
<p>最後才會編譯成 binary 的形式。</p>
<p>延續上面的例子，</p>
<p>這段程式碼經過 Espree 這個 parser，「最終」可能會變成：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    type: <span class="string">'VariableDeclarator'</span>,</div><div class="line">    id: &#123;</div><div class="line">        type: <span class="string">'Identifier'</span>,</div><div class="line">        name: <span class="string">'a'</span></div><div class="line">    &#125;,</div><div class="line">    init: &#123;</div><div class="line">        type: <span class="string">'BinaryExpression'</span>,</div><div class="line">        left: &#123;</div><div class="line">            type: <span class="string">'Literal'</span>,</div><div class="line">            value: <span class="number">1</span>,</div><div class="line">        &#125;,</div><div class="line">        operator: <span class="string">'+'</span>,</div><div class="line">        right: &#123;</div><div class="line">            type: <span class="string">'Literal'</span>,</div><div class="line">            value: <span class="number">2</span>,</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>為了簡單一點，我把它在檔案的位置標記給移掉了，</p>
</blockquote>
<p>但整體而言你可以感受一下，比起直接操作純文字，</p>
<p>轉成 AST 後能用更結構化的方式來取用程式碼。</p>
<p>科普就到此為止了，</p>
<p>想對 Parser 有更深入了解，可以參考一下我之前寫的筆記：</p>
<ul>
<li><a href="http://abalone0204.github.io/2016/04/25/Super-tiny-compiler/" target="_blank" rel="external">Super tiny compiler</a></li>
</ul>
<p>下面參考文章部分也有放一些我當初學習時讀的文章。</p>
<p>一言以蔽之， </p>
<p><strong> Parser 就是將我們對語法的理解給「程式化」成一個樹狀的結構。</strong></p>
<hr>
<p>前面有說過， Parser 會將純文本的 code 轉成 AST，</p>
<p><code>eslint</code> 中的 parser 只有預設支援 es5 語法，</p>
<p>所以其他額外的語法：es6, es7, jsx，都必須要另外設定。</p>
<blockquote>
<p>Note: </p>
<p><strong>支援 jsx 的 parser 不代表支援 React 的語法。</strong></p>
<p>如果你想要直接使用 React 語法的話可以安裝 <code>eslint-plugin-react</code></p>
</blockquote>
<p>接著就直接來看要怎樣設置 Parser 的 options，</p>
<p>在 <code>.eslintrc.json</code>中的 <code>parserOptions</code>去設置：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="attr">"parserOptions"</span>: &#123;</div><div class="line">    <span class="attr">"ecmaVersion"</span>: <span class="number">6</span>,</div><div class="line">    <span class="attr">"sourceType"</span>: <span class="string">"module"</span>,</div><div class="line">    <span class="attr">"ecmaFeatures"</span>: &#123;</div><div class="line">      <span class="attr">"jsx"</span>: <span class="literal">true</span>,</div><div class="line">      <span class="attr">"impliedStrict"</span>: <span class="literal">true</span></div><div class="line">    &#125;</div><div class="line">  &#125;,</div><div class="line">  <span class="attr">"rules"</span>: &#123;</div><div class="line">    <span class="attr">"semi"</span>: <span class="number">2</span></div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li><p><code>ecmaVersion</code>: 顧名思義就是 ECMA script 的 version，有 3, 5, 6, 7 可以供你挑選</p>
</li>
<li><p><code>ecmaFeatures</code></p>
<ul>
<li><p>啟用 jsx、strict mode 等 feature，預設都是關閉，可以用 boolean 的方式來開啟。</p>
</li>
<li><p>詳情可以到<a href="http://eslint.org/docs/user-guide/configuring" target="_blank" rel="external">官網文件</a>看</p>
</li>
</ul>
</li>
<li><p><code>sourceType</code>: </p>
<ul>
<li><p>預設是 script，但如果你的 code 是被包在 ECMA script 的 module 中，就要設成 module</p>
</li>
<li><p>白話文：你用 webpack 的話就把它設成 module </p>
</li>
</ul>
</li>
</ul>
<p>最後，雖然 eslint 預設的 parser 是 <code>Espree</code>，但你還是可以換成其他的 parser：</p>
<ul>
<li>Esprima, Babel-ESLint</li>
</ul>
<blockquote>
<p>parserOptions 是共通的，在以上的 parser 裡面不用擔心要寫不一樣的 parserOptions</p>
</blockquote>
<h2 id="Environments"><a href="#Environments" class="headerlink" title="Environments"></a>Environments</h2><p>可以在不同 environment 去 predefine 所需的 global variables。</p>
<blockquote>
<p>注意：</p>
<p>這裡並不是去 assign global variables，</p>
<p>而是把不同 environments 的選項給打開，</p>
<p>接著你就會取到在這個 env 底下 predefine 的 global variables 了</p>
</blockquote>
<p>一樣用 <code>.eslintrc</code>舉例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"env"</span>: &#123;</div><div class="line">        <span class="attr">"browser"</span>: <span class="literal">true</span>,</div><div class="line">        <span class="attr">"node"</span>: <span class="literal">true</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以到官方文件看有哪些 environments 可以用：</p>
<ul>
<li><a href="http://eslint.org/docs/user-guide/configuring#specifying-environments" target="_blank" rel="external">官方文件</a></li>
</ul>
<p>假如你想要自訂或是用別人 plugin 中的 env 也很簡單：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"plugins"</span>: [<span class="string">"example"</span>],</div><div class="line">    <span class="attr">"env"</span>: &#123;</div><div class="line">        <span class="attr">"example/custom"</span>: <span class="literal">true</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Globals"><a href="#Globals" class="headerlink" title="Globals"></a>Globals</h2><p>定義你需要的 global variables，</p>
<p>這裡並不是像平常寫 code 時在 assign 值給 variable 一樣，</p>
<p>因為我們並不會去執行程式碼，只會進行靜態的分析，</p>
<p>所以我們做的事情只是確認這個 global variable 是有被 define 的，</p>
<p>舉例來說：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> a = globalB</div></pre></td></tr></table></figure>
<p>上述的 <code>globalB</code> 就是未被 define 的 global variable。</p>
<p>假如我們定義了不能接受未 define variable 的規則(rule)，</p>
<p>linter 就會把這個視為語法檢查不通過。</p>
<p>所以我們必須要讓 eslint 知道這個全域變數是有被 define 過的：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"globals"</span>: &#123;</div><div class="line">        <span class="attr">"globalB"</span>: <span class="literal">true</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如此一來 parser 在看到 <code>globalB</code> 時就會知道：</p>
<p>「啊！這不就是寫在 globals 裡面的 globalB 嗎？沒事兒沒事兒」</p>
<h2 id="Plugins"><a href="#Plugins" class="headerlink" title="Plugins"></a>Plugins</h2><p>eslint 能夠很靈活的安裝第三方的 plugin。</p>
<p>這裡就是我們平常在使用 airbnb 的 config 時會用到的地方 XD，</p>
<p>通常名字會長這樣：<code>eslint-plugin-*</code>，你可以省略掉前面這一段 prefix，</p>
<p>比如說<code>eslint-plugin-demo</code>，在 <code>.eslintrc</code> 可以這樣引入：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"plugins"</span>: [</div><div class="line">        <span class="string">"demo"</span></div><div class="line">    ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>待會提到 rule 時，再來解釋要怎樣引用 plugin 裡的東西。</p>
<h2 id="Rules"><a href="#Rules" class="headerlink" title="Rules"></a>Rules</h2><p>rule 就是我們在 style guide 中定義的規則，</p>
<p>可以針對嚴重程度設定 error level：</p>
<p>分別是 <code>off</code>, <code>warn</code>, <code>error</code>，</p>
<blockquote>
<p>它們分別對應到 0, 1, 2 三個數字，</p>
<p>也就是說 <code>{&quot;curly&quot;: &quot;error&quot;}</code> 和 <code>{&quot;curly&quot;: 2}</code> 是一樣的意思。</p>
</blockquote>
<p>看例子可能會清楚一點：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"plugins"</span>: [</div><div class="line">        <span class="string">"plugin1"</span></div><div class="line">    ],</div><div class="line">    <span class="attr">"rules"</span>: &#123;</div><div class="line">        <span class="attr">"eqeqeq"</span>: <span class="string">"off"</span>,</div><div class="line">        <span class="attr">"curly"</span>: <span class="string">"error"</span>,</div><div class="line">        <span class="attr">"plugin1/rule1"</span>: <span class="string">"error"</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裡的 rule 都是 eslint 事先定義好的規則，</p>
<p>想看有哪些的話一樣可以到官方文件去看，</p>
<p>不過我想應該是不會有人一條條看完就是：<a href="http://eslint.org/docs/rules/" target="_blank" rel="external">eslint: rules</a></p>
<p>同樣的，我們可以藉由 <code>&lt;pluginName&gt;/rule</code> 來獲取 plugin 底下定義的 rule。</p>
<p>補充一下，你也可以在一些特別的時候 enable 或 disable rule。</p>
<p>舉例來說有一條規則是 code 裡面不要有任何 <code>console.log</code>，</p>
<p>但有些地方一定要存在 <code>console.log</code> 該怎麼辦呢？</p>
<p>你可以讓 eslint ignore 掉這整個 file，不過這不是個好解法。</p>
<p>更好的做法應該是在那幾行 code 前面加上 “inline disable” 的 comment：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">server.listen(<span class="number">8080</span>, <span class="string">'0.0.0.0'</span>, (err) =&gt; &#123;</div><div class="line">  <span class="comment">/* eslint-disable no-console */</span></div><div class="line">  <span class="keyword">if</span> (err) &#123;</div><div class="line">    <span class="built_in">console</span>.log(err);</div><div class="line">  &#125;</div><div class="line">  <span class="built_in">console</span>.log(<span class="string">'Listening at http://0.0.0.0:8080/'</span>);</div><div class="line">  <span class="comment">/* eslint-enable no-console */</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p><code>/* eslint-disable no-console */</code>底下的 code 都會關閉 <code>no-console</code>這個規則，</p>
<p>但<code>/* eslint-enable no-console */</code>會把 <code>no-console</code> 這個規則再次打開。</p>
<p>兩個搭配起來的結果就是在這兩段 comment 中間的 code 不會啟用 <code>no-console</code> 這個規則。</p>
<h2 id="Extends"><a href="#Extends" class="headerlink" title="Extends"></a>Extends</h2><p>總結上述幾點，其實 extends 這個 array 裡面放的其實是個完整的 config，</p>
<p>你也可以直接 extend 別人 export 出來的 config。</p>
<p>這也是為什麼當你安裝別人的 extends 時，</p>
<p>會以 <code>eslint-config-*</code>來當作 package 名稱，</p>
<p>而不是用 extension 的原因。</p>
<blockquote>
<p>同樣的，在寫 config 時，可以忽略 <code>eslint-config</code> 這個 prefix</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    &quot;extends&quot;: &quot;airbnb&quot;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Others"><a href="#Others" class="headerlink" title="Others"></a>Others</h2><ul>
<li><p>跟 git 一樣，可以忽略掉某些檔案：<code>.eslintignore</code></p>
</li>
<li><p>前面的 rules 看起來都是別人幫你建好的，你也可以參照 <a href="http://eslint.org/docs/developer-guide/working-with-rules" target="_blank" rel="external">working with rules</a> 來定義你自己的 rule。</p>
</li>
</ul>
<blockquote>
<p>對我而言現有的 rules 幾乎已經把我能想到的模組都開發完，</p>
<p>理解 linter 對我來說最重要的是知道「哪些東西是我要的」，</p>
<p>最後再將其組裝起來，而不是從頭造一遍輪子。</p>
</blockquote>
<ul>
<li><p>同理，你也可以自己開發 plugin。</p>
</li>
<li><p>你可以 extend 其他人的 config，但你也可以在最外層去把 rule 給覆寫掉。</p>
</li>
</ul>
<h1 id="Practical-Usage"><a href="#Practical-Usage" class="headerlink" title="Practical Usage"></a>Practical Usage</h1><p>如果寫完 eslint 設定，卻還要每次寫完 code 都自己跑一次：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$&gt; eslint file.js</div></pre></td></tr></table></figure>
<p>這是相當反人性的事情，所以在有了前述的背景知識後，</p>
<p>我們來看看日常開發中是如何使用的，</p>
<p>以下就兩個比較常見的方法來介紹，沒有誰好誰壞，</p>
<p>全看怎樣比較適合你的團隊。</p>
<p>我盡量不為讀的人預設什麼預備知識，</p>
<p>但懂一些 git 以及 webpack 的話，</p>
<p>設定起來會相當的 trivial：</p>
<ul>
<li><p>Webpack</p>
<ul>
<li>邊開發時就邊檢測你是否有違反規則</li>
</ul>
</li>
<li><p>git hook</p>
<ul>
<li>在 commit 前檢查是否符合規則</li>
</ul>
</li>
</ul>
<p>其實編輯器也有許多可以搭配 linter 的東西，</p>
<p>但鑑於所有開發者使用的編輯器種類太多，</p>
<p>而且編輯器的設置相對簡單，</p>
<p>所以這裡不會再贅述編輯器上面的設定。</p>
<h2 id="Integration-with-webpack"><a href="#Integration-with-webpack" class="headerlink" title="Integration with webpack"></a>Integration with webpack</h2><p>首先要先安裝 <code>eslint-loader</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$&gt; npm install -D eslint-loader</div></pre></td></tr></table></figure>
<p>接著到 <code>webpack.config.js</code> ，只要看 loaders 這個屬性就好了:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="built_in">module</span>: &#123;</div><div class="line">        loaders: [</div><div class="line">            &#123;</div><div class="line">                test: <span class="regexp">/\.js[x]?$/</span>,</div><div class="line">                exclude: <span class="regexp">/node_modules/</span>,</div><div class="line">                loaders: [<span class="string">'babel'</span>, <span class="string">'eslint'</span>]</div><div class="line">            &#125;</div><div class="line">        ]</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>loaders array 中的順序是相當重要的，因為它的順序是從最後面開始往前執行。</p>
<p>也就是說在讀取到 js 或是 jsx 檔案時，</p>
<p>會先經過 eslint 檢查，再進去 babel 轉譯。</p>
<blockquote>
<p>反之的話，一定會噴錯噴得滿天飛 XD </p>
<p>而且這樣 eslint 去檢查的就是轉譯過後的程式碼了</p>
</blockquote>
<p>但更好的方式是把 eslint-loader 放在 <code>preloaders</code> 中：</p>
<blockquote>
<p>馬的我也是第一次知道有這東西，webpack 的 config 就是這麼令人驚喜</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">&#123;</div><div class="line">    <span class="built_in">module</span>: &#123;</div><div class="line">        preLoaders: [</div><div class="line">            &#123;</div><div class="line">                test: <span class="regexp">/\.js[x]?$/</span>,</div><div class="line">                exclude: <span class="regexp">/node_modules/</span>,</div><div class="line">                loader: <span class="string">'eslint'</span></div><div class="line">            &#125;</div><div class="line">        ],</div><div class="line">        loaders: [</div><div class="line">            &#123;</div><div class="line">                test: <span class="regexp">/\.js[x]?$/</span>,</div><div class="line">                exclude: <span class="regexp">/node_modules/</span>,</div><div class="line">                loader: <span class="string">'babel'</span></div><div class="line">            &#125;</div><div class="line">        ]</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如此在開發途中，只要語法有違反規則，</p>
<p>就是視同為 error。</p>
<p>現在你已經有一個自動化的 linter 了。</p>
<p>補充一下，有些人可能會用 webpack 的 provide plugin，</p>
<p>去省掉一些 <code>../../../../actions/doSomething.js</code> 的程式碼，</p>
<p>這時候你可能會需要這個 plugin: <a href="https://www.npmjs.com/package/eslint-import-resolver-webpack" target="_blank" rel="external">eslint-import-resolver-webpack</a>，</p>
<p>然後你要在 <code>.eslintrc</code> 的 settings 裡面加上：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="attr">"settings"</span>: &#123;</div><div class="line">    <span class="attr">"import/resolver"</span>: &#123;</div><div class="line">      <span class="attr">"webpack"</span>: <span class="string">"webpack.config.js"</span></div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這樣子當你使用 <code>no-unresolved</code> 這條規則時，</p>
<p>eslint 會先去檢查你在 provide 裡的 alias，</p>
<p>再來看有沒有辦法 resolve 這個 path。</p>
<h2 id="Integration-with-git-hooks"><a href="#Integration-with-git-hooks" class="headerlink" title="Integration with git hooks"></a>Integration with git hooks</h2><blockquote>
<p>如果你很熟悉 git 的話甚至可以不用安裝這套件 XD </p>
</blockquote>
<p>git hook 能做的事情就是讓開發者在執行某些 git 操作前，</p>
<p>自動得去執行某些 scripts，</p>
<p>不過首先，我們要先將 lint 的 script 給寫出來才行</p>
<p>接著在 <code>package.json</code> 裡面：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"scripts"</span>: &#123;</div><div class="line">        <span class="attr">"lint"</span>: <span class="string">"./node_modules/eslint/bin/eslint.js target.js"</span>,</div><div class="line">    &#125;,</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來只要執行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$&gt; npm run lint</div></pre></td></tr></table></figure>
<p>就會自動的去做 lint，簡單的 script 完成了，</p>
<p>接下來就是跟 git hook 結合的時候，</p>
<p>會需要用到 <code>husky</code> 這個套件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$&gt; npm install husky --save-dev</div></pre></td></tr></table></figure>
<p>會用它的原因是因為它用起來簡單粗暴，</p>
<p>不管你要用哪個 hook，只要把名字放在 npm script 中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"scripts"</span>: &#123;</div><div class="line">        <span class="string">"lint"</span>: <span class="string">"./node_modules/eslint/bin/eslint.js demoStore.js"</span>,</div><div class="line">        <span class="string">"precommit"</span>: <span class="string">"npm run lint"</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>你的 git hook 就設定完成了</p>
<blockquote>
<p>precommit 就是在 commit 之前我們會去執行 <code>npm run lint</code>這個 script，</p>
<p>這裡有個對應的 <a href="https://github.com/typicode/husky/blob/master/HOOKS.md" target="_blank" rel="external">hooks 表格</a></p>
<p>你可以挑一個在適當的時機執行語法的 lint</p>
</blockquote>
<h2 id="Other-solution"><a href="#Other-solution" class="headerlink" title="Other solution"></a>Other solution</h2><p>不過如果每次 Commit 都要跑一次 lint，讓你很煩的話，</p>
<p>實務上的做法也可以只整合在 IDE 以及 CI server 上就足夠。</p>
<p>假如你還是要保留原本的流程，</p>
<p>但在某些整理 commit 時並不需要重新執行 lint的話，</p>
<p>也可以在 commit 時加上 <code>--no-verify</code>或<code>-n</code>。</p>
<p>還有一個做法是使用 <a href="https://github.com/okonet/lint-staged" target="_blank" rel="external"><code>lint-staged</code></a> 這個套件，</p>
<p>簡單的說，它會讓 linter 只檢查新放上 stage 的 code，</p>
<blockquote>
<p>在 git 中執行 add 之後，會把 file 放到 stage 上，</p>
<p>這就是為什麼他要命名為 <code>lint-staged</code>。</p>
</blockquote>
<p>這樣每次的 Commit 就不用重新檢查一次全部的程式碼了。</p>
<blockquote>
<p>快速的想過一遍之後，<code>lint-staged</code>可能會有個小 gotcha，</p>
<p>可能在 <code>no-unresolved</code> 這條 rule 上面犯錯。</p>
<p>舉例來說 a 檔案會 require <code>./b</code>，</p>
<p>然後我把 b 刪掉了，這次 a 檔案並不會上 stage，</p>
<p>所以這次檢查並不會把這個錯誤給檢查出來，</p>
<p>但整體而言其實還是為我們省了不少時間，</p>
<p>就看個人怎麼選擇啦！</p>
</blockquote>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>在學習 eslint 的過程中，</p>
<p>對於這種自動化、提升團隊程式碼品質的東西又有了一些心得，</p>
<p>像是 eslint-loader 以及 git hook 的使用時機都是。</p>
<p>同時也理解到這種 pluggable 的特性在開發者的世界裡能帶來極大的成功，</p>
<p>看看 webpack、babel，以及 eslint 都是因為其容易製作 plugin 的特性，</p>
<p>讓開發者自主的開發出優質的插件來讓整個生態系更蓬勃。</p>
<p>也許工具會一代代推陳出新，</p>
<p>但是這種我為人人、人人為我的系統思維是不會變的。</p>
<p>最後，</p>
<p>在前面有說過 coding style 之於指喻，</p>
<p>最近實務上有個算小型的 project 從一開始開發時並沒有去使用 eslint，</p>
<p>到了今天把簡單的 style guide 訂出來之後，（大概就是四條 rules 而已，沒有直接引用 airbnb 那一套）</p>
<p>結果是這個樣子：</p>
<p><img src="http://i.imgur.com/FFLkTXA.png" alt="errro"></p>
<p>嗯⋯⋯</p>
<p>晚了一點以後更新成 airbnb 的 config 然後自己修改一下 rule，</p>
<p>變成：</p>
<p><img src="http://i.imgur.com/PYzEmMf.png" alt="error2"></p>
<p>….</p>
<p><img src="http://i.imgur.com/2yJBwXp.jpg" alt="eyes"></p>
<p>這一定是假的。</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="http://eslint.org/" target="_blank" rel="external">eslint</a></p>
</li>
<li><p><a href="http://abalone0204.github.io/2016/04/25/Super-tiny-compiler/" target="_blank" rel="external">Super tiny compiler</a></p>
</li>
<li><p><a href="http://www.jianshu.com/p/35b9fc5467e0" target="_blank" rel="external">谈谈Parser - 王垠</a></p>
</li>
<li><p><a href="https://blog.gopheracademy.com/advent-2014/parsers-lexers/" target="_blank" rel="external">Handwritten Parsers &amp; Lexers in Go - Gopher Academy</a></p>
</li>
<li><p><a href="https://github.com/MoOx/eslint-loader" target="_blank" rel="external">eslint-loader</a></p>
</li>
</ul>
<blockquote>
<p>感謝 <a href="https://github.com/wuct" target="_blank" rel="external"><code>@ctwu</code></a> 、李俊緯對開發流程中整合 eslint 的建議</p>
<p>感謝 Amobiz Chen 提供 <code>lint-staged</code>這個工具</p>
<p>感謝陳威霖提醒我要加上 inline-disable 的用法 XD</p>
</blockquote>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;相信團隊為了提升程式碼的品質，&lt;/p&gt;
&lt;p&gt;第一步通常會是制定 style guide，&lt;/p&gt;
&lt;p&gt;但 style guide 越定越複雜後，要靠人工去檢查就顯得有點不切實際。&lt;/p&gt;
&lt;p&gt;這時候就需要靠程式自動來做語法上的檢查及 highlight，&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;更殘酷一點可以讓不符合 coding style 的 code 無法被 commit&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;這就是 linter 的功用。&lt;/p&gt;
&lt;p&gt;而這篇會以我最近在實務上以 eslint + webpack + githook 來做舉例。&lt;/p&gt;
&lt;p&gt;我知道網路上有許多充滿獨到經驗的 javascript linter，最有名應該就是 airbnb 的），&lt;/p&gt;
&lt;p&gt;直接拿來用當然也 ok，不過，我們固然要學工具，&lt;/p&gt;
&lt;p&gt;工具背後的想法才是我們更該了解的。&lt;/p&gt;
&lt;p&gt;這一篇並不是什麼懶人教學，複製貼上就能用的 eslint extends，&lt;/p&gt;
&lt;p&gt;而是一步一步地去理解 eslint 到底能做到什麼事情，&lt;/p&gt;
&lt;p&gt;也許你看完以後還是會選擇直接使用 airbnb 或是其他人寫好的 linter，&lt;/p&gt;
&lt;p&gt;但這時候的你，&lt;/p&gt;
&lt;p&gt;已經完全有能力參考前人經驗並制定出一套符合你們團隊需求的 linter，&lt;/p&gt;
&lt;p&gt;甚至去看他們的設定時，能夠對他們為什麼這樣做更有想法。&lt;/p&gt;
&lt;p&gt;希望你看完之後，學會的並不是 eslint 這個工具而已，&lt;/p&gt;
&lt;p&gt;而是未來你要做類似東西時內心已經有一個架構在。&lt;/p&gt;
&lt;p&gt;雖然站在巨人肩膀上能夠看的更遠，&lt;/p&gt;
&lt;p&gt;但能夠自己造出一個鋼彈再站上去，那他媽完全是不一樣帥氣的事情。&lt;/p&gt;
    
    </summary>
    
    
      <category term="eslint" scheme="http://abalone0204.github.com/tags/eslint/"/>
    
      <category term="webpack" scheme="http://abalone0204.github.com/tags/webpack/"/>
    
  </entry>
  
  <entry>
    <title>寫在 Clairvoyance 發布之後：軟體開發者的社會責任</title>
    <link href="http://abalone0204.github.com/2016/06/16/clv-beta-version/"/>
    <id>http://abalone0204.github.com/2016/06/16/clv-beta-version/</id>
    <published>2016-06-16T01:44:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<blockquote>
<p>這篇可能不會講到太多直接跟技術相關的東西，</p>
<p>如果你對這個東西怎麼寫出來比較有興趣的話，</p>
<p>可以看這篇：<a href="http://abalone0204.github.io/2016/06/12/clv-dev-note/" target="_blank" rel="external">Clairvoyance 是怎麼開發的</a></p>
<p>主要是希望這次從開發到現在較多人使用，</p>
<p>中間受到許多幫助和指點的經驗，能夠被記錄下來，</p>
<p>假如以後有人遇到一樣的事情能從中借鏡。</p>
<p>當然，這也是對自己的一個反省。</p>
</blockquote>
<p>首先還是得先講一下求職天～眼通是什麼。</p>
<p>它其實就是個 chrome 的 extension，</p>
<p>裝了它以後，能在人力銀行的職缺下方給評論，以及看到其他人給的評論，</p>
<p>載點在這裡：</p>
<p><a href="https://chrome.google.com/webstore/detail/clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A/mdneakdlnoidknagkamfeambdefhppbi?hl=zh-TW&amp;gl=TW" target="_blank" rel="external"><img src="https://raw.githubusercontent.com/abalone0204/Clairvoyance/master/chrome-store-available.png" alt="pic"></a></p>
<p>其他說明的話 <a href="https://www.ptt.cc/bbs/Soft_Job/M.1465759641.A.E57.html" target="_blank" rel="external">ptt 上的文章</a>會清楚得多。</p>
<h1 id="目錄"><a href="#目錄" class="headerlink" title="目錄"></a>目錄</h1><ul>
<li><p><a href="#在開始動手寫程式之前">在開始動手寫程式之前</a></p>
<ul>
<li>只有這一小段會講到比較多技術相關的</li>
</ul>
</li>
<li><p><a href="#發布-Beta-版本">發布 Beta 版本</a></p>
</li>
<li><p><a href="#收到回饋之後">收到回饋之後</a></p>
</li>
<li><p><a href="#商業化的迷思以及贊助管道">商業化的迷思以及贊助管道</a></p>
</li>
<li><p><a href="#未來方向">未來方向</a></p>
</li>
<li><p><a href="#一個軟體工作者的反思">一個軟體工作者的反思</a></p>
</li>
</ul>
<a id="more"></a>
<p><img src="http://i.imgur.com/QvYeAmN.png" alt="Jean Grey and Cyclops from Entertainment Weekly"></p>
<blockquote>
<p>Jean Grey and Cyclops from Entertainment Weekly</p>
</blockquote>
<p>求職天～眼通要做的事情很單純，</p>
<p>就是像前面說的把留言功能加上去而已，</p>
<p>不過其實就像我們平常在做一件事情一樣，用想的都很簡單。</p>
<p>但總歸其實只會遇到三個問題：</p>
<ol>
<li><p>真正做的時候會遇到問題</p>
</li>
<li><p>做出來之後有沒有人用會是一個問題</p>
</li>
<li><p>有太多人用之後又會是一個問題</p>
</li>
</ol>
<p>下面來說一下從端午連假到今天為止的這一段故事，</p>
<p>寫程式是這個故事很重要的一部份，</p>
<p>不過其實還有很多其他眉眉角角可以跟大家分享。</p>
<h1 id="在開始動手寫程式之前"><a href="#在開始動手寫程式之前" class="headerlink" title="在開始動手寫程式之前"></a>在開始動手寫程式之前</h1><p>在開發前，首要的認知就是知道：</p>
<p>自己擅長什麼、手上有什麼資源，如果前兩者還不夠還要再準備什麼。</p>
<p>其實有這個發想是在端午節之前，</p>
<p>我平常是一個網頁前端工程師。</p>
<blockquote>
<p>雖然也寫寫後端以及對系統感興趣，</p>
<p>但我知道 full stack 是一個被濫用的職稱。</p>
<p>這年頭多的是 Database 操作只會 CRUD 的前端工程師稱自己為 full stack，</p>
<p>或是只會套 bootstrap 的後端工程師稱自己為 full stack。</p>
</blockquote>
<p>最常用的語言剛好就是 JavaScript ，可以直接拿來寫 Chrome 的插件，</p>
<p>但這還不夠，我還需要一個存放資料的 back-end。</p>
<p>下面這個基本上就是我畫在紙上的草圖：</p>
<p><img src="https://github.com/abalone0204/Clairvoyance/raw/master/clv-arc.png" alt="pic"></p>
<p>本來打算直接在 AWS 上開一個 EC2+RDS 放著，</p>
<p>後來發現只是單純留言，也沒有要真正 render 一個網頁。</p>
<p>這個 back-end 需要能達到兩件事情：</p>
<ol>
<li><p>計算的能力</p>
</li>
<li><p>資料的持久性</p>
</li>
</ol>
<p>首先是單純的運算能力，最終看上了 AWS 的另一個服務 AWS lambda，</p>
<p>它是以 function 為單位，不會需要我去維護整台機器（serverless），</p>
<p>而且當運算量變大時，我大 amazon 會自己幫我 scale-out。</p>
<p>於是稍微研究了一下 serverless 這套 framework，</p>
<p>也寫了一份筆記在這裡：</p>
<ul>
<li><a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/" target="_blank" rel="external">淺析 serverless 架構與實作</a>。</li>
</ul>
<p>再來則是資料的持久性，我選擇了 DynamoDB，</p>
<p>是個跟 lambda 搭配很常見的選擇。</p>
<p>儘管它看起來就是簡單易用，</p>
<p>但為了這個選擇其實下了不少功夫，</p>
<p>一開始是因為對「最終一致性」有疑慮，所以去看了 CAP 理論：</p>
<ul>
<li><a href="http://www.julianbrowne.com/article/viewer/brewers-cap-theorem" target="_blank" rel="external">Brewer’s CAP Theorem</a></li>
</ul>
<p>後來再看了這本簡介分散式運算的書：</p>
<ul>
<li><a href="http://book.mixu.net/distsys/" target="_blank" rel="external">Distributed systems for fun and profit</a></li>
</ul>
<p>總歸對系統的架構有個理解後，才開始安心使用，</p>
<p>儘管現在回頭看這兩份文本都可以跳過，</p>
<p>但要做能 scale-out 的系統，</p>
<p>對分散式運算如果一無所知的話，會沒有那個 sense，</p>
<p>身為一個軟體人就不該對未知的東西姑息或害怕去學它。</p>
<p>接著一切就緒後，我突然發現我少了一位設計師夥伴，</p>
<p>基於不想在假日麻煩人，我上了 <a href="https://codepen.io" target="_blank" rel="external">codepen</a> 去看他們的 license：</p>
<blockquote>
<p>codepen 是一個讓前端工程師放作品的地方，上面有蠻多好玩的設計以及如何實做的原始碼。</p>
<p>有人會問跟 pinterest 有什麼差別？</p>
<p>簡言之 pinterest 是比較偏向純設計師的。</p>
</blockquote>
<ul>
<li><a href="https://blog.codepen.io/legal/licensing/" target="_blank" rel="external">What License Is Code I Post to CodePen?</a></li>
</ul>
<p>簡單說一句話，就是 public pen 都是 MIT license 的，</p>
<p>要使用的話，只要包含了他們原本的 license，就可以自由使用。</p>
<p>雖然最後幾乎都只是參考概念，並沒有真正援用哪個 pen 上的東西，</p>
<p>但身為一個軟體開發者，就應該遵守這些基本的規定，</p>
<p>畢竟當真的有人要找你麻煩時，沒有不知者不罪這種事情。</p>
<blockquote>
<p>如果對於這些法規方面以及技術有興趣的人，</p>
<p>可以去 follow Muzik Online 首席工程師 Ant 的臉書，</p>
<p>上面有許多能讓技術人有一些法規 sense 的文章，</p>
<p>而且對於 Database 和系統架構，上面也很多東西可以看。</p>
</blockquote>
<p>好了，現在我有：</p>
<ul>
<li><p>前端開發能力</p>
</li>
<li><p>back-end</p>
</li>
<li><p>codepen 上參考的 UI</p>
</li>
</ul>
<p>再來只是需要時間就能把東西做出來了。</p>
<h1 id="發布-Beta-版本"><a href="#發布-Beta-版本" class="headerlink" title="發布 Beta 版本"></a>發布 Beta 版本</h1><p>大家看到的版本，其實是有滿滿 bug 的 beta 版本，</p>
<p>我只有讓身邊幾個朋友測試過，就先 po 在 soft_job 板上。</p>
<blockquote>
<p>讓開發者以外的人先測過這一步至關重要，</p>
<p>因為自己開發的東西一定會有盲點。</p>
</blockquote>
<p>會這樣做的原因是因為我想知道這東西是不是真的有需求，</p>
<p>當時 po 完文章就去睡覺，早上看到有三十推就覺得蠻開心，</p>
<p>結果幾個小時候 TonyQ 將它轉到八卦版去，直接一個爆衝。</p>
<p>但結局讓我又開心又害怕：</p>
<ul>
<li><p>開心的是這東西真的有需求，而且很有需求。</p>
</li>
<li><p>害怕的是我覺得這東西還不夠成熟，怕一開始太難用就直接被拋棄。</p>
</li>
</ul>
<p>令我意外的是， aws lambda 和 DynamoDB 完全撐住了流量，</p>
<p>當初把這些東西交到雲端託管有了成效，</p>
<p>後來去看 log 發現沒辦法留言，都是原本 code 裡面有 bug，</p>
<p>跟 AWS 一點關係都沒有 XD</p>
<p>不過後續就一直修到昨天晚上為止，留言功能才算正式穩定下來。</p>
<h1 id="收到回饋之後"><a href="#收到回饋之後" class="headerlink" title="收到回饋之後"></a>收到回饋之後</h1><p>接著除了大量的 bug 回報之外，</p>
<p>也收到許多跟功能上有關的回饋。</p>
<p>其實大部分的回饋我都認為做了功能絕對會更完善，</p>
<p>但時間並不允許這樣做，</p>
<p>所以問題並不在於「現在要做什麼」，而是「現在不做什麼」。</p>
<blockquote>
<p>這裡感謝 TonyQ 以及榮尼王給我的許多建議。</p>
</blockquote>
<p>因為背負著很多人的期待，我並不能想做什麼就亂做什麼，</p>
<p>必須訂下一個明確開發的方向，</p>
<p>就現階段而言，讓這個 extension 活下去是至關緊要的事情，</p>
<p>因為已經有了第一批用戶（已註冊目前大概約四千多人），</p>
<p>剩下的只是繼續累積。</p>
<p>太激進、會讓人力銀行對這個 extension 採取行動的事情，</p>
<p>都不該去做，因為目前還玩不起這個槓桿。</p>
<blockquote>
<p>不過 github 上面有許多人提了一些有辦法解決的方法，</p>
<p>總之，沒有「絕對不做」的事情，只有「現階段不做」而已，</p>
<p>有興趣的人也可以去看看，集思廣益：</p>
<p><a href="https://github.com/abalone0204/Clairvoyance/issues" target="_blank" rel="external">Issue 討論區</a></p>
</blockquote>
<h1 id="商業化的迷思以及贊助管道"><a href="#商業化的迷思以及贊助管道" class="headerlink" title="商業化的迷思以及贊助管道"></a>商業化的迷思以及贊助管道</h1><p>有蠻多人在提到這件事情要商業化，</p>
<p>也有人覺得只要「不商業化」就先把你貼上「傻傻、不懂事」的標籤。</p>
<p>但其實我一點都不排斥商業化，我只是單純的覺得這件事不適合，</p>
<p>或者現在沒想到適合的方式。</p>
<p>像是如果要在上面硬是建立一個什麼商業模式，（像是廣告什麼的）</p>
<p>這東西最後看起來只會是一個擾民的垃圾。</p>
<p>而且當以獲利角度來做這些事情，</p>
<p>我就不能單純站在勞工的角度去思考了。</p>
<p>至於要永續經營，後續等真正穩定下來後，</p>
<p>會放上小額捐款的連結，</p>
<p>這件事會在擬定如何公布經費的使用以及規劃後才做，</p>
<p>不在現在就先急著募錢的原因很簡單，</p>
<p>因為我想讓捐錢的人真正弄清楚他們的錢為何所用，</p>
<p>畢竟群眾募資不是大乞討，懂？</p>
<h1 id="未來方向"><a href="#未來方向" class="headerlink" title="未來方向"></a>未來方向</h1><p>這裡不談功能，最終的希望就是所有的勞方都會是天眼通的用戶。</p>
<p>因為大家並不是一年四季都在找工作，</p>
<p>但大家卻是一年四季都能上去做評論，</p>
<p>有時候並不是說一定要面試過或怎樣才能做評論，</p>
<p>短期內，可以揭露一些根本沒必要去的職缺，</p>
<p>長期下來，經驗的分享才是這個 extension 最難發揮價值的地方，</p>
<p>「老馬識途」這種事情，在職場上也是適用的，</p>
<p>總之，如何吸引大家去做這件事，就會是接下來的主要課題。</p>
<h1 id="一個軟體工作者的反思"><a href="#一個軟體工作者的反思" class="headerlink" title="一個軟體工作者的反思"></a>一個軟體工作者的反思</h1><p>終於寫到這裡了，前幾天看到了 <a href="weekly.codetengu.com">Codetengu</a> 上分享了這篇文章：</p>
<ul>
<li><a href="http://groundbreaking.tw/wordpress/archives/2055" target="_blank" rel="external">此處有bug：程序員統治的黑暗世界</a></li>
</ul>
<p>我也想到前陣子 Alpha Go 很夯時，阮一峰所寫的文章：</p>
<ul>
<li><a href="http://www.ruanyifeng.com/blog/2016/03/techonology-vs-equality.html" target="_blank" rel="external">技术会带来社会平等吗？</a></li>
</ul>
<p>身為一個軟體開發者，能了解電腦能做到的就是大量自動化、去中介化，</p>
<p>去取代掉那些機器可以取代的員工，</p>
<p>企業為了達成這件事情，自然要雇用一堆軟體工程師來幫忙，</p>
<p>所以軟體工作者也變成一個搶手的職業。</p>
<p>所謂技術帶來的平等，是指「資訊上」的平等，</p>
<p>我們的資訊流通因為網路和軟體越來越快，</p>
<p>舉例像是：歐巴馬總統和我們一樣都能用 google 快速查東西。</p>
<blockquote>
<p>這年頭不知道還有沒有人記得百科全書這東西</p>
</blockquote>
<p>但在財富上卻不盡然，我們拿到越來越多薪水時，也讓越來越多的人失業，</p>
<p>當此同時，除了繳了多一點點的稅，</p>
<p>我們大多數人並沒有負起什麼社會責任。</p>
<p>儘管軟體開發者理應是最有辦法讓想法付諸實現的人才對，</p>
<p>畢竟軟體能夠運行在電腦這個已經稱霸全球的載體上，</p>
<p>更別說我們還有了 Internet 這樣鋪天蓋地的通路，</p>
<p>寫程式這件事雖然有時候我也會因為智商不夠用覺得好難，</p>
<p>但是比起動不動要砸大錢的製造業，寫程式真的容易實現多了。</p>
<p>寫程式是世界的潮流沒錯，</p>
<p>只是許多台灣創業家提到寫程式就很喜歡強調矽谷如何、如何，</p>
<p>忽略了許多在本質上就有顯著差異的事情。</p>
<blockquote>
<p>統計學裡面告訴我們：<strong>有顯著差異是要拒絕虛無假設的</strong>，這句話現在看來蠻有哲理。</p>
</blockquote>
<p>我不會說面對國際市場是一件錯誤的事情，</p>
<p>在商言商總是有許多額外的考量，</p>
<p>畢竟連話說的不好聽，要怎麼讓人掏錢投資勒？</p>
<p>只是很多問題，其實台灣有其因應的解決方式，</p>
<p>而工程師本來就該是提出 solution 的人，而不是負責說空話的人，</p>
<p>所以更應該要虛心學習用一個台灣人的角度來看向世界以及台灣，</p>
<p>才能真正解決台灣的問題。</p>
<p>舉例來說：這個插件就是解決台灣特有的問題 XD，</p>
<p>因為國外的求職平台沒有像台灣這樣被壟斷。</p>
<p>中國那邊的招募平台也幾乎都有開放留言討論這個功能，</p>
<p>資方跟勞方是積極在<del>爭論</del>對話的。</p>
<p>所以這插件只有在這樣子的台灣才會有需求XD</p>
<blockquote>
<p>題外話是其實台灣也有蠻多新的求職平台，</p>
<p>像是 <a href="https://sudo.com.tw/" target="_blank" rel="external">sudo</a>，</p>
<p>或是 <a href="https://www.yourator.co/" target="_blank" rel="external">yourator</a>，</p>
<p>都相當不錯，而且在資訊上也相對傳統的人力銀行透明很多，</p>
<p>不過都是比較以新創或工程師為主。</p>
<p>特別講到 sudo 是因為他們的留言功能更完整，</p>
<p>（正因為以前就在那裡工作才更了解這些事情）</p>
<p>裡面的就職顧問雖然是講話很愛中英交雜的 AIESECer，</p>
<p>但絕對是真心要幫助工程師求職的：Ｄ</p>
</blockquote>
<p>再來雖然現代人生活離不開電腦，</p>
<p>但其實對於軟體相關的事務都是有疏離和懼怕感的，</p>
<p>很多時候是因為身為人與機器的 Proxy 的我們沒有做好事情讓其他人有感。</p>
<p>身為一個在軟體產業工作的人，</p>
<p>這件事可能會蠻常見的，就是你有時候很難跟不寫程式的人敘述你到底完成了一些什麼 XD</p>
<p>舉例：</p>
<ol>
<li><p>把什麼東西做了 cache 讓它更快</p>
</li>
<li><p>或是用了什麼 Design Pattern 提高了維護性</p>
</li>
</ol>
<p>別人聽一聽常常是：「喔⋯⋯這樣啊⋯⋯」。</p>
<p>但生活中到處都是我們能夠付出專業能力去改變的地方，</p>
<p>工作之餘，還要有生活，生活之餘，</p>
<p>我們還能改善其他人的生活啊 :D</p>
<p>當認為有正確的事情該做，</p>
<p>就該運用系統化的角度去設計和解決，</p>
<p>因為假如做出來不小心規模化，你的系統又扛得住的話，</p>
<p>那可能就不小心改變世界了。</p>
<blockquote>
<p>題外話是天眼通本來是個我跟別人講，</p>
<p>別人只會說：「喔～聽起來還不錯啊」的 Project。XDD</p>
</blockquote>
<p>再說我們身在這個年代，</p>
<p>有各種雲端服務幫你搞定基礎建設（IaaS、SaaS、PaaS），</p>
<p>還有各種框架幫你搞定 UI。</p>
<p>基本上你只要有想法、計畫，再加上一段時間穩紮穩打的學習、練習，</p>
<p>幾乎就能解開各種 Issue 了，</p>
<p>不覺得很讚嗎？</p>
<p>讚讚讚！</p>
<ul>
<li><p><a href="https://github.com/abalone0204/Clairvoyance" target="_blank" rel="external">github repo: Clairvoyance</a></p>
</li>
<li><p><a href="https://www.facebook.com/clairvoyance4job/" target="_blank" rel="external">facebook 粉絲專頁</a></p>
</li>
</ul>
<p>也期許自己未來是真正的 RD 工程師，</p>
<p>而不是出現 bug 只會 XD 的 XD 工程師：</p>
<p><img src="http://i.imgur.com/lwFbW4l.jpg" alt="XD"></p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/" target="_blank" rel="external">淺析 serverless 架構與實作</a></p>
</li>
<li><p><a href="http://www.julianbrowne.com/article/viewer/brewers-cap-theorem" target="_blank" rel="external">Brewer’s CAP Theorem</a></p>
</li>
<li><p><a href="http://book.mixu.net/distsys/" target="_blank" rel="external">Distributed systems for fun and profit</a></p>
</li>
<li><p><a href="http://www.ruanyifeng.com/blog/2016/03/techonology-vs-equality.html" target="_blank" rel="external">技术会带来社会平等吗？</a></p>
</li>
<li><p><a href="http://groundbreaking.tw/wordpress/archives/2055" target="_blank" rel="external">此處有bug：程序員統治的黑暗世界</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;blockquote&gt;
&lt;p&gt;這篇可能不會講到太多直接跟技術相關的東西，&lt;/p&gt;
&lt;p&gt;如果你對這個東西怎麼寫出來比較有興趣的話，&lt;/p&gt;
&lt;p&gt;可以看這篇：&lt;a href=&quot;http://abalone0204.github.io/2016/06/12/clv-dev-note/&quot;&gt;Clairvoyance 是怎麼開發的&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;主要是希望這次從開發到現在較多人使用，&lt;/p&gt;
&lt;p&gt;中間受到許多幫助和指點的經驗，能夠被記錄下來，&lt;/p&gt;
&lt;p&gt;假如以後有人遇到一樣的事情能從中借鏡。&lt;/p&gt;
&lt;p&gt;當然，這也是對自己的一個反省。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;首先還是得先講一下求職天～眼通是什麼。&lt;/p&gt;
&lt;p&gt;它其實就是個 chrome 的 extension，&lt;/p&gt;
&lt;p&gt;裝了它以後，能在人力銀行的職缺下方給評論，以及看到其他人給的評論，&lt;/p&gt;
&lt;p&gt;載點在這裡：&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://chrome.google.com/webstore/detail/clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A/mdneakdlnoidknagkamfeambdefhppbi?hl=zh-TW&amp;amp;gl=TW&quot;&gt;&lt;img src=&quot;https://raw.githubusercontent.com/abalone0204/Clairvoyance/master/chrome-store-available.png&quot; alt=&quot;pic&quot;&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;其他說明的話 &lt;a href=&quot;https://www.ptt.cc/bbs/Soft_Job/M.1465759641.A.E57.html&quot;&gt;ptt 上的文章&lt;/a&gt;會清楚得多。&lt;/p&gt;
&lt;h1 id=&quot;目錄&quot;&gt;&lt;a href=&quot;#目錄&quot; class=&quot;headerlink&quot; title=&quot;目錄&quot;&gt;&lt;/a&gt;目錄&lt;/h1&gt;&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#在開始動手寫程式之前&quot;&gt;在開始動手寫程式之前&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;只有這一小段會講到比較多技術相關的&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#發布-Beta-版本&quot;&gt;發布 Beta 版本&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#收到回饋之後&quot;&gt;收到回饋之後&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#商業化的迷思以及贊助管道&quot;&gt;商業化的迷思以及贊助管道&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#未來方向&quot;&gt;未來方向&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href=&quot;#一個軟體工作者的反思&quot;&gt;一個軟體工作者的反思&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
    
    </summary>
    
    
      <category term="serverless" scheme="http://abalone0204.github.com/tags/serverless/"/>
    
      <category term="clairvoyance" scheme="http://abalone0204.github.com/tags/clairvoyance/"/>
    
      <category term="chrome-extension" scheme="http://abalone0204.github.com/tags/chrome-extension/"/>
    
  </entry>
  
  <entry>
    <title>Clairvoyance 是怎麼開發的</title>
    <link href="http://abalone0204.github.com/2016/06/12/clv-dev-note/"/>
    <id>http://abalone0204.github.com/2016/06/12/clv-dev-note/</id>
    <published>2016-06-12T19:07:33.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>我寫了一個 chrome 的插件，</p>
<p>能夠讓求職者在人力銀行的職缺下面留言討論。</p>
<p>聽起來是很平常的需求，不過各大人力銀行就是不做這個功能，</p>
<p>所以我想看看假如有這個功能會不會對求職有正向的幫助。</p>
<p>下載的連結在這裡： <a href="https://chrome.google.com/webstore/detail/clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A/mdneakdlnoidknagkamfeambdefhppbi?hl=zh-TW&amp;gl=TW" target="_blank" rel="external">Clairvoyance - 求職天眼通</a></p>
<p>目前還在 beta 階段，可能會有些 bug，</p>
<p>可以到<a href="https://www.facebook.com/Clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A-1084564708284768" target="_blank" rel="external">粉絲頁</a>留言，</p>
<p>或是在 <a href="https://github.com/abalone0204/Clairvoyance" target="_blank" rel="external">github</a> 上直接發 issue。</p>
<p>下面就來筆記一下為什麼要做這件事，以及怎麼做到的。</p>
<p>用的技術就是以下列的這些</p>
<ul>
<li><p>front-end: reactjs、redux、redux-saga</p>
</li>
<li><p>back-end: aws-lambda, dynamodb, serverless-framework</p>
</li>
</ul>
<blockquote>
<p>目前只支援 104 和 1111，至於 yes123，後面會再提到為什麼暫時沒做。</p>
</blockquote>
<p>下面來簡介一下是怎麼做出來、以及為什麼要做。</p>
<a id="more"></a>
<p><img src="https://raw.githubusercontent.com/abalone0204/Clairvoyance/master/static/intro.jpg" alt="clv intro"></p>
<h1 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h1><p>為什麼要做這件事情？</p>
<p>其實我比較想問的問題是：為什麼不要做這件事情呢？</p>
<p>我們買商品的時候，在拍賣網站上就可以看到買家對店家的評價、對商品的評價，</p>
<p>而求職的時候，卻一定要到其他討論區、其他網站，</p>
<p>才能看到其他人對於該職缺或公司的評價，</p>
<p>這其實是一件很不自然的事情，</p>
<p>再說種種擔心對手黑函還是求職者亂抹黑什麼的，</p>
<p>嗯⋯⋯電商其實也會遇到這樣的事情，</p>
<p>總之想不到一個很合理的解釋，</p>
<p>唯一能想得到的解釋就是<strong>「盈利模式」</strong>。</p>
<p>目前我們在人力銀行上找工作，其實是不用付錢的，</p>
<p>但是企業卻是要付費用才能張貼職缺。</p>
<p>合理的推斷，</p>
<p>其實我們這些求職方就是人力銀行的商品，</p>
<p>真正的使用者是那些企業用戶（資方），</p>
<p>而讓使用者能夠留言討論的功能，</p>
<p>可能會讓部分企業用戶不想使用。</p>
<blockquote>
<p>看看各大人力銀行上，許多職缺都喜歡「面議」</p>
<p>就知道資訊不對稱對於資方來說是一件多麼正常的事情</p>
<p>我不會認為敘薪是簡單的，</p>
<p>但給個底價，避免浪費彼此時間這件事，</p>
<p>真心不應該難道哪裡去。</p>
<p>否則騙人去面試的行為，其實跟詐騙集團一樣可恥</p>
</blockquote>
<p>無論背後的動機是什麼，</p>
<p>既然人力銀行有其考量不做這件事、我又認為有需要的話，</p>
<p>那與其動嘴巴抱怨台灣的求職平台不好用，</p>
<p>不如自己來做做看，看能不能為台灣險峻的就業環境帶來一些幫助。</p>
<blockquote>
<p>在做這個 side project 之前，</p>
<p>其實我自己找工作從來都沒有用過各大人力銀行，</p>
<p>這次還花蠻多時間在探究自己到底為什麼不用這些平台，</p>
<p>以及他們到底缺少了什麼。</p>
</blockquote>
<h1 id="What-is-clairvoyance"><a href="#What-is-clairvoyance" class="headerlink" title="What is clairvoyance"></a>What is clairvoyance</h1><p>為什麼是這個名字？ </p>
<p>命名一直是蠻困難的一件事情，</p>
<p>本來有想過要叫什麼 job-bar in in der。</p>
<p>不過後來還是靈光一現跑出這個單字：</p>
<p>Clairvoyance。</p>
<p>為什麼要取這個名字有兩個版本的故事：</p>
<h2 id="高級版本"><a href="#高級版本" class="headerlink" title="高級版本"></a>高級版本</h2><p>Clairvoyance，可以翻作洞察力或是透視，</p>
<p>主要是希望透過求職者彼此分享經驗，</p>
<p>來透視一個職缺的好壞，或是否適合他。</p>
<h2 id="真實版本"><a href="#真實版本" class="headerlink" title="真實版本"></a>真實版本</h2><p>其實就是 google 天眼通，</p>
<p>翻譯的第一個單字就是 Clairvoyance，</p>
<p>然後我蠻喜歡周星馳的賭聖，所以就這樣命名了。</p>
<h1 id="Why-is-Clairvoyance"><a href="#Why-is-Clairvoyance" class="headerlink" title="Why is Clairvoyance"></a>Why is Clairvoyance</h1><p>其實會做這個 project ，</p>
<p>有一部分是因為自己最近開始接觸分散式運算，</p>
<p>開始了解去中心化的想法，</p>
<p>我認為與其把所有對平台上職缺的評論給「集中」起來，</p>
<p>不如將它分散到各自原本的職缺下方，</p>
<p>然後再將相同職缺的評論同步。（Consistency）</p>
<p>這樣的做法是更合理，而且使用起來更有效率的。</p>
<h1 id="Architecture"><a href="#Architecture" class="headerlink" title="Architecture"></a>Architecture</h1><blockquote>
<p>假如說一開始我知道會這麼搞剛的話，</p>
<p>應該就會放棄了⋯⋯</p>
</blockquote>
<p>整個 project 主要分成三塊：</p>
<ul>
<li><p><a href="https://github.com/abalone0204/Clairvoyance" target="_blank" rel="external">gui</a>：Chrome extension 的 UI</p>
</li>
<li><p><a href="https://github.com/abalone0204/serverless-clairvoyance" target="_blank" rel="external">serverless-clv-backend</a></p>
<ul>
<li>處理後端的資料</li>
</ul>
</li>
<li><p><a href="https://github.com/abalone0204/serverless-clv-oauth" target="_blank" rel="external">serverless-clv-auth</a></p>
<ul>
<li><p>問題：chrome 的插件是明碼的，假如要在上面做認證，就要在 chrome 上面直接放 secret key，這樣做一點都不 secret</p>
</li>
<li><p>解法：開了一個 serverless 的 api 專門來做這件事情，在 repo 的 README 裡面蠻詳細的紀錄如何做到，所以這篇裡面不會贅述這一點。</p>
</li>
</ul>
</li>
</ul>
<p>這裡畫了個很粗略的圖，看一下會比較有概念：</p>
<blockquote>
<p>clv = clairvoyance</p>
</blockquote>
<p><img src="https://raw.githubusercontent.com/abalone0204/Clairvoyance/master/clv-arc.png" alt="clv arc"></p>
<p>其實 backend 就是處理留言、工作、使用者，</p>
<p>而我並不想自己維護一台機器做這些事情，</p>
<p>所以我用了 serverless 的方式去解決，</p>
<p>想要瞭解更多關於 serverless 基礎的人，</p>
<p>可以看一下這篇舊文：<a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/" target="_blank" rel="external">淺析 serverless 架構</a></p>
<p>是我剛學習 serverless 時做的筆記，</p>
<p>同時也是繁體中文裡面最詳細的新手教學。</p>
<blockquote>
<p>就算簡體中文其實也是啦</p>
</blockquote>
<p>前端的話，有一些比較討厭的部分就是非同步的處理，</p>
<p>但這裡 saga 很簡單的幫我 handle 處理好了，</p>
<p>而且還給了相當好的測試性，</p>
<p>這點非常非常重要，</p>
<p>測試省掉了我不少 debug 的時間。</p>
<blockquote>
<p>中間大概重構了一兩次</p>
</blockquote>
<h1 id="Back-end"><a href="#Back-end" class="headerlink" title="Back-end"></a>Back-end</h1><p>首先就是要先訂好 schema，以及各個資料相互的關聯性，</p>
<p>這裡有用到 GSI 來建立查詢的 index，</p>
<p>雖然我們會用公司名稱以及職缺名稱來查詢，</p>
<p>但這兩樣東西都不適合拿來當作 Primary Key，</p>
<p>我覺得看完這篇官方的<a href="https://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/BestPractices.html" target="_blank" rel="external">最佳實踐</a>，</p>
<p>就已經差不多能掌握怎樣去設計一個拿 dynamodb 當作資料庫服務的心法，</p>
<p>剩下的只是把資料長怎樣想清楚而已。</p>
<blockquote>
<p>使用 DyanmoDB 時，會考慮到資料一致性的問題。</p>
<p>但畢竟這不是一個非常要求即時性的服務，</p>
<p>所以我對於最終一致性這件事情是有相當高的容忍度的 :D</p>
<p>什麼是最終一致性呢？</p>
<p>就是我們不保證每個節點讀取資料時，資料都會是相同的，（強一致性）</p>
<p>但隨著時間過去，每個節點上的數據會回歸一致。</p>
<p>這只是很粗略的說法，接下來幾個禮拜可能會寫一些和分散式有關的，</p>
<p>就會提到這一點。因為一致性對於分散式運算來說一直是一個很頭痛的問題。</p>
</blockquote>
<h1 id="Front-end"><a href="#Front-end" class="headerlink" title="Front-end"></a>Front-end</h1><p>我選擇使用 React 及 Redux 的原因蠻單純的，</p>
<p>因為我最近常在工作上用到它們。</p>
<ul>
<li><p>Reactjs+ CSS Module</p>
<ul>
<li><p>CSS 的命名一直是一個很難解的問題，這裡我的想法是無論再怎麼有效的規範，都是軟性的，CSS 的特性讓全域污染這件事情變得難以避免。但 CSS Module 卻可以讓所有的 class 都變成 local 的，</p>
</li>
<li><p>React 以 component 為主的開發模式，跟 CSS Module 搭配起來相當不錯</p>
</li>
</ul>
</li>
<li><p>Redux Saga</p>
<ul>
<li><p>處理非同步的資料流（像是從 backend fetch 資料）</p>
</li>
<li><p>有些 UI 上的 transaction 都可以在 saga 處理</p>
</li>
<li><p>使用 saga 的重點是「測試」，effect 的概念讓測試變得簡單很多，少了各種 mock</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>其實這裡本來想用 Rx 搞定，但工作上真的用了太多 Saga，現在有點回不去了⋯⋯</p>
<p>假如你未曾瞭解過 saga，可以看一下我的這篇文章 <a href="http://abalone0204.github.io/2016/05/14/redux-saga/" target="_blank" rel="external">Saga Pattern 在前端的應用</a> </p>
</blockquote>
<h1 id="UX"><a href="#UX" class="headerlink" title="UX"></a>UX</h1><p>這裡不是要說有著多精美的 UI，</p>
<p>是自己開發時，總覺得我開發的東西，真他媽怎麼用怎麼順手啊！</p>
<p>實際上別人一看到時，卻常常完全不是這麼一回事。</p>
<p>最好的方法就是請朋友幫忙用一下，</p>
<p>然後什麼都不要跟他說，也不要有任何預先的假設。</p>
<blockquote>
<p>沒錯，就算你有說明書，User 就是死都不會看（我也是）</p>
</blockquote>
<p>很常發生的事情就是 User 完全不知道你想幹什麼，</p>
<p>留言區塊那邊一開始就是這麼一回事，</p>
<p>所以如果有人說你做的東西「太工程師」、「太 geek」，</p>
<p>大概就是這個樣子。</p>
<blockquote>
<p>感謝我的幾個被我巴著幫忙測試的朋友。 <code>m (_ _) m</code></p>
</blockquote>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>目前只支援 1111 以及 104，</p>
<p>yes123 的 url，有那麼一點難以預測⋯⋯</p>
<p>不過也是因為這個 Project ，可以感覺到各個求職平台是否用心，</p>
<p>未來要加入的功能應該有以下幾項：</p>
<ul>
<li><p>個人留言職缺的追蹤</p>
</li>
<li><p>Facebook 粉絲頁的機器人</p>
<ul>
<li>幫忙發布熱門討論的職缺</li>
</ul>
</li>
<li><p>重構</p>
<ul>
<li>比較有問題的應該是建立職缺那裡的 code 很醜 XD</li>
</ul>
</li>
</ul>
<p>其實我知道這個 beta 版本還有許多可以更好的地方，</p>
<p>不過我更想瞭解這個插件是不是真的能解決一些問題，</p>
<p>所以就先釋出這個 beta 版了！</p>
<p>假如有什麼想問的問題也可以留言、發 issue 或直接跟問我，</p>
<p>對我來說，不只是想 build 一個小小的插件，</p>
<p>我想造出一個對求職者來說真正透明友善的環境，</p>
<p>我知道一定會有蠻多人覺得這真是 too young, too naive 的想法，</p>
<p>不過不試試看，怎麼會知道結果怎樣勒？</p>
<ul>
<li>下載位置：<a href="https://chrome.google.com/webstore/detail/clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A/mdneakdlnoidknagkamfeambdefhppbi?hl=zh-TW&amp;gl=TW" target="_blank" rel="external">Clairvoyance - 求職天眼通</a></li>
</ul>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="https://github.com/css-modules/css-modules" target="_blank" rel="external">CSS Module</a></p>
</li>
<li><p><a href="https://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/BestPractices.html" target="_blank" rel="external">DynamoDB 的最佳實踐</a>，</p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;我寫了一個 chrome 的插件，&lt;/p&gt;
&lt;p&gt;能夠讓求職者在人力銀行的職缺下面留言討論。&lt;/p&gt;
&lt;p&gt;聽起來是很平常的需求，不過各大人力銀行就是不做這個功能，&lt;/p&gt;
&lt;p&gt;所以我想看看假如有這個功能會不會對求職有正向的幫助。&lt;/p&gt;
&lt;p&gt;下載的連結在這裡： &lt;a href=&quot;https://chrome.google.com/webstore/detail/clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A/mdneakdlnoidknagkamfeambdefhppbi?hl=zh-TW&amp;amp;gl=TW&quot;&gt;Clairvoyance - 求職天眼通&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;目前還在 beta 階段，可能會有些 bug，&lt;/p&gt;
&lt;p&gt;可以到&lt;a href=&quot;https://www.facebook.com/Clairvoyance-%E6%B1%82%E8%81%B7%E5%A4%A9%E7%9C%BC%E9%80%9A-1084564708284768&quot;&gt;粉絲頁&lt;/a&gt;留言，&lt;/p&gt;
&lt;p&gt;或是在 &lt;a href=&quot;https://github.com/abalone0204/Clairvoyance&quot;&gt;github&lt;/a&gt; 上直接發 issue。&lt;/p&gt;
&lt;p&gt;下面就來筆記一下為什麼要做這件事，以及怎麼做到的。&lt;/p&gt;
&lt;p&gt;用的技術就是以下列的這些&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;front-end: reactjs、redux、redux-saga&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;back-end: aws-lambda, dynamodb, serverless-framework&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;目前只支援 104 和 1111，至於 yes123，後面會再提到為什麼暫時沒做。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;下面來簡介一下是怎麼做出來、以及為什麼要做。&lt;/p&gt;
    
    </summary>
    
    
      <category term="serverless" scheme="http://abalone0204.github.com/tags/serverless/"/>
    
      <category term="chrome-extension" scheme="http://abalone0204.github.com/tags/chrome-extension/"/>
    
      <category term="career" scheme="http://abalone0204.github.com/tags/career/"/>
    
      <category term="job" scheme="http://abalone0204.github.com/tags/job/"/>
    
  </entry>
  
  <entry>
    <title>實作 Serverless 的 facebook messenger bot</title>
    <link href="http://abalone0204.github.com/2016/05/29/sls-fb-bot/"/>
    <id>http://abalone0204.github.com/2016/05/29/sls-fb-bot/</id>
    <published>2016-05-29T11:55:40.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>上禮拜簡單介紹了一下 serverless 的起手式後，</p>
<p>我想再舉個更接近實際應用的例子，</p>
<p>儘管並不是所有的應用都適合 serverless 的架構，</p>
<p>但聊天機器人(chat bot)是一個相當好的例子，</p>
<p>且讓我稍後再說明為什麼。</p>
<p>今天就結合一下很實用的粉絲頁回覆機器人以及 serverless 。</p>
<blockquote>
<p>你可以把聊天機器人想成是你粉絲頁自動回覆的員工</p>
<p>或是進行一些簡單的操作</p>
<p>而聊天機器人流行起來的原因正是因為 mobile 裝置上的介面，</p>
<p>並不能滿足於現代人操作的所有需求，</p>
<p>聊天的介面解放了我們在小框框裡做事的限制。</p>
<p>或者是你是小小公司的開發者，需要一個助理來幫你做很無腦或繁瑣的事情，</p>
<p>再講下去可能要一篇了，如果你對這個主題有興趣，</p>
<p>可以看看 <a href="https://wanqu.co/blog/2015-05-24-behind-the-scenes.html" target="_blank" rel="external">灣區日報是如何運作的</a></p>
</blockquote>
<a id="more"></a> 
<h1 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h1><p><img src="http://i.imgur.com/JmVfjQ5.png" alt="bot"></p>
<p>微軟、line、slack 都出了，</p>
<p>臉書當然也要 bot 來幫我們處理一些事情。</p>
<blockquote>
<p>相當不建議直接照著貼，可以先看看我的前一篇文章，</p>
<p>至少現在敢大膽的說是目前最詳盡的 serverless 繁體中文入門教學：</p>
<p><a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/" target="_blank" rel="external">淺析 serverless 架構與實作</a></p>
</blockquote>
<p>這一篇筆記裡面會介紹如何把一個 facebook 粉絲專頁的 bot，</p>
<p>用 serverless 的方式架起來。</p>
<p>這個 bot 能夠：</p>
<ul>
<li><p>處理粉絲專頁接收到訊息的 events</p>
</li>
<li><p>執行對應的動作或回傳訊息</p>
</li>
</ul>
<p>為了保持簡單，並且專注在 messenger bot 本身，</p>
<p>我不會用到其他服務的 events，像是 DynamoDB 或是 S3 之類的，</p>
<p>但其實只要能掌握收訊息，以及對應訊息做出動作，</p>
<p>基本上就掌握了搭配其他功能的 interface 了 :D</p>
<p>假如你是個懶得看文章的人，我一樣把 code 放在 github 上面了：</p>
<ul>
<li><a href="https://github.com/abalone0204/serverless-facebook-messenger-bot-starter" target="_blank" rel="external">serverless-facebook-messenger-bot-starter</a></li>
</ul>
<p>有幫助到你的話給星星打賞，有問題的話也歡迎提 issue 或直接告訴我。</p>
<h1 id="Catalogue"><a href="#Catalogue" class="headerlink" title="Catalogue"></a>Catalogue</h1><ul>
<li><p><a href="#Why-serverless">Why serverless</a></p>
</li>
<li><p><a href="#Implementation">Implementation</a></p>
<ul>
<li><p><a href="#申請作業">申請作業</a></p>
</li>
<li><p><a href="#Serverless-環境建構">Serverless 環境建構</a></p>
</li>
<li><p><a href="#https">https</a></p>
</li>
<li><p><a href="#Deployment-部署">Deployment 部署</a></p>
</li>
<li><p><a href="#Subscribe-to-fan-page">Subscribe to fan page</a></p>
</li>
<li><p><a href="#Reply-回覆訊息">Reply - 回覆訊息</a></p>
</li>
<li><p><a href="#更複雜的回覆訊息格式">更複雜的回覆訊息格式</a></p>
</li>
</ul>
</li>
<li><p><a href="#Conclusion">Conclusion</a></p>
</li>
</ul>
<h1 id="Why-serverless"><a href="#Why-serverless" class="headerlink" title="Why serverless"></a>Why serverless</h1><p>為什麼我認為 chat bot 是一個非常適合 serverless 架構的運用？</p>
<p>想想我們平常聊天，訊息也都不會馬上回嘛！</p>
<p>所以我們其實不需要那麼真正的「real time」，</p>
<p>而且只有在有人丟訊息時，lambda 才會幫我們運算，</p>
<p>省下了不少機器閒置在那的費用。</p>
<ul>
<li><p>對於延遲時間的容忍度高：</p>
<ul>
<li>容忍了 serverless 的缺點</li>
</ul>
</li>
<li><p>有使用才收費：</p>
<ul>
<li>省錢、加上使用情境相當符合</li>
</ul>
</li>
<li><p>簡單的運算</p>
<ul>
<li><p>AWS lambda 運算時間不能超過五分鐘，否則會被強制結束，但這種簡單的文字回覆，通常處理不會超過五分鐘…吧</p>
</li>
<li><p>當然如果你要跑什麼類神經網路，那我會建議那些運算邏輯可以放在真正的 server 上</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>題外話是這篇 <a href="http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/" target="_blank" rel="external">面試遇到 用 deep learning 解 fizzbuzz</a></p>
<p>看到後面超好笑 XD</p>
</blockquote>
<ul>
<li><code>https</code>: facebook 的 bot 會需要有 https ，通常可以透過 CloudFlare 免費申請一個，但假如你使用 lambda 的話，原生給你的連結就是 https 的。</li>
</ul>
<h1 id="Implementation"><a href="#Implementation" class="headerlink" title="Implementation"></a>Implementation</h1><p>同樣的，因為我認為介面隨時會改變，</p>
<p>所以我不做截圖的 step by step 。</p>
<h2 id="申請作業"><a href="#申請作業" class="headerlink" title="申請作業"></a>申請作業</h2><ul>
<li>申請 facebook app、一個要用到的粉絲頁</li>
</ul>
<blockquote>
<p>申請的類型有 ios、android 什麼的，</p>
<p>先選網頁，然後網址可以亂打一通，這對之後沒有影響</p>
</blockquote>
<ul>
<li><p>到 facebook 的 app 控制台</p>
</li>
<li><p>在控制列選擇新增產品</p>
</li>
<li><p>選 Messenger Expression</p>
</li>
<li><p>會看到一個新的 Messenger 跑出來了，選它</p>
</li>
<li><p>接著可以選擇你要把你的 bot 安置的粉絲頁，選擇後會得到一個權杖。</p>
</li>
</ul>
<blockquote>
<p>我覺得權杖是一個一聽會覺得「啥？」的命名，</p>
<p>不過它的意思就是你能夠讓 bot 藉由這個「權杖」，</p>
<p>取得在你粉絲頁發文或是發訊息的「權利」</p>
</blockquote>
<ul>
<li>接下來選擇 setup webhooks</li>
</ul>
<blockquote>
<p>什麼是 Webhook？</p>
<p>你可以把它看成是一種 back-end 到 back-end 之間的通知，</p>
<p>最常見的例子就是 CI 了</p>
<p>e.q：今天在 github 上送了一個 commit，</p>
<p>webhook 就會把這邊更新的訊息帶去給 CI server，</p>
<p>CI server 收到後就會開始跑後續的流程</p>
<p>hook，就是鉤子，在網路上把訊息以及收到訊息要執行的行為鉤住，</p>
<p>帶到別的地方(callback url)去的就是 webhook</p>
</blockquote>
<ul>
<li>到這裡我們就可以去設置一下環境了</li>
</ul>
<h2 id="Serverless-環境建構"><a href="#Serverless-環境建構" class="headerlink" title="Serverless 環境建構"></a>Serverless 環境建構</h2><p>為了驗證我們的 callback 是不是正確的，</p>
<p>facebook 這邊會去做驗證，</p>
<p>確認它送來的<code>hub.verify_token</code>跟你粉絲專頁的權杖一樣時，</p>
<p>就會把 request 中的<code>hub.challenge</code>送回來。</p>
<blockquote>
<p>這裡有個小雷是我們要送回來的值是 integer，不是 string</p>
</blockquote>
<p>官方的例子大概長這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Node.js Example</span></div><div class="line">app.get(<span class="string">'/webhook'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</div><div class="line">  <span class="keyword">if</span> (req.query[<span class="string">'hub.verify_token'</span>] === &lt;YOUR_VERIFY_TOKEN&gt;) &#123;</div><div class="line">    res.send(req.query['hub.challenge']);</div><div class="line">  &#125; else &#123;</div><div class="line">    res.send('Error, wrong validation token');    </div><div class="line">  &#125;</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>接著就一如往常的開一個 serverless 專案，</p>
<p>建立一個 handler function。</p>
<blockquote>
<p>參考這邊<a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/#Setup-開發環境的建置" target="_blank" rel="external">serverless setup 開發環境的建置</a></p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">serverless function create functions/bot</div></pre></td></tr></table></figure>
<p>然後在來看程式的進入點：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports.handler = <span class="function"><span class="keyword">function</span>(<span class="params">event, context</span>) </span>&#123;</div><div class="line">    </div><div class="line">    <span class="keyword">const</span> operation = event.operation</div><div class="line">    </div><div class="line"></div><div class="line">    <span class="keyword">switch</span> (operation) &#123;</div><div class="line">        <span class="keyword">case</span> <span class="string">'verify'</span>:</div><div class="line">            <span class="keyword">const</span> secret = event.secret</div><div class="line">            <span class="keyword">const</span> verifyToken = event[<span class="string">"verify_token"</span>]</div><div class="line">            <span class="keyword">if</span> (secret === verifyToken) &#123;</div><div class="line">                context.succeed(<span class="built_in">parseInt</span>(event[<span class="string">"challenge"</span>]))</div><div class="line">            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unmatch'</span>))</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">break</span></div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unrecognized operation "'</span> + operation + <span class="string">'"'</span>))</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p><code>operation</code>這個屬性是為了後續的動作，</p>
<p>不管對這個 callback url 呼叫東西，</p>
<p>都會進入這個 <code>handler.js</code> 但是我們必須有不同的動作，</p>
<p>我認為這裡都是屬於在 bot 執行動作的邏輯之下，</p>
<p>所以將它們放在同一個 handler.js 中，你完全可以有不同的編排方式 :)</p>
</blockquote>
<p><code>event</code> 裡的東西哪裡來呢？</p>
<p><code>event</code>其實就是 request，serverless 是個 event-driven 的架構，</p>
<p>我們可以在 <code>s-templates</code> 裡面去設置 template，</p>
<p>這裡有個 tricky 的問題，就是要怎麼處理權杖？</p>
<p>有兩種方法，</p>
<p>一種是在本地端用 module export 的方式解決，</p>
<p>另一種則是用 aws 的 env variable。</p>
<p>首先先看用 aws 的 variable 怎麼解決</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">sls variables set -k KEY -v VALUE -s STAGE -r REGION</div></pre></td></tr></table></figure>
<p>然後我們就可以在 template 中使用 ${KEY} 的語法來拿到 variable，</p>
<p>這裡要注意你是不是在每個不一樣的 stage 以及 region 都設置了 variable。</p>
<p>要檢查的話可以進去自動生成的 <code>_meta</code> 資料夾看。</p>
<blockquote>
<p><code>_meta</code> 是自動被 git 給忽略的</p>
</blockquote>
<p>接下來到 <code>s-function.json</code> 裡面設定 request 的 template，</p>
<p>把 callback</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">"requestTemplates": "$$&#123;apiGetCallbackTemplate&#125;",</div></pre></td></tr></table></figure>
<p>再來看 <code>template</code> 長什麼樣子：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="attr">"apiGetCallbackTemplate"</span>: &#123;</div><div class="line">        <span class="attr">"application/json"</span>: &#123;</div><div class="line">            <span class="attr">"operation"</span>: <span class="string">"verify"</span>,</div><div class="line">            <span class="attr">"secret"</span>: <span class="string">"$&#123;fb_secret_key&#125;"</span>,</div><div class="line">            <span class="attr">"verify_token"</span>: <span class="string">"$input.params('hub.verify_token')"</span>,</div><div class="line">            <span class="attr">"challenge"</span>:<span class="string">"$input.params('hub.challenge')"</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>假如你還不太熟悉 serverless，</p>
<p>這裡就是在描述剛剛 <code>handler</code> 中<code>event</code>的長相：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"secret"</span>: <span class="string">"FB_SECRET_KEY"</span>,</div><div class="line">    <span class="string">"verify_token"</span>: <span class="string">"VERIFY_TOKEN"</span>,</div><div class="line">    <span class="string">"challenge"</span>:<span class="string">"CHALLENGE_CODE"</span>    </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>你可能會覺得對方如果知道你的 callback url 那不就顯示出你的 secret 了嗎？</p>
<p>其一是這個連結不會對外，而你也可以限制 request 的來源，</p>
<p>而這也是為什麼要加上這一段的原因：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (secret === verifyToken) &#123;</div><div class="line">    context.succeed(<span class="built_in">parseInt</span>(event[<span class="string">"challenge"</span>]))</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unmatch'</span>))</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果沒有 secret 跟 verifyToken 沒有相等的話，</p>
<p>會直接結束，並且返回 error。</p>
<p>假如你不熟悉 aws 也不想接受這樣的做法的話，</p>
<p>你可以在本地新建一個<code>secret.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">export</span> <span class="keyword">const</span> secret = <span class="string">"FB_SECRET_KEY"</span></div></pre></td></tr></table></figure>
<p>然後把這支檔案 <code>.gitignore</code> 就行了，</p>
<p>不過這其實算是一種 hack 的方式，並不是一個很漂亮的做法。</p>
<h2 id="https"><a href="#https" class="headerlink" title="https"></a>https</h2><p>假如你要自己 host 一個服務來放 bot 的話，</p>
<p>還要去額外申請 https，但如果你用 serverless，</p>
<p>搭配 api gateway 就直接幫你避免掉了這個問題</p>
<h2 id="Deployment-部署"><a href="#Deployment-部署" class="headerlink" title="Deployment 部署"></a>Deployment 部署</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">serverless dash deploy</div></pre></td></tr></table></figure>
<p><code>function - callback</code> 跟 <code>endpoint - callback</code> 都選起來，</p>
<p>部署上去之後會返回一個網址，</p>
<p>當我們對這個網址送一個帶有 http method 為 GET 的 Requst 時，</p>
<p>就會進入我們剛剛看到的 <code>handler.js</code> 中執行東西。</p>
<ul>
<li>setup wehook</li>
</ul>
<p>最後就是把返回的那個網址貼在 callback url 那裡，</p>
<p>再把權杖給貼上去：</p>
<p><img src="https://scontent-tpe1-1.xx.fbcdn.net/t39.2178-6/12057143_211110782612505_894181129_n.png" alt="webhook setup"></p>
<p>(下面的欄位我都會全勾起來 XD)</p>
<p>正確的方式應該是在 back-end 上放上 secret（這裡指權杖），</p>
<p>facebook 會送個 request 到你的 callbakc url 去，</p>
<p>並且看看在 params 中的 <code>hub.verify_token</code> 是不是等於你放上去的 secret，</p>
<p>如果是的話，再把 params 中的 <code>hub.challenge</code> 當作 response 丟回來，</p>
<p>facebook 就會判定你這個 webhook 通過認證，</p>
<p>後續才能繼續進行下去。</p>
<h2 id="Subscribe-to-fan-page"><a href="#Subscribe-to-fan-page" class="headerlink" title="Subscribe to fan page"></a>Subscribe to fan page</h2><p>有兩種方法可以去「監聽」粉絲專頁收到訊息的 event。</p>
<ul>
<li>以在 facebook app 操作的後台上選擇你要訂閱哪個粉絲專頁收到的訊息</li>
</ul>
<p>假如你寫過 rx，會知道 subscribe 可以監聽 event 是否進來，</p>
<p>接著我們會去做對應的動作。</p>
<p>假如你沒寫過 rx，<del>那你應該去學一下</del>。</p>
<p>簡單說就是當我們監聽的粉絲專頁收到訊息時，</p>
<p>剛剛設定的 webhook 會送一個 post method 的 request，</p>
<p>而我們可以做出對應的行為，這裡通常就是返回一些訊息，</p>
<p>facebook 的 messenger 還可以回傳附件之類的。</p>
<p>官方給的 demo code 長這個樣子，先只要大略掃過一遍就好，</p>
<p>後面會更詳細解說這裡在幹什麼，</p>
<p>畢竟第一次看到的時候我也不知道這到底在幹嘛：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">app.post(<span class="string">'/webhook/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</div><div class="line">  messaging_events = req.body.entry[<span class="number">0</span>].messaging; <span class="comment">// 拿到 request 中的訊息</span></div><div class="line">  <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; messaging_events.length; i++) &#123;</div><div class="line">    event = req.body.entry[<span class="number">0</span>].messaging[i];</div><div class="line">    sender = event.sender.id; <span class="comment">// 送訊息人的 id</span></div><div class="line">    <span class="keyword">if</span> (event.message &amp;&amp; event.message.text) &#123;</div><div class="line">      text = event.message.text;</div><div class="line">      <span class="comment">// Handle a text message from this sender</span></div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  res.sendStatus(<span class="number">200</span>);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>唯一知道的是我們送訊息時，會丟一個 POST reqeust 給 webhook，</p>
<p>雖然最後得到了一個 <code>sender</code>（訊息的發送者），以及傳送的<code>text</code>訊息，</p>
<p>還是有點搞不懂到底在做什麼，像遇到這種情形時，</p>
<p>把東西 log 出來就對了。</p>
<p>所以第一個目標就是來觀察一下 facebook 到底會送一些什麼東西過來。</p>
<p>先把 post method 的 template 建出來</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"apiPostCallbackTemplate"</span>: &#123;</div><div class="line">        <span class="string">"application/json"</span>: &#123;</div><div class="line">            <span class="string">"operation"</span>: <span class="string">"reply"</span>,</div><div class="line">            <span class="string">"body"</span>: <span class="string">"$input.json('$')"</span></div><div class="line">        &#125;        </div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>handler.js</code> 中其實 succeed 傳回的結果是什麼都沒差，</p>
<p>重要的是我們能看到傳過來的 request，要把它 log 出來</p>
<p>這是我們在寫 code 時常做的 debug 方法，</p>
<p>就算 serverless 其實也沒有不同 XD</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// inside the handler function</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">display</span>(<span class="params">object</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="built_in">JSON</span>.stringify(object, <span class="literal">null</span>, <span class="number">2</span>)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="built_in">console</span>.log(<span class="string">'Event: '</span>, display(event))</div><div class="line"><span class="keyword">switch</span>(operation) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="string">'reply'</span>:</div><div class="line">        context.succeed(event)</div><div class="line">        <span class="keyword">break</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著我們到 facebook 上丟給我們剛剛創的粉絲專頁一些訊息，</p>
<p>假設我們密他然後說個：「Hello bot 」</p>
<p>到 AWS Cloud Watch 上面就可以看到返回的 body 長這個樣子，</p>
<p>可以快速的掃過一次（大寫的是是代表一些 id，你懂的）：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"object"</span>: <span class="string">"page"</span>,</div><div class="line">    <span class="string">"entry"</span>: [</div><div class="line">        &#123;</div><div class="line">            <span class="string">"id"</span>: ENTRY_ID,</div><div class="line">            <span class="string">"time"</span>: <span class="number">1464447058752</span>,</div><div class="line">            <span class="string">"messaging"</span>: [</div><div class="line">                &#123;</div><div class="line">                    <span class="string">"sender"</span>: &#123;</div><div class="line">                        <span class="string">"id"</span>: SENDER_ID</div><div class="line">                    &#125;,</div><div class="line">                    <span class="string">"recipient"</span>: &#123;</div><div class="line">                        <span class="string">"id"</span>: RECIPIENT_ID</div><div class="line">                    &#125;,</div><div class="line">                    <span class="string">"timestamp"</span>: <span class="number">1464447058667</span>,</div><div class="line">                    <span class="string">"message"</span>: &#123;</div><div class="line">                        <span class="string">"mid"</span>: <span class="string">"mid.1464447058507:7548866c81ec168b21"</span>,</div><div class="line">                        <span class="string">"seq"</span>: <span class="number">4</span>,</div><div class="line">                        <span class="string">"text"</span>: <span class="string">"Hello bot"</span></div><div class="line">                    &#125;</div><div class="line">                &#125;</div><div class="line">            ]</div><div class="line">        &#125;</div><div class="line">    ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>看到這個之後，比較能知道 facebook 的 sample code 在幹嘛，</p>
<p>而不是單純的 copy and paste。</p>
<p>再上一次 sample code 來對照一下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">app.post(<span class="string">'/webhook/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</div><div class="line">  messaging_events = req.body.entry[<span class="number">0</span>].messaging;</div><div class="line">  <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; messaging_events.length; i++) &#123;</div><div class="line">    event = req.body.entry[<span class="number">0</span>].messaging[i];</div><div class="line">    sender = event.sender.id;</div><div class="line">    <span class="keyword">if</span> (event.message &amp;&amp; event.message.text) &#123;</div><div class="line">      text = event.message.text;</div><div class="line">      <span class="comment">// Handle a text message from this sender</span></div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">  res.sendStatus(<span class="number">200</span>);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>看起來 facebook 的工程師為了保留開發上的彈性，</p>
<p>所以加上了一些目前看起來有點冗的東西，</p>
<p>我們可以選擇一開始就把 <code>messaging_events</code> 在 template 裡面拿出來，</p>
<p>或者是一樣拿回整個 body，不過為了說明方便，</p>
<p>還是照它原本的格式走。</p>
<p>總之，理解後就能開始試著把它改成 serverless 的模式了：</p>
<p>（真的是幾乎長得一模一樣）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">switch</span> (operation) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="string">'reply'</span>:</div><div class="line">    <span class="keyword">const</span> messagingEvents = event.body.entry[<span class="number">0</span>].messaging</div><div class="line">    messagingEvents.forEach((messagingEvent) =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> sender = messagingEvent.sender.id</div><div class="line">        <span class="keyword">if</span> (messagingEvent.message &amp;&amp; messagingEvent.message.text) &#123;</div><div class="line">            <span class="keyword">const</span> text = messagingEvent.message.text</div><div class="line">            <span class="comment">// Handle a text message from this sender</span></div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">break</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>為什麼要拿 <code>sender</code> 以及 <code>text</code>呢？</p>
<p>原因就是待會回覆訊息會需要用到。</p>
<h2 id="Reply-回覆訊息"><a href="#Reply-回覆訊息" class="headerlink" title="Reply - 回覆訊息"></a>Reply - 回覆訊息</h2><p>回覆訊息要用到我們之前的能登入粉絲頁的「密碼權杖」，</p>
<p>假如你是用 variable 解決的話，這部分會簡單很多。</p>
<p>只要把剛剛在 callback url 的 <code>fb_secret_key</code> copy 過去就好了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="string">"apiPostCallbackTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"secret"</span>: <span class="string">"$&#123;fb_secret_key&#125;"</span>,</div><div class="line">        <span class="string">"operation"</span>: <span class="string">"reply"</span>,</div><div class="line">        <span class="string">"body"</span>: <span class="string">"$input.json('$')"</span></div><div class="line">    &#125;        </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>一樣先來看一下 sample code 是怎麼做的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> token = <span class="string">"&lt;page_access_token&gt;"</span>;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">sendTextMessage</span>(<span class="params">sender, text</span>) </span>&#123;</div><div class="line">  messageData = &#123;</div><div class="line">    text:text</div><div class="line">  &#125;</div><div class="line">  request(&#123;</div><div class="line">    url: <span class="string">'https://graph.facebook.com/v2.6/me/messages'</span>,</div><div class="line">    qs: &#123;access_token:token&#125;,</div><div class="line">    method: <span class="string">'POST'</span>,</div><div class="line">    json: &#123;</div><div class="line">      recipient: &#123;id:sender&#125;,</div><div class="line">      message: messageData,</div><div class="line">    &#125;</div><div class="line">  &#125;, <span class="function"><span class="keyword">function</span>(<span class="params">error, response, body</span>) </span>&#123;</div><div class="line">    <span class="keyword">if</span> (error) &#123;</div><div class="line">      <span class="built_in">console</span>.log(<span class="string">'Error sending message: '</span>, error);</div><div class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (response.body.error) &#123;</div><div class="line">      <span class="built_in">console</span>.log(<span class="string">'Error: '</span>, response.body.error);</div><div class="line">    &#125;</div><div class="line">  &#125;);</div><div class="line">&#125;</div><div class="line"><span class="comment">// 實際傳送訊息</span></div><div class="line">sendTextMessage(sender, <span class="string">"Text received, echo: "</span>+ text.substring(<span class="number">0</span>, <span class="number">200</span>));</div></pre></td></tr></table></figure>
<p>沒錯，這裡根本就可以直接拿來用了，</p>
<p>我們先求有再求好：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports.handler = <span class="function"><span class="keyword">function</span>(<span class="params">event, context</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> operation = event.operation</div><div class="line">    <span class="keyword">const</span> secret = event.secret</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">sendTextMessage</span>(<span class="params">sender, text</span>) </span>&#123;</div><div class="line">        <span class="keyword">const</span> messageData = &#123;text: text&#125;</div><div class="line">        request(&#123;</div><div class="line">            url: <span class="string">'https://graph.facebook.com/v2.6/me/messages'</span>,</div><div class="line">            qs: &#123;</div><div class="line">                access_token: secret</div><div class="line">            &#125;,</div><div class="line">            method: <span class="string">'POST'</span>,</div><div class="line">            json: &#123;</div><div class="line">                recipient: &#123;</div><div class="line">                    id: sender</div><div class="line">                &#125;,</div><div class="line">                message: messageData,</div><div class="line">            &#125;</div><div class="line">        &#125;, (error, response, body) =&gt; &#123;</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'GET response'</span>, response);</div><div class="line">            context.succeed(response);</div><div class="line">            <span class="keyword">if</span> (error) &#123;</div><div class="line">                context.fail(<span class="string">'Error sending message: '</span>, error);</div><div class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (response.body.error) &#123;</div><div class="line">                context.fail(<span class="string">'Error: '</span>, response.body.error);</div><div class="line">            &#125;</div><div class="line">        &#125;)</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="keyword">switch</span> (operation) &#123;</div><div class="line">        <span class="keyword">case</span> <span class="string">'reply'</span>:</div><div class="line">            <span class="keyword">const</span> messagingEvents = event.body.entry[<span class="number">0</span>].messaging;</div><div class="line">            messagingEvents.forEach((messagingEvent) =&gt; &#123;</div><div class="line">                <span class="keyword">const</span> sender = messagingEvent.sender.id</div><div class="line">                <span class="keyword">if</span> (messagingEvent.message &amp;&amp; messagingEvent.message.text) &#123;</div><div class="line">                    <span class="keyword">const</span> text = messagingEvent.message.text;</div><div class="line">                    sendTextMessage(sender, <span class="string">"Text received, echo: "</span>+ text.substring(<span class="number">0</span>, <span class="number">200</span>))</div><div class="line">                &#125;</div><div class="line">            &#125;)</div><div class="line">            <span class="keyword">break</span></div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unrecognized operation "'</span> + operation + <span class="string">'"'</span>))</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在執行 <code>sendTextMessage</code> 時，</p>
<p>裡面的 <code>request</code> 會是非同步的，</p>
<p>也就是說在後續的流程裡如果你讓整個 function 提早結束的話，</p>
<p>訊息將不會被傳送。</p>
<p>不過 user 一進來，其實不會知道 bot 有哪些功能，</p>
<p>我們可以設定對話剛開始的開場白，只要在執行這行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">curl -X POST -H &quot;Content-Type: application/json&quot; -d &apos;&#123;</div><div class="line">  &quot;setting_type&quot;:&quot;call_to_actions&quot;,</div><div class="line">  &quot;thread_state&quot;:&quot;new_thread&quot;,</div><div class="line">  &quot;call_to_actions&quot;:[</div><div class="line">    &#123;</div><div class="line">      &quot;message&quot;:&#123;</div><div class="line">        &quot;text&quot;:&quot;Hi, 歡迎來到 Serverless Maniac。我是機器人，輸入 help 來看有什麼指令可以用吧&quot;</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">  ]</div><div class="line">&#125;&apos; &quot;https://graph.facebook.com/v2.6/&lt;PAGE_ID&gt;/thread_settings?access_token=&lt;FB_SECRET_KEY&gt;&quot;</div></pre></td></tr></table></figure>
<blockquote>
<p><code>FB_SECRET_KEY</code>就是前面提到的密碼權杖，<code>PAGE_ID</code> 是你粉絲頁對應的 id，</p>
</blockquote>
<p>出來結果大概就是這樣子</p>
<p><img src="http://i.imgur.com/hruiXeO.jpg" alt="demo"></p>
<h2 id="更複雜的回覆訊息格式"><a href="#更複雜的回覆訊息格式" class="headerlink" title="更複雜的回覆訊息格式"></a>更複雜的回覆訊息格式</h2><ul>
<li><p>facebook 也提供一些更 fancy 的訊息格式 </p>
</li>
<li><p>針對特定的訊息去做動作</p>
</li>
</ul>
<p>比起一般的小編回覆訊息，這裡能夠藉由 messenger platform 提供的 API，</p>
<p>回覆一個更像 app 的訊息模板、提供更棒的 UX，</p>
<p>啊！這樣講好抽象，直接看一下成果的話大概是這樣子：</p>
<p><img src="https://media.giphy.com/media/xT4uQAs24rrYQDjNuw/giphy.gif" alt="struc demo"></p>
<blockquote>
<p>沒錯，就是做了一個自己 blog 的 feeds</p>
</blockquote>
<p>剛剛在 <code>sendTextMessage</code> 裡面會把 <code>text</code>再額外包一層處理，</p>
<p>可見這裡是保留了其他彈性，</p>
<p>往後翻一下文件就會看到我們可以自訂訊息的模板。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> text = messagingEvent.message.text;</div><div class="line"><span class="keyword">const</span> messageData = genMessageData(text)</div><div class="line">sendTextMessage(sender, messageData)</div></pre></td></tr></table></figure>
<p>在 <code>genMessageData</code> 裡面：</p>
<blockquote>
<p>不要被長度嚇到了，你可以對照圖片中的字，</p>
<p>跟下面程式碼做對照，其實都只是在處理 elements 裡面一個個 object 而已</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (text === <span class="string">'feeds'</span>) &#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        <span class="string">"attachment"</span>: &#123;</div><div class="line">            <span class="string">"type"</span>: <span class="string">"template"</span>,</div><div class="line">            <span class="string">"payload"</span>: &#123;</div><div class="line">                <span class="string">"template_type"</span>: <span class="string">"generic"</span>,</div><div class="line">                <span class="string">"elements"</span>: [&#123;</div><div class="line">                    <span class="string">"title"</span>: <span class="string">"淺析 serverless 架構與實作"</span>,</div><div class="line">                    <span class="string">"subtitle"</span>: <span class="string">"May 22, 2016"</span>,</div><div class="line">                    <span class="string">"image_url"</span>: <span class="string">"http://i.imgur.com/lP3wcnh.jpg"</span>,</div><div class="line">                    <span class="string">"buttons"</span>: [&#123;</div><div class="line">                        <span class="string">"type"</span>: <span class="string">"web_url"</span>,</div><div class="line">                        <span class="string">"url"</span>: <span class="string">"http://abalone0204.github.io/2016/05/22/serverless-simple-crud/"</span>,</div><div class="line">                        <span class="string">"title"</span>: <span class="string">"open"</span></div><div class="line">                    &#125;]</div><div class="line">                &#125;, &#123;</div><div class="line">                    <span class="string">"title"</span>: <span class="string">"Saga Pattern 在前端的應用"</span>,</div><div class="line">                    <span class="string">"subtitle"</span>: <span class="string">"May 14, 2016"</span>,</div><div class="line">                    <span class="string">"image_url"</span>: <span class="string">"https://upload.wikimedia.org/wikipedia/zh/3/37/Adventure_Time_-_Title_card.png"</span>,</div><div class="line">                    <span class="string">"buttons"</span>: [&#123;</div><div class="line">                        <span class="string">"type"</span>: <span class="string">"web_url"</span>,</div><div class="line">                        <span class="string">"url"</span>: <span class="string">"http://abalone0204.github.io/2016/05/14/redux-saga/"</span>,</div><div class="line">                        <span class="string">"title"</span>: <span class="string">"open"</span></div><div class="line">                    &#125;]</div><div class="line">                &#125;,</div><div class="line">                &#123;</div><div class="line">                    <span class="string">"title"</span>: <span class="string">"淺入淺出 Generator Function"</span>,</div><div class="line">                    <span class="string">"subtitle"</span>: <span class="string">"May 8, 2016"</span>,</div><div class="line">                    <span class="string">"image_url"</span>: <span class="string">"http://www.rumproast.com/images/uploads/shallow_end_thumb.jpg"</span>,</div><div class="line">                    <span class="string">"buttons"</span>: [&#123;</div><div class="line">                        <span class="string">"type"</span>: <span class="string">"web_url"</span>,</div><div class="line">                        <span class="string">"url"</span>: <span class="string">"http://abalone0204.github.io/2016/05/08/es6-generator-func/"</span>,</div><div class="line">                        <span class="string">"title"</span>: <span class="string">"open"</span></div><div class="line">                    &#125;]</div><div class="line">                &#125;,</div><div class="line">                &#123;</div><div class="line">                    <span class="string">"title"</span>: <span class="string">"Super tiny compiler"</span>,</div><div class="line">                    <span class="string">"subtitle"</span>: <span class="string">"Apr 25, 2016"</span>,</div><div class="line">                    <span class="string">"image_url"</span>: <span class="string">"https://cloud.githubusercontent.com/assets/952783/14413766/134c4068-ff39-11e5-996e-9452973299c2.png"</span>,</div><div class="line">                    <span class="string">"buttons"</span>: [&#123;</div><div class="line">                        <span class="string">"type"</span>: <span class="string">"web_url"</span>,</div><div class="line">                        <span class="string">"url"</span>: <span class="string">"http://abalone0204.github.io/2016/04/25/Super-tiny-compiler/"</span>,</div><div class="line">                        <span class="string">"title"</span>: <span class="string">"open"</span></div><div class="line">                    &#125;]</div><div class="line">                &#125;</div><div class="line">                ]</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>截至目前為止，我們已經理解了怎麼接收和傳送訊息，</p>
<p>對我來說這是一個比 slack 更輕量的小助理，</p>
<p>其實搭配 DynamoDB 或是其他 backend 就可以做到 schedule 的效果。</p>
<p>同時我認為 bot 並不是拿來取代小編的，</p>
<p>可以將一些常問的問題和解答建在 bot 裡面，</p>
<p>讓小編不用再去回一些重複的問題，專注在寫出更好的文案，</p>
<p>以及更急迫需要回應的客戶上面。</p>
<blockquote>
<p>可以選擇搭配 <a href="https://hubot.github.com/" target="_blank" rel="external">hubot</a> 來處理各種訊息，</p>
<p>以及對應的動作。</p>
<p>不過仍然要強調一下，這篇筆記著重在如何建立一個這樣的 interface：<code>收訊息 =&gt; 執行動作</code></p>
<p>另外，把程式邏輯全部都放在 <code>handelr.js</code>，只是為了說明方便，</p>
<p>你可以選擇自己喜歡的方式來建構 bot。</p>
</blockquote>
<p>最後，額外提醒一下 XD</p>
<p>目前完成的 bot 只能夠跟你個人通話而已，</p>
<p>假如你想讓其他人也看到的話，</p>
<p>必須到 facebook app 的控制台通過 facebook 的審核後才行，</p>
<p>希望大家能做出許多好玩的粉絲專頁應用 XD</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="https://developers.facebook.com/docs/messenger-platform" target="_blank" rel="external">Facebook Messenger Platform</a></p>
</li>
<li><p><a href="http://abalone0204.github.io/2016/05/22/serverless-simple-crud/" target="_blank" rel="external">淺析 serverless 架構與實作</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;上禮拜簡單介紹了一下 serverless 的起手式後，&lt;/p&gt;
&lt;p&gt;我想再舉個更接近實際應用的例子，&lt;/p&gt;
&lt;p&gt;儘管並不是所有的應用都適合 serverless 的架構，&lt;/p&gt;
&lt;p&gt;但聊天機器人(chat bot)是一個相當好的例子，&lt;/p&gt;
&lt;p&gt;且讓我稍後再說明為什麼。&lt;/p&gt;
&lt;p&gt;今天就結合一下很實用的粉絲頁回覆機器人以及 serverless 。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;你可以把聊天機器人想成是你粉絲頁自動回覆的員工&lt;/p&gt;
&lt;p&gt;或是進行一些簡單的操作&lt;/p&gt;
&lt;p&gt;而聊天機器人流行起來的原因正是因為 mobile 裝置上的介面，&lt;/p&gt;
&lt;p&gt;並不能滿足於現代人操作的所有需求，&lt;/p&gt;
&lt;p&gt;聊天的介面解放了我們在小框框裡做事的限制。&lt;/p&gt;
&lt;p&gt;或者是你是小小公司的開發者，需要一個助理來幫你做很無腦或繁瑣的事情，&lt;/p&gt;
&lt;p&gt;再講下去可能要一篇了，如果你對這個主題有興趣，&lt;/p&gt;
&lt;p&gt;可以看看 &lt;a href=&quot;https://wanqu.co/blog/2015-05-24-behind-the-scenes.html&quot;&gt;灣區日報是如何運作的&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
    
    </summary>
    
    
      <category term="serverless" scheme="http://abalone0204.github.com/tags/serverless/"/>
    
      <category term="fb" scheme="http://abalone0204.github.com/tags/fb/"/>
    
      <category term="bot" scheme="http://abalone0204.github.com/tags/bot/"/>
    
  </entry>
  
  <entry>
    <title>淺析 serverless 架構與實作</title>
    <link href="http://abalone0204.github.com/2016/05/22/serverless-simple-crud/"/>
    <id>http://abalone0204.github.com/2016/05/22/serverless-simple-crud/</id>
    <published>2016-05-22T03:32:31.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>Serverless ，不是沒有 server，而是不用去擔心維護 server 這件事，</p>
<p>不管是在部署還是開發，都是以一個個 function 為單位，</p>
<p>這帶來了程式碼上的高度 decoupling，但同時也因為過大的彈性，</p>
<p>常常搞的我們無所適從，就像這張圖一樣：</p>
<p><img src="http://i.imgur.com/lP3wcnh.jpg" alt="howto"></p>
<p>serverless 更考驗著我們對系統設計的思維，</p>
<p>這是一篇非常粗淺的文章，</p>
<p>目的在帶領對 serverless 有興趣的人無痛的入門，</p>
<p>不管是在概念上，還是在實務的使用上。</p>
<blockquote>
<p>假如你是懶得看文章的人，可以直接到我的 <a href="https://github.com/abalone0204/serverless-demo-with-dynamodb-node" target="_blank" rel="external">github repo</a> 上面看</p>
<p>有哪裡寫錯的話可以提個 issue，覺得讚讚讚的話也可以給星星以茲鼓勵。</p>
</blockquote>
<a id="more"></a>
<p>試想當你是一個單槍匹馬的開發者時，你絕對會希望能真正專心在開發，</p>
<p>而不是一天到晚擔心機器有沒有死掉，或者配置環境就花了大半時間。</p>
<p>我只是一個前端工程師，對於後端的知識甚是淺薄，</p>
<p>serverless 對我而言是個很合理的選擇，</p>
<p>但這不代表我不在乎任何後端的專業性，</p>
<p>更不代表著後端工程師使用 serverless 架構就是代表實力不夠。</p>
<p>相反的，我認為後端工程師如果能從管理機器中解放，</p>
<p>設計出更好的 serverless 架構以及更專注在程式本身的邏輯上，</p>
<p>那從 serverless 上能獲得的增益一定也是相當驚人的。</p>
<blockquote>
<p>看著我們虛擬化的趨勢 =&gt; VM =&gt; Container =&gt; Docker 的興起</p>
<p>儘管做法略有不同，但方向是一致的，</p>
<p>都是想讓程式開發者更能專注在程式本身，而不是管理機器上</p>
<p>話說回來，前端後端的分界點一直都是個有爭議的問題，</p>
<p>不過就不在這裡去討論了</p>
</blockquote>
<p>這篇會需要用到數個 aws 的服務，不過為了讓事情更單純，</p>
<p>我只會用到 IAM, DynamoDB, API Gateway, CloudWatch 以及 Lambda，</p>
<p>都不熟悉這些也沒有關係，因為我在寫完這一段之前， </p>
<p>也只是大略的把文件掃過去，也不用擔心縮寫令人看不懂，</p>
<p>因為我最討厭的就是這種縮來縮去的東西，</p>
<p>所以接下來都會在提到的地方解釋我們正在處理的是什麼。</p>
<blockquote>
<p>以往都是直接用 EC2 開一台機器，</p>
<p>要用什麼直接當自己家的在上面裝就是了。</p>
<p>（當然可以學一些東西自動化這流程： chef，不過這不是這篇的重點）</p>
</blockquote>
<h1 id="Catalogue"><a href="#Catalogue" class="headerlink" title="Catalogue"></a>Catalogue</h1><ul>
<li><p><a href="#Introduction">Introduction</a></p>
<ul>
<li><p><a href="#優點">優點</a></p>
</li>
<li><p><a href="#限制與風險">限制與風險</a></p>
</li>
<li><p><a href="#Why-serverless-framework">Why serverless framework</a></p>
</li>
</ul>
</li>
<li><p><a href="#Setup-開發環境的建置">Setup 開發環境的建置</a></p>
<ul>
<li><p><a href="#為你的-api-建立一個「role」">為你的 api 建立一個「role」</a></p>
</li>
<li><p><a href="#Create-Project">Create Project</a></p>
</li>
<li><p><a href="#Create-First-function">Create First function</a></p>
</li>
<li><p><a href="#Deployment">Deployment</a></p>
</li>
</ul>
</li>
<li><p><a href="#Abstraction">Abstraction</a></p>
<ul>
<li><p><a href="#Overview">Overview</a></p>
</li>
<li><p><a href="#Source event">Source event</a></p>
</li>
<li><p><a href="#Context">Context</a></p>
</li>
<li><p><a href="#handler-js"><code>handler.js</code></a></p>
</li>
</ul>
</li>
</ul>
<ul>
<li><p><a href="#Implementation-Simple-RESTful-api">Implementation: Simple RESTful api: Simple RESTful api</a></p>
<ul>
<li><p><a href="#Why">Why</a></p>
</li>
<li><p><a href="#Log">Log</a></p>
</li>
<li><p><a href="#Create-an-item">Create an item</a></p>
</li>
<li><p><a href="#Read-an-item">Read an item</a></p>
</li>
<li><p><a href="#Update-an-item">Update an item</a></p>
</li>
<li><p><a href="#Delete-an-item">Delete an item</a></p>
</li>
<li><p><a href="#List-items">List items</a></p>
</li>
</ul>
</li>
<li><p><a href="#Conclusion">Conclusion</a></p>
</li>
<li><p><a href="#References">References</a></p>
</li>
</ul>
<h1 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h1><p>這篇會著重在比較抽象化的概念上，</p>
<p>而不是去針對特定的功能作 serverless 的實現，</p>
<blockquote>
<p>但不要誤會了，後面還是有一個簡易 restful api 的實作</p>
</blockquote>
<p>我認為能掌握以下幾個點，才是針對特定功能實現的基礎：</p>
<ul>
<li><p>Project 的架構</p>
<ul>
<li><p>對於設計一套 serverless architecture 的抽象概念</p>
</li>
<li><p>各個功能與 api 間對應的關係</p>
</li>
</ul>
</li>
<li><p>資料的處理 </p>
<ul>
<li><p>要能永久被儲存</p>
</li>
<li><p>CRUD 操作</p>
</li>
<li><p>Schedule：定時或是 routine 的去做一些事情(這一篇文章裡面不會提到)</p>
</li>
</ul>
</li>
<li><p>部署</p>
<ul>
<li>有新功能時我們要能夠部署上去</li>
</ul>
</li>
<li><p>Log</p>
<ul>
<li>不然你 debug 是要通靈嗎</li>
</ul>
</li>
</ul>
<p>至於使用的語言會是 nodejs。</p>
<h2 id="優點"><a href="#優點" class="headerlink" title="優點"></a>優點</h2><ul>
<li><p>不需要自己管機器，以及近乎無限能力的 scale-out（你的財力夠的話）</p>
</li>
<li><p>相對便宜。因為我們是有執行 function 才收費</p>
<ul>
<li>如果只是自己要使用或是小型專案，基本上都會落在 free tier 區間</li>
</ul>
</li>
<li><p>高度的解耦及靈活的配置</p>
<ul>
<li>不管你是想要製作 nano service 還是 micro service 你都能靈活地去組合</li>
</ul>
</li>
</ul>
<p>有人說過，當你手上只有錘子時，那你看到的所有東西都會是釘子。</p>
<p>不過對於 <code>function</code> 這麼 general purpose 的東西來說，</p>
<p>它的確能拿來解決一切計算相關的問題，端看你組合的方式對不對而已。</p>
<h2 id="限制與風險"><a href="#限制與風險" class="headerlink" title="限制與風險"></a>限制與風險</h2><p>講了這麼多好處，現在當然要來講它的限制。</p>
<ul>
<li><p>有限的記憶體</p>
</li>
<li><p>timeout</p>
<ul>
<li>目前最多只能運算 300 秒，就會被強制結束掉</li>
</ul>
</li>
<li><p>高度的解耦</p>
<ul>
<li>這看起來是好處，但必須要用跟以前不一樣的想法來設計程式，因為我們每次 function 運行完之後，就會把所有資源釋放出去</li>
</ul>
</li>
<li><p>Latency</p>
<ul>
<li><p>因為我們是需要計算時，才會去要資源來運算，每次都算是一個 cold start，所以對 latency 完全無法容忍的服務，可能不適合。</p>
</li>
<li><p>實際上透過 schedule 可以一定程度的解決這問題</p>
</li>
</ul>
</li>
<li><p>風險</p>
<ul>
<li><p>Scale-out</p>
<ul>
<li>坦白說，如果是考慮到有沒有辦法 scale-out，那我想大部分情形，aws 都是沒問題的</li>
</ul>
</li>
<li><p>API 更換</p>
<ul>
<li>因為我們以 function 為單位的高解耦，所以更換 API，不是一個讓人全面崩潰的風險</li>
</ul>
</li>
<li><p><strong>服務被停用</strong></p>
<ul>
<li><p>我說一個字大家就懂了：Parse</p>
</li>
<li><p>當事情走到這一步的時候，基本上就沒啥救了，這就是我們冒著最大的風險</p>
</li>
<li><p>但就如同前面所言，我認為 serverless 是未來大勢所趨，也許不會所有的 project 都如此，不過大多數的中小型專案都會轉向朝這一架構邁進。</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="Why-serverless-framework"><a href="#Why-serverless-framework" class="headerlink" title="Why serverless framework"></a>Why serverless framework</h2><ul>
<li><p>過度的自由，失控的 decoupling</p>
<ul>
<li>框架給了我們更好結構化 project 的方式</li>
</ul>
</li>
<li><p>Config 的設置以及部署 function 簡化</p>
</li>
<li><p>文件和 plugins</p>
</li>
<li><p>社群或公司支持</p>
<ul>
<li><p>Serverless 的官網上有說到，現在是由一群工程師全職在維護這個 framework</p>
</li>
<li><p>gitter 上問問題也幾乎馬上就能得到回答</p>
</li>
</ul>
</li>
<li><p>Apex?</p>
<ul>
<li><p>TJ 的產品，目前還在觀望中，但 serverless 看起來相對較穩定、成熟</p>
</li>
<li><p>不過光是 TJ 這個名字，就很值得一試</p>
</li>
<li><p>就像我前面說的，因為高度解耦的關係，其實要遷移過來「理論上」不是太難的事</p>
</li>
</ul>
</li>
</ul>
<h1 id="Setup-開發環境的建置"><a href="#Setup-開發環境的建置" class="headerlink" title="Setup 開發環境的建置"></a>Setup 開發環境的建置</h1><p>我不認為一個環境的建置，是在把東西裝一裝之後就結束了，</p>
<p>因為東西裝一裝之後，通常後續只會有更多的問題，</p>
<p>而且一個 project 本來就需要在一開始就做好 deploy 的準備了。</p>
<blockquote>
<p>不部署的話幹嘛要用 aws 啊？囧</p>
</blockquote>
<p>完整一點的 setup 應該要包含了從 建置基本設定 =&gt; 部署 </p>
<p>才算是真的結束，</p>
<p>所以這一小節會從配置到部署都走過一次。</p>
<blockquote>
<p>AWS 的介面可能會因為時間的關係，與下方略有不同，</p>
<p>但估計變動不會太大，知道要使用什麼功能比較重要，</p>
<p>故我不會把操作介面的圖片放上來。</p>
</blockquote>
<h2 id="為你的-api-建立一個「role」"><a href="#為你的-api-建立一個「role」" class="headerlink" title="為你的 api 建立一個「role」"></a>為你的 api 建立一個「role」</h2><ul>
<li><p>跟以往一樣，我認為建環境是最困難的部分</p>
</li>
<li><p>首先要建一個 <code>IAM</code> role</p>
</li>
</ul>
<blockquote>
<p>IAM(Identity and Access Management)</p>
<p><code>IAM</code> 的功用就是讓你能夠管理使用者對於服務和資源所擁有的「權限」</p>
<p>可以針對不同的使用者，制定不同的角色，</p>
<p>舉例來說，如果你今天的 api 只想讓 user 從 s3 的 bucket 裡面讀一些靜態資源</p>
<p>你就不會想要讓他擁有 access DynamoDB 的權限，懂？</p>
<p><strong>IAM 是免費的</strong>。</p>
</blockquote>
<p>到 aws 選取 services，在拉下來一狗票的服務中，</p>
<p>選擇 <code>IAM</code>。</p>
<p>建立一個新的 User，名字就輸入：<code>serverless-admin</code>。</p>
<p>建立好之後，</p>
<p>把拿到的 <code>Access Key Id</code> 跟 <code>Secret Access Key</code> 給記下來，</p>
<p>待會會用到。</p>
<p>接著選擇剛剛建立的那個 user：<code>serverless-admin</code>，</p>
<p>在 permissions 的地方加上新的 policy，</p>
<p>這裡 aws 相當貼心的提供我們超大一坨的 policies 可供選擇，</p>
<p>為了方便，我們直接選擇 <code>AdministratorAccess</code>。</p>
<blockquote>
<p>當在 production 環境時，這樣處理 permissions 不會是一個好主意 XD</p>
<p>坦白說我覺得 permissions 會是一個令人頭痛的點</p>
</blockquote>
<h2 id="Create-Project"><a href="#Create-Project" class="headerlink" title="Create Project"></a>Create Project</h2><p>我們選擇了 <code>serverless-framework</code>這一套 serverless framework。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">npm i -g serverless</div><div class="line">serverless project create</div></pre></td></tr></table></figure>
<p>會要你輸入名字以及剛剛的 access key id 跟 secret access key。</p>
<p>接著還要選擇你想要你的 project 運行服務在的地區。</p>
<p>再來稍後三分鐘之後， project 就會建好了。</p>
<blockquote>
<p>會生成一大堆東西，下面列出簡易版的解釋，</p>
<p>看不懂也沒關係，之後在實作中就會碰到很多次了：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">├── _meta // (.gitignored) 就是個存 meta data 的地方（config 之類的</div><div class="line">├── admin.env // (.gitignored)剛剛 create function 時的 AWS Profiles</div><div class="line">├── functions</div><div class="line">│   └── function1</div><div class="line">│       ├── event.json</div><div class="line">│       ├── handler.js</div><div class="line">│       └── s-function.json</div><div class="line">├── package.json // 就是 npm 的那個</div><div class="line">├── s-project.json // serverless 的套件管理</div><div class="line">└── s-resources-cf.json // 就是上述講到 CloudFormation 的描述檔</div></pre></td></tr></table></figure>
<h2 id="Create-First-function"><a href="#Create-First-function" class="headerlink" title="Create First function"></a>Create First function</h2><p>先讓我們 focus 在 <code>function</code> 上，這些 config 真的都可以先放著沒關係。</p>
<blockquote>
<p>這不代表他們不重要，只是晚點再回來看他們是在做什麼</p>
<p>如果你真的現在就等不及，也可以到 serverless 的官方文件看</p>
<p><a href="http://docs.serverless.com/docs/project-structure" target="_blank" rel="external">Project structure</a></p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">serverless function create functions/posts</div></pre></td></tr></table></figure>
<p>選擇 nodejs =&gt; Create Endpoint</p>
<p>接著就可以看到多了一個 <code>functions</code> 資料夾，</p>
<p>並且裡面跟著一個 <code>posts</code> 以及一些東西了。</p>
<p>一樣我們只要知道自己現在建立了一些基礎建設，稍後再來回頭看這是什麼。</p>
<h2 id="Deployment"><a href="#Deployment" class="headerlink" title="Deployment"></a>Deployment</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">serverless dash deploy</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">function - posts</div><div class="line">endpoint - posts - GET</div></pre></td></tr></table></figure>
<p>這兩個都記得要選才會把東西部署上去 aws-lambda。</p>
<p>選擇 deploy 之後稍待幾秒鐘，就可以看到回傳一個網址給你。</p>
<p>這就是能夠執行我們剛剛部屬上去的 <code>posts</code> 的地方。</p>
<p>如果你沒做任何更改，點進去後應該能看到</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;&quot;message&quot;: &quot;Go Serverless! Your Lambda function executed successfully!&quot;&#125;</div></pre></td></tr></table></figure>
<p>到這裡為止，我們才能不心虛的說：環境建完，可以繼續了。</p>
<h1 id="Abstraction"><a href="#Abstraction" class="headerlink" title="Abstraction"></a>Abstraction</h1><h2 id="Overview"><a href="#Overview" class="headerlink" title="Overview"></a>Overview</h2><p>前面一直說到 serverless 架構是以 function 為單位去部署和開發，</p>
<p>現在來對「lambda function」有個具體的抽象概念。（欸？</p>
<p>先來個大略的概觀，你可以跟剛剛 create 的 project 對照著看：</p>
<ul>
<li><p>每個 function 可以有許多個 endpoint（進入點）</p>
</li>
<li><p>每個 endpoint 可以有許多個 method( GET, POST…)</p>
</li>
<li><p>Handler 則是 aws lambda 執行的進入點(就是 <code>handler.js</code>)</p>
</li>
</ul>
<p>來看一下 handler.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports.handler = <span class="function"><span class="keyword">function</span>(<span class="params">event, context, cb</span>) </span>&#123;</div><div class="line">    <span class="comment">// empty</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>實際上我們運行的 function 就是長下面這個樣子，</p>
<p>在開始討論其他配置，和 aws 要怎麼運行到這裡之前，</p>
<p>先搞清楚到底在談論什麼東西：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>(<span class="params">event, context</span>)</span></div></pre></td></tr></table></figure>
<blockquote>
<p>可以有第三個參數 cabllback，</p>
<p>不過其實只要這兩項就可以運作的很好了，</p>
<p>而且 callback 實在不是一個好事</p>
</blockquote>
<h2 id="Source-event"><a href="#Source-event" class="headerlink" title="Source event"></a>Source event</h2><p>source event，可以是 push 或 pull model。</p>
<p>假設 S3 上面資料新增，lambda function 會接收到 event 去做事情，</p>
<p>那這就是一個 push model。</p>
<p>假設今天是 lamda function 去掃了一遍 DynamoDB ，</p>
<p>發現有事情要根據上面的資料去做，</p>
<p>這就是一個 pull model。</p>
<p>而 source event 也可以很單純的來自 http request。</p>
<h2 id="Context"><a href="#Context" class="headerlink" title="Context"></a>Context</h2><p><code>context</code> 是一個 object，</p>
<p>裡面包含了當前 lambda 運行環境的訊息，</p>
<p>以及一些 method。</p>
<p>有三個 methods 是一定要知道的：</p>
<blockquote>
<p>這裡的參數是可選的，我們可以只讓 function 做事，<br>沒有一定要強制回傳結果。</p>
</blockquote>
<ul>
<li><p><code>context.succeed(Object result)</code></p>
<ul>
<li><p>可以在執行成功時回傳東西： <code>context.succeed(someObject)</code></p>
</li>
<li><p>注意這裡的 <code>result</code> 必須要能夠被 JSON.stringifyu 轉成字串</p>
</li>
</ul>
</li>
<li><p><code>context.fail(Error error)</code> </p>
<ul>
<li>在失敗時回傳東西</li>
</ul>
</li>
<li><p><code>context.done(Error error, Object result)</code></p>
<ul>
<li><p>這個就有點奇葩了，有了成功和失敗為什麼還要存在個 done 呢？</p>
</li>
<li><p>如果 error 不為 null，這次的 lamda function 就會被認定為執行失敗</p>
</li>
</ul>
</li>
</ul>
<p>再來是可以看到目前執行剩餘時間：</p>
<p><code>context.getRemainingTimeInMillis()</code></p>
<p>這裡所謂的看到當然是指在 function 執行時我們能利用啦！</p>
<p>不過要注意的是如果歸零，</p>
<p>AWS lambda 就會強制終止我們的 lambda function 了。</p>
<h2 id="handler-js"><a href="#handler-js" class="headerlink" title="handler.js"></a><code>handler.js</code></h2><p>前面有提到過這裡就是 aws 運行的進入點，</p>
<p>要在 <code>s-function.json</code> 裡面設定，</p>
<p>這裡看到我們只在 <code>handler</code> 那個屬性打上 : <code>handler.handler</code>，</p>
<p>這有兩件事情值得注意：</p>
<ul>
<li>對應執行的就是 <code>handler.js</code> 這個 module 底下的 <code>handler</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// in handler.js</span></div><div class="line"><span class="built_in">module</span>.exports.handler = <span class="function"><span class="keyword">function</span>(<span class="params">event, context</span>) </span>&#123;</div><div class="line">    <span class="comment">// This be implemented</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>第二件事就是這個 hanlder 屬性還隱含著我們目前能作用的 scope，</p>
<p>假如我們是：<code>function1/handler.handler</code>，</p>
<p>就把上層的 parent folder 給包含進去，</p>
<p>所以他就吃得到我們在根目錄安裝的 npm 套件。</p>
<blockquote>
<p>比如說你安裝了 react，那你就可以：<br><code>require(&#39;react&#39;)</code></p>
</blockquote>
<p>理解到這樣的程度，就已經足夠進行下去了，</p>
<p>直接來實作吧！</p>
<h1 id="Implementation-Simple-RESTful-api"><a href="#Implementation-Simple-RESTful-api" class="headerlink" title="Implementation: Simple RESTful api"></a>Implementation: Simple RESTful api</h1><p>直接看文件時，總會有種霧裡看花的感覺，</p>
<p>不過等到實際開始做之後，你會發現其實概念只要 mapping 過去，</p>
<p>並沒有想像中的困難。</p>
<blockquote>
<p>這個是完成後的 <a href="https://github.com/abalone0204/serverless-demo-with-dynamodb-node" target="_blank" rel="external">github repo</a>，</p>
<p>如果你中途發現有什麼錯誤的話，可以在上面查看是否有哪裡不一樣。</p>
</blockquote>
<h2 id="Why"><a href="#Why" class="headerlink" title="Why"></a>Why</h2><p>底下會包含基本的 CRUD 以及 list，</p>
<p>大多數的應用程式都不脫這五種操作，</p>
<p>就算需要更特殊的操作，</p>
<p>也總是要熟悉這些基礎後才能繼續前進，</p>
<p>包含著如何儲存資料以及 debug 的概念。</p>
<p>至於資料夾的結構或是 workflow 的順序，</p>
<p>你都可以依照個人的喜好去調整，不一定要照我寫的走。</p>
<h2 id="Log"><a href="#Log" class="headerlink" title="Log"></a>Log</h2><ul>
<li><p>沒錯，我們先來看看要怎麼找出錯誤，從犯錯中學習，是新手成長最快的方式</p>
</li>
<li><p>來修改一下<code>functions/posts/hanlder.js</code></p>
</li>
</ul>
<p><code>context</code> 和 <code>event</code> 是我們在 lambda 中要好好處理的東西沒錯，</p>
<p>不過這裡先專注在出 bug 時要怎麼解決：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="meta">'use strict'</span></div><div class="line"></div><div class="line"><span class="built_in">console</span>.log(<span class="string">'Loading function'</span>)</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">display</span>(<span class="params">object</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="built_in">JSON</span>.stringify(object, <span class="literal">null</span>, <span class="number">2</span>)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports.handler = (event, context) =&gt; &#123;</div><div class="line">  <span class="built_in">console</span>.log(<span class="string">'Event: '</span>, display(event))</div><div class="line">  <span class="built_in">console</span>.log(<span class="string">'Context: '</span>, display(context))</div><div class="line">  context.succedd(&#123;</div><div class="line">    message: <span class="string">'ok, it works'</span></div><div class="line">  &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>這裡的程式碼有個明顯的錯誤，待會我們會除錯並且學習如何看 log</p>
</blockquote>
<p>稍做一些更改之後我們就可以再次部署了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">serverless dash deploy</div></pre></td></tr></table></figure>
<p>再到剛剛的網址，會發現出現錯誤了！</p>
<p>幸好這裡加上了許多 <code>console.log</code>，</p>
<p>假如你曾經寫過 JavaScript 對這樣的除錯技巧一定不陌生，</p>
<p>但，這裡的 log 不會在 console 印出來，會到哪裡呢？</p>
<p>這裡就要使用 aws 上的另個服務：CloudWatch 了。</p>
<p>到 services 點 CloudWatch，選取 logs，</p>
<p>就會看到這裡有個 log groups 就是我們剛剛建立的 functions。</p>
<p>選進去後會很神奇地發現我們之前 call 的紀錄都在這裡。</p>
<p>在 log 中我們可以看到：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">...(一些日期和系統資訊) TypeError: context.succedd is not a function at module.exports.handler (/const/task/handler.js:12:11)</div></pre></td></tr></table></figure>
<p>我們出了一個 typo 的錯誤，改正過來以後就成功啦！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">context.succeed(&#123;</div><div class="line">    message: <span class="string">'ok, it works'</span></div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<h2 id="Create-an-item"><a href="#Create-an-item" class="headerlink" title="Create an item"></a>Create an item</h2><p>要存資料庫前，必須先在 <code>DynamoDB</code> 建一張 Table。</p>
<blockquote>
<p>DynamoDB 是一個 no sql 的資料庫</p>
<p>為了 scale-out ，它在使用上有一些限制，</p>
<p>但在這個簡單的示例中，並不會需要考量到這些，</p>
<p>假如有興趣深入的話，可以看補充資料的地方</p>
<p><a href="http://history.programmer.com.cn/11081/" target="_blank" rel="external">解析 DynamoDB</a></p>
</blockquote>
<ul>
<li><p>到 aws 上選擇 <code>DynamoDB</code> 。</p>
</li>
<li><p>Create table</p>
</li>
<li><p>table name 輸入 <code>posts</code></p>
</li>
<li><p>primary key 名稱設定為 <code>id</code></p>
</li>
<li><p>下面的 default setting 取消勾選，然後將 Read capacity units 以及 Write capacity units 都調成 1</p>
</li>
<li><p>我們就有一個很陽春的 table 了</p>
</li>
</ul>
<p>接著是在 <code>handler</code> 裡面的更動，</p>
<p>首先要安裝兩個 package</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">npm i -S dynamodb-doc node-uuid</div></pre></td></tr></table></figure>
<p>前面有說過 lambda function 其實就是根據 source event，</p>
<p>去執行對應的動作：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> DOC = <span class="built_in">require</span>(<span class="string">'dynamodb-doc'</span>)</div><div class="line"><span class="keyword">const</span> dynamo = <span class="keyword">new</span> DOC.DynamoDB()</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports.handler = (event, context) =&gt; &#123;</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">'Event: '</span>, display(event))</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">'Context: '</span>, display(context))</div><div class="line">    </div><div class="line">    <span class="keyword">const</span> operation = event.operation</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (event.tableName) &#123;</div><div class="line">        event.payload.TableName = event.tableName</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">switch</span> (operation) &#123;</div><div class="line">        <span class="keyword">case</span> <span class="string">'create'</span>:</div><div class="line">            <span class="keyword">const</span> uuid = <span class="built_in">require</span>(<span class="string">'node-uuid'</span>)</div><div class="line">            event.payload.Item.id = uuid.v1()</div><div class="line">            dynamo.putItem(event.payload, () =&gt; &#123;</div><div class="line">                context.succeed(&#123;</div><div class="line">                    <span class="string">"id"</span>: event.payload.Item.id</div><div class="line">                &#125;)</div><div class="line">            &#125;)</div><div class="line">            <span class="keyword">break</span></div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unrecognized operation "'</span> + operation + <span class="string">'"'</span>))</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>其實蠻像我們平常在<code>redux</code>中處理對應的 action type 的 <code>reducer</code></p>
</blockquote>
<p>這裡建立了一個 <code>DynamoDB</code> 的 client，簡單的來說，我們會把 <code>event.payload</code> 這個 object，</p>
<p>新增成 Table 裡的一個新 item，並且給它一個唯一的 <code>id</code>，</p>
<p>畢竟是 Primary key 嘛！ </p>
<blockquote>
<p>如果你不熟悉 Database 的基礎理論，Primary key。</p>
<p>Primary key 就是我們拿來識別這個 item 在這個表中是唯一的「身分證」，</p>
<p>在這裡我們是用 <code>id</code>來作為我們的 Primary key。</p>
</blockquote>
<p>那這個 <code>event</code>又是怎麼來的呢？</p>
<p>首先我們要了解的是 Create 這個動作對應到的 http method 是 <code>POST</code>，</p>
<p>所以當我們在對同一個 url 執行 <code>GET</code> 跟 <code>POST</code>時，</p>
<p>雖然 call 的是同個 function（或者更精確地說，是同一個 Endpoint）。</p>
<p>在 <code>posts</code> 資料夾底下，可以看到一個 <code>s-function.json</code>，</p>
<p>這個檔案中放著的是關於我們在進入 <code>handler.js</code>時相關的 config。</p>
<p>當然也包括了前面說到的 <code>event</code>。</p>
<p>先直接看到 <code>endpoints</code> 這個 attribute，裡面有許多個物件，</p>
<p>預設的是這個：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">      <span class="string">"path"</span>: <span class="string">"posts"</span>,</div><div class="line">      <span class="string">"method"</span>: <span class="string">"GET"</span>,</div><div class="line">      <span class="string">"type"</span>: <span class="string">"AWS"</span>,</div><div class="line">      <span class="string">"authorizationType"</span>: <span class="string">"none"</span>,</div><div class="line">      <span class="string">"authorizerFunction"</span>: <span class="literal">false</span>,</div><div class="line">      <span class="string">"apiKeyRequired"</span>: <span class="literal">false</span>,</div><div class="line">      <span class="string">"requestParameters"</span>: &#123;&#125;,</div><div class="line">      <span class="string">"requestTemplates"</span>: &#123;</div><div class="line">        <span class="string">"application/json"</span>: <span class="string">""</span></div><div class="line">      &#125;,</div><div class="line">      <span class="string">"responses"</span>: &#123;</div><div class="line">        <span class="string">"400"</span>: &#123;</div><div class="line">          <span class="string">"statusCode"</span>: <span class="string">"400"</span></div><div class="line">        &#125;,</div><div class="line">        <span class="string">"default"</span>: &#123;</div><div class="line">          <span class="string">"statusCode"</span>: <span class="string">"200"</span>,</div><div class="line">          <span class="string">"responseParameters"</span>: &#123;&#125;,</div><div class="line">          <span class="string">"responseModels"</span>: &#123;</div><div class="line">            <span class="string">"application/jsoncharset=UTF-8"</span>: <span class="string">"Empty"</span></div><div class="line">          &#125;,</div><div class="line">          <span class="string">"responseTemplates"</span>: &#123;</div><div class="line">            <span class="string">"application/jsoncharset=UTF-8"</span>: <span class="string">""</span></div><div class="line">          &#125;</div><div class="line">        &#125;</div><div class="line">      &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裡有好多東西，</p>
<p>假如我們要在裡面定義我們對每個 endpoint 的長相，誰不發瘋呢？</p>
<p>眼尖的你應該看到了有 <code>template</code>這個字眼，</p>
<p>而剛剛送進來的 <code>event</code> 正是一個 http request，</p>
<p>所以我們要做的事情已經呼之欲出了，就是在<code>requestTemplates</code>加上我們指定的 template 名稱，</p>
<p>就能根據這個 template 生出我們想要的 event 。</p>
<p>在 <code>endpoints</code> 中加上了這個新的 object：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">      <span class="string">"path"</span>: <span class="string">"posts"</span>,</div><div class="line">      <span class="string">"method"</span>: <span class="string">"POST"</span>,</div><div class="line">      <span class="string">"type"</span>: <span class="string">"AWS"</span>,</div><div class="line">      <span class="string">"authorizationType"</span>: <span class="string">"none"</span>,</div><div class="line">      <span class="string">"authorizerFunction"</span>: <span class="literal">false</span>,</div><div class="line">      <span class="string">"apiKeyRequired"</span>: <span class="literal">false</span>,</div><div class="line">      <span class="string">"requestParameters"</span>: &#123;&#125;,</div><div class="line">      <span class="string">"requestTemplates"</span>: <span class="string">"$$&#123;requestCreatePostTemplate&#125;"</span>,</div><div class="line">      <span class="string">"responses"</span>: &#123;</div><div class="line">        <span class="string">"400"</span>: &#123;</div><div class="line">          <span class="string">"statusCode"</span>: <span class="string">"400"</span></div><div class="line">        &#125;,</div><div class="line">        <span class="string">"default"</span>: &#123;</div><div class="line">          <span class="string">"statusCode"</span>: <span class="string">"200"</span>,</div><div class="line">          <span class="string">"responseParameters"</span>: &#123;&#125;,</div><div class="line">          <span class="string">"responseModels"</span>: &#123;</div><div class="line">            <span class="string">"application/jsoncharset=UTF-8"</span>: <span class="string">"Empty"</span></div><div class="line">          &#125;,</div><div class="line">          <span class="string">"responseTemplates"</span>: &#123;</div><div class="line">            <span class="string">"application/jsoncharset=UTF-8"</span>: <span class="string">""</span></div><div class="line">          &#125;</div><div class="line">        &#125;</div><div class="line">      &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>當進入這個 api 時(path 沒有改變)，使用 POST method時，</p>
<p>我們的 request 會照著<code>requestCreatePostTemplate</code>這個 template 走</p>
<blockquote>
<p>$${requestCreatePostTemplate} 是特殊的語法，</p>
<p>讓 serverless 知道這是個 template 名字，而不是一般的 string。</p>
</blockquote>
<p>所以我說，那個 tempalte 呢？</p>
<p>這裡要在 <code>posts</code> 底下新增 <code>s-templates.json</code>，</p>
<p>所有的關於 lambda function 的 template 都會放在這裡。</p>
<p>接下來我們就可以設計我們的 request（event）的長相了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"requestCreatePostTemplate"</span>: &#123;</div><div class="line">        <span class="string">"application/json"</span>: &#123;</div><div class="line">            <span class="string">"operation"</span>: <span class="string">"create"</span>,</div><div class="line">            <span class="string">"tableName"</span>: <span class="string">"posts"</span>,</div><div class="line">            <span class="string">"payload"</span>: &#123;</div><div class="line">                <span class="string">"Item"</span>: &#123;</div><div class="line">                    <span class="string">"content"</span>: <span class="string">"$input.json('$')"</span></div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裡比較讓人疑惑的是 <code>$input.json(&#39;$&#39;)</code>是什麼，</p>
<p>這其實是跟 API Gateway 比較有關係的 template 語法，</p>
<p>而不是 serverless 這個框架底下的。</p>
<blockquote>
<p>This function evaluates a JSONPath expression and returns the results as a JSON string.<br>For example, $input.json(‘$.pets’) will return a JSON string representing the pets structure.</p>
</blockquote>
<p>簡單的說，他會將 input 轉成一個 json-like string，</p>
<p>更棒的地方是他可以像我們平常 access 底下的 attribut 那樣去找底下的東西：</p>
<p>（就是所謂的 <a href="http://goessner.net/articles/JsonPath/" target="_blank" rel="external">json path</a>）</p>
<p>像是 <code>$.pets</code> 就是將我們吃到的 input object底下<code>pets</code> 對應到的東西，</p>
<p>轉成 string。</p>
<blockquote>
<p><a href="http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html" target="_blank" rel="external">Amazon API Gateway: Mapping template reference</a></p>
<p>想瞭解更多關於 Template 的話可以參考 serverless framework 的文件：</p>
<p><a href="http://docs.serverless.com/docs/application-architectures" target="_blank" rel="external">Template &amp; Variable</a></p>
</blockquote>
<p>接著回到一開始的 <code>handler.js</code>，</p>
<p>就可以把跟 <code>event</code> 有關的東西與我們前面 template 裡面所做的 config 連接起來了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">module</span>.exports.handler = (event, context) =&gt; &#123;</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">'Event: '</span>, display(event))</div><div class="line">    <span class="built_in">console</span>.log(<span class="string">'Context: '</span>, display(context))</div><div class="line">    <span class="keyword">const</span> operation = event.operation</div><div class="line">    <span class="keyword">if</span> (event.tableName) &#123;</div><div class="line">        event.payload.TableName = event.tableName</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">switch</span> (operation) &#123;</div><div class="line">        <span class="keyword">case</span> <span class="string">'create'</span>:</div><div class="line">            <span class="keyword">const</span> uuid = <span class="built_in">require</span>(<span class="string">'node-uuid'</span>)</div><div class="line">            event.payload.Item.id = uuid.v1()</div><div class="line">            <span class="built_in">console</span>.log(<span class="string">'Payload: '</span>, display(event.payload))</div><div class="line">            dynamo.putItem(event.payload, () =&gt; &#123;</div><div class="line">                context.succeed(event.payload.Item)</div><div class="line">            &#125;)</div><div class="line">            <span class="keyword">break</span></div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unrecognized operation "'</span> + operation + <span class="string">'"'</span>))</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這時候可以部署了！</p>
<p>部署完成之後我們需要試試有沒有成功，必須要打開 API Gateway，</p>
<p>一進去就可以看到對應 project 名稱的 api，</p>
<p>點進去能看到我們現在有哪幾個 api 可以用（url）。</p>
<p>可以把 API Gateway 想像成我們平常使用的 <code>router</code>，</p>
<p>Gateway 會把要執行的 endpoint 接到對應的 url 上。</p>
<p>點擊 <code>/posts</code> 底下 <code>POST</code> method 的 integration request ，</p>
<p>在 Body Mapping Templates 可以看到對應的 template：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;<span class="string">"operation"</span>:<span class="string">"create"</span>,<span class="string">"tableName"</span>:<span class="string">"posts"</span>,<span class="string">"payload"</span>:&#123;<span class="string">"Item"</span>:&#123;<span class="string">"content"</span>:$input.json(<span class="string">'$'</span>)&#125;&#125;&#125;</div></pre></td></tr></table></figure>
<p>那，要怎麼測試呢？</p>
<p>我習慣用 postman，算是一個測 api 相當好用的工具，</p>
<p>找到<code>serverless-demo</code>這 project 底下對應的 <code>stages</code> ，</p>
<p>選擇當前對應的 stage（預設應該是 dev），</p>
<p>然後選擇<code>Export as Swagger + Postman Extensions</code> 這個選項，</p>
<p>會下載一個 json ，裡面把你所有建立的 request 都包好好的。</p>
<p>接著就能在 postman 中 import ，就能直接使用了。</p>
<p>首先當然是先測試原先的 <code>GET</code> method，理論上來說應該要丟出 error，</p>
<p>因為送進來的 request(event)，它的 <code>operation</code>是 <code>undefined</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="string">"errorMessage"</span>: <span class="string">"Unrecognized operation \"undefined\""</span>,</div><div class="line">  <span class="string">"errorType"</span>: <span class="string">"Error"</span>,</div><div class="line">  <span class="string">"stackTrace"</span>: [</div><div class="line">    <span class="string">"module.exports.handler (/const/task/handler.js:28:26)"</span></div><div class="line">  ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>非常的好。</p>
<p>接著是<code>POST</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="string">"errorMessage"</span>: <span class="string">"Process exited before completing request"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>居然噴錯了，所以我們要再度到 CloudWatch 去看一下 log，</p>
<p>看起來 <code>event</code> 的樣子是對的，但往下一看就找到了這個錯誤：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Cannot find module &apos;node-uuid&apos;</div></pre></td></tr></table></figure>
<p>我們在根目錄雖然有<code>package.json</code>，</p>
<p>但是目前對於底下的 <code>handler.js</code> 而言，</p>
<p>它對根目錄是完全一無所知的，那該怎麼做呢？</p>
<p>在<code>s-function.json</code> 中的 <code>handler</code> 改成 <code>functions/posts/handler.handler</code>，</p>
<p>我們能在這裡決定 function 要對整個 project 的權限到哪裡，</p>
<p>像這裡就會一直延伸到根目錄，所以我們在根目錄所安裝的 package，</p>
<p>自然到了<code>posts</code>底下也吃得到了。</p>
<p>假如仍然沒有辦法動到 dynamodb 的話，</p>
<p>就要到 <code>s-resources-cf.json</code> 更改設定</p>
<p>在<code>IamPolicyLambda.Properties.PolicyDocument.Statement</code>底下加上：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&#123; </div><div class="line">    <span class="string">"Effect"</span>: <span class="string">"Allow"</span>,</div><div class="line">    <span class="string">"Action"</span>: [<span class="string">"*"</span>],</div><div class="line">    <span class="string">"Resource"</span>: <span class="string">"arn:aws:dynamodb:$&#123;region&#125;:*:table/*"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再去 Postman 執行一次，</p>
<p>DynamoDB 的 Table 裡面就會出現新一筆的資料了（一個新的 Item）。</p>
<h2 id="Read-an-item"><a href="#Read-an-item" class="headerlink" title="Read an item"></a>Read an item</h2><ul>
<li>我們剛剛已經可以在 DynamoDB 裡面新增資料，自然要有辦法拿出來才是。</li>
</ul>
<p>第一步一樣是從 <code>handler.js</code> 裡面直接去做更改：</p>
<blockquote>
<p>為什麼每次都從 <code>handler.js</code>開始是因為這邊是最符合邏輯的地方，</p>
<p>其他都比較特定的 config 問題</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">switch</span> (operation) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="string">'create'</span>:</div><div class="line">        <span class="keyword">const</span> uuid = <span class="built_in">require</span>(<span class="string">'node-uuid'</span>)</div><div class="line">        event.payload.Item.id = uuid.v1()</div><div class="line">        <span class="built_in">console</span>.log(<span class="string">'Payload: '</span>, display(event.payload))</div><div class="line">        dynamo.putItem(event.payload, () =&gt; &#123;</div><div class="line">            context.succeed(event.payload.Item)</div><div class="line">        &#125;)</div><div class="line">        <span class="keyword">break</span></div><div class="line">    <span class="keyword">case</span> <span class="string">'read'</span>:</div><div class="line">        dynamo.getItem(event.payload, context.done)</div><div class="line">        <span class="keyword">break</span></div><div class="line">    <span class="keyword">default</span>:</div><div class="line">        context.fail(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Unrecognized operation "'</span> + operation + <span class="string">'"'</span>))</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著要到 <code>s-function.json</code> 裡面去加上對於 parameter 的設定，</p>
<p>以及加上 template：</p>
<blockquote>
<p>在 GET method 的底下</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="string">"requestParameters"</span>: &#123;</div><div class="line">        <span class="string">"integration.request.querystring.id"</span>: <span class="string">"method.request.querystring.id"</span></div><div class="line">      &#125;,</div><div class="line"><span class="string">"requestTemplates"</span>: <span class="string">"$$&#123;requestReadPostTemplate&#125;"</span></div></pre></td></tr></table></figure>
<p>最後則是 template：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="string">"requestReadPostTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"operation"</span>: <span class="string">"read"</span>,</div><div class="line">        <span class="string">"tableName"</span>: <span class="string">"posts"</span>,</div><div class="line">        <span class="string">"payload"</span>: &#123;</div><div class="line">            <span class="string">"Key"</span>: &#123;</div><div class="line">                <span class="string">"id"</span>: <span class="string">"$input.params('id')"</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>假如你好奇為什麼要用<code>Key</code> 的話，</p>
<p>可以參考 DynamoDB js sdk 的 <a href="https://github.com/awslabs/dynamodb-document-js-sdk" target="_blank" rel="external">github</a></p>
<p>與 mongodb 的 query 非常相似</p>
</blockquote>
<p>因為我們在 handler 中用了 <code>context.done</code>，</p>
<p>這裡其實是個 callback function，等到 <code>getItem</code> 結束後，</p>
<p>才會執行 <code>context.done</code> ，</p>
<p>並且會依序傳入 <code>error</code>、<code>data</code>兩個 object，</p>
<p>所以回傳的 response 會是像這樣的一整個 item：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="string">"Item"</span>: &#123;</div><div class="line">    <span class="string">"id"</span>: <span class="string">"3caaeb80-1ebf-11e6-81a9-21cf9c171332"</span>,</div><div class="line">    <span class="string">"content"</span>: &#123;</div><div class="line">      <span class="string">"message"</span>: <span class="string">"Hello world again!"</span></div><div class="line">    &#125;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>有時候我們並不想讓使用者知道這麼多，</p>
<p>所以可以使用 response template，</p>
<p>這裡就能看到前面說的 json path 的用處：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// s-function.json</span></div><div class="line"><span class="string">"responseTemplates"</span>: <span class="string">"$$&#123;responseReadPostTemplate&#125;"</span></div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// s-templates.json</span></div><div class="line"><span class="string">"responseReadPostTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"post"</span>: &#123;</div><div class="line">            <span class="string">"id"</span>: <span class="string">"$input.path('$').Item.id"</span>,</div><div class="line">            <span class="string">"content"</span>: &#123;</div><div class="line">                <span class="string">"message"</span>: <span class="string">"$input.path('$').Item.content.message"</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Update-an-item"><a href="#Update-an-item" class="headerlink" title="Update an item"></a>Update an item</h2><p>Update 跟 Read 的做法其實已經大同小異，</p>
<p>一樣是把查詢用的 Key 放在 <code>params</code> 中，</p>
<p>這裡我們一樣把整包 payload 都丟進來。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">dynamo.putItem(event.payload, (err, data)=&gt; &#123;</div><div class="line">    context.succeed(event.payload)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>看起來只是改成使用 <code>putItem</code> 而已，</p>
<p>但其實這邊的 template 有點小小的改變。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="string">"requestUpdatePostTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"operation"</span>: <span class="string">"update"</span>,</div><div class="line">        <span class="string">"tableName"</span>: <span class="string">"posts"</span>,</div><div class="line">        <span class="string">"payload"</span>: &#123;</div><div class="line">            <span class="string">"Item"</span>: &#123;</div><div class="line">                <span class="string">"id"</span>: <span class="string">"$input.params('id')"</span>,</div><div class="line">                <span class="string">"content"</span>: <span class="string">"$input.json('$')"</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這樣子的好處就是在更新時，只要在 params 輸入指定的 <code>id</code>，</p>
<p>其餘要更新的部分就是放在 <code>body</code>裡面。</p>
<blockquote>
<p>這裡的 <code>PUT</code> 並不是 partial 的更新，</p>
<p>而是整個會替換掉，符合它原本 HTTP method 對應的行為</p>
</blockquote>
<p>至於<code>s-function.json</code> 裡面要怎麼改，這有點太 trivial ，</p>
<p>就不放上來了。</p>
<h2 id="Delete-an-item"><a href="#Delete-an-item" class="headerlink" title="Delete an item"></a>Delete an item</h2><p>刪除一個 item，要做的事情比 update 單純多了，</p>
<p>基本上只要指定好 Key，一切就已經結束了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">dynamo.deleteItem(event.payload, context.done)</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="string">"requestDestroyPostTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"operation"</span>: <span class="string">"destroy"</span>,</div><div class="line">        <span class="string">"tableName"</span>: <span class="string">"posts"</span>,</div><div class="line">        <span class="string">"payload"</span>: &#123;</div><div class="line">            <span class="string">"Key"</span>: &#123;</div><div class="line">                <span class="string">"id"</span>: <span class="string">"$input.params('id')"</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="List-items"><a href="#List-items" class="headerlink" title="List items"></a>List items</h2><p>除了以上的 CRUD 之外，</p>
<p>列出一定數量的 items 也是一個相當常見的需求。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">dynamo.scan(event.payload, context.done)</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="string">"requestListPostTemplate"</span>: &#123;</div><div class="line">    <span class="string">"application/json"</span>: &#123;</div><div class="line">        <span class="string">"operation"</span>: <span class="string">"list"</span>,</div><div class="line">        <span class="string">"tableName"</span>: <span class="string">"posts"</span>,</div><div class="line">        <span class="string">"payload"</span>: &#123;&#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最後的 Response template 會用到 <code>foreach</code> 語法，</p>
<p>坦白說這裡我壓根不想去理解這裡的意義是什麼，</p>
<p>我寧願在需要的時候再去查文件就好，</p>
<p>因為我相信這種夭壽的語法遲早會被改掉的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&quot;responseListPostTemplate&quot;: &quot;&#123;\&quot;posts\&quot; : [#foreach($post in $input.path(&apos;$&apos;).Items)&#123;\&quot;id\&quot; : \&quot;$post.id\&quot;,\&quot;content\&quot; : &#123; \&quot;message\&quot;:\&quot;$post.content.message\&quot; &#125;&#125;#if($foreach.hasNext),#end #end ] &#125;&quot;</div></pre></td></tr></table></figure>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>現在大概知道，</p>
<p>為什麼當初開始學的時候網路上沒什麼好的教學文了，</p>
<p>因為 config 的設置真的是挺複雜的，</p>
<p>不過我想這一篇這樣記錄下來，應該能讓許多人省下走冤枉路的時間。</p>
<p>對於一個程式開發者來說，學習東西的時間就是最大的成本，</p>
<p>我想 serverless 不管對於前後端來說，</p>
<p>都是一項很超值的投資。</p>
<p>因為大部分時候，我們都不需要開一整台機器來完成你想做的事情。</p>
<p>在完成這篇之後，可以做什麼練習呢？</p>
<p>你可以試著把你原本在 EC2 上 host 的服務，</p>
<p>轉移成 serverless 架構。</p>
<blockquote>
<p>光想就覺得超難的</p>
</blockquote>
<p>或者是把一些 routine 的工作，用 serverless 的方式去做，</p>
<p>當你越過前面那些雞巴毛 config 後，</p>
<p>你會發現開發和部署上帶來的效率令你吃驚。</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p><a href="https://github.com/markusklems/serverless-node-dynamodb-example" target="_blank" rel="external">Serverless node dynamodb example</a></p>
</li>
<li><p><a href="http://docs.serverless.com/docs/" target="_blank" rel="external">serverless framework document</a></p>
</li>
<li><p><a href="http://history.programmer.com.cn/11081/" target="_blank" rel="external">解析 DynamoDB</a></p>
</li>
<li><p><a href="http://docs.aws.amazon.com/zh_cn/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html" target="_blank" rel="external">Amazon API Gateway: Mapping template reference</a></p>
</li>
<li><p><a href="http://alexfalkowski.blogspot.tw/2013/12/micro-and-nano-services.html" target="_blank" rel="external">Micro service and Nano service</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Serverless ，不是沒有 server，而是不用去擔心維護 server 這件事，&lt;/p&gt;
&lt;p&gt;不管是在部署還是開發，都是以一個個 function 為單位，&lt;/p&gt;
&lt;p&gt;這帶來了程式碼上的高度 decoupling，但同時也因為過大的彈性，&lt;/p&gt;
&lt;p&gt;常常搞的我們無所適從，就像這張圖一樣：&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/lP3wcnh.jpg&quot; alt=&quot;howto&quot;&gt;&lt;/p&gt;
&lt;p&gt;serverless 更考驗著我們對系統設計的思維，&lt;/p&gt;
&lt;p&gt;這是一篇非常粗淺的文章，&lt;/p&gt;
&lt;p&gt;目的在帶領對 serverless 有興趣的人無痛的入門，&lt;/p&gt;
&lt;p&gt;不管是在概念上，還是在實務的使用上。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;假如你是懶得看文章的人，可以直接到我的 &lt;a href=&quot;https://github.com/abalone0204/serverless-demo-with-dynamodb-node&quot;&gt;github repo&lt;/a&gt; 上面看&lt;/p&gt;
&lt;p&gt;有哪裡寫錯的話可以提個 issue，覺得讚讚讚的話也可以給星星以茲鼓勵。&lt;/p&gt;
&lt;/blockquote&gt;
    
    </summary>
    
    
      <category term="serverless" scheme="http://abalone0204.github.com/tags/serverless/"/>
    
      <category term="aws-lambda" scheme="http://abalone0204.github.com/tags/aws-lambda/"/>
    
      <category term="dynamodb" scheme="http://abalone0204.github.com/tags/dynamodb/"/>
    
  </entry>
  
  <entry>
    <title>Saga Pattern 在前端的應用</title>
    <link href="http://abalone0204.github.com/2016/05/14/redux-saga/"/>
    <id>http://abalone0204.github.com/2016/05/14/redux-saga/</id>
    <published>2016-05-14T19:02:18.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<blockquote>
<p>這是篇長文，你可以直接跳到<a href="/2016/05/14/redux-saga/#Catalogue">你想看的地方</a>就好<br>或是直接在 github 上面看我 step by step 的教學<br><a href="https://github.com/abalone0204/redux-thunk-to-saga-tutorial/commit/1a4455b23ce6bc434d17a8c2ebcbf9e80e922be5" target="_blank" rel="external">redux-thunk-to-saga-tutorial</a></p>
</blockquote>
<p>先把結論講在一開始，這並不只是一個 library 的使用方法介紹而已，</p>
<p>因為學習 saga pattern 對於前端工程師是有幫助的，</p>
<p>主要不出以下三個概念：</p>
<ul>
<li><p>好的 UI/UX 該是一個畫面的 transaction</p>
</li>
<li><p>User 隨時能夠取消 transaction</p>
</li>
<li><p>滿足上述條件實作出來的資料流是要容易被測試的</p>
</li>
</ul>
<p>那<code>redux-saga</code>到底是在解決什麼問題呢？</p>
<p>答案：</p>
<ul>
<li><p>讓我們的非同步 action 能夠更好被開發、維護、測試。</p>
</li>
<li><p>讓我們用不同的方式來思考非同步的前端資料流</p>
</li>
</ul>
<a id="more"></a>
<p><img src="https://upload.wikimedia.org/wikipedia/zh/3/37/Adventure_Time_-_Title_card.png" alt="Adventure time"></p>
<blockquote>
<p>saga 的中文翻譯是冒險故事 </p>
<p>這裡來舉個例子：我們要登入</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">送出登入 request =&gt;</div><div class="line">畫面進入 loading 畫面 =&gt;</div><div class="line">if (登入成功) &#123;</div><div class="line">    取得並把 token 快取起來 =&gt; </div><div class="line">    拿到`username`以及對應的`token` =&gt; </div><div class="line">    done</div><div class="line">&#125; else &#123;</div><div class="line">    顯示錯誤訊息在首頁上</div><div class="line">    done</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>你會怎樣去設計這個資料流呢？</p>
<p>畫面要有什麼 state ？</p>
<p>假如登入要可以取消，你要怎樣改變畫面的 state 呢？</p>
<p>這個流程看似簡單，</p>
<p>但要處理的乾淨、又好測試，</p>
<p>是不是事情就沒有那麼直覺了？</p>
<p>目前看起來好像很抽象，但瞭解後，</p>
<p><code>redux-saga</code> 並沒有什麼神奇的黑魔法。</p>
<p>我不認為 <code>redux-saga</code> 的只是拿來取代 <code>redux-thunk</code>的工具，</p>
<p>重要的應該是 saga 這個 pattern 背後的概念，</p>
<p>給了你新的方式去思考前端資料流。</p>
<p><code>送出資料 =&gt; loading 動畫 =&gt; 完成</code></p>
<p>其實前端的畫面也隱含著 transaction 的概念在裡面。</p>
<p>我認為如果有出現以下幾個現象，</p>
<p>那 <code>redux-saga</code> 值得你一試：</p>
<ul>
<li><p>學會 generator function 卻無處可應用</p>
</li>
<li><p>處理非同步的 action 時，總覺得哪裡怪怪的 =&gt; 回傳 promise 時要怎麼測試</p>
</li>
<li><p>純粹好奇 <code>redux-saga</code>能幫助你什麼</p>
</li>
</ul>
<h1 id="Catalogue"><a href="#Catalogue" class="headerlink" title="Catalogue"></a>Catalogue</h1><ul>
<li><p><a href="#Introduction">Introduction</a></p>
</li>
<li><p><a href="#什麼是-Saga">什麼是 Saga</a></p>
<ul>
<li><p><a href="#Long-lived-transaction-LLT-有什麼問題">Long lived transaction (LLT)有什麼問題</a></p>
</li>
<li><p><a href="#Saga-是一種特殊的-LLT">Saga 是一種特殊的 LLT</a></p>
</li>
</ul>
</li>
<li><p><a href="#Front-end-perspective">Front-end perspective (如果你懶得看理論的話可以直接從這裡開始看)</a></p>
<ul>
<li><p><a href="#Login-flow">example: Login flow</a></p>
</li>
<li><p><a href="#Redux-thunk-的解法與問題">Redux thunk 的解法與問題</a></p>
</li>
<li><p><a href="#Front-end-中的-saga">Front-end 中的 saga</a></p>
</li>
</ul>
</li>
<li><p><a href="#Refactor-with-redux-saga">Refactor with <code>redux-saga</code></a></p>
<ul>
<li><p><a href="#Setup">Setup</a></p>
</li>
<li><p><a href="#Effect">Effect</a></p>
</li>
<li><p><a href="#Watch-action">Watch action</a></p>
</li>
<li><p><a href="#Migrate-Login-Flow-to-saga">Migrate Login Flow to saga</a></p>
</li>
<li><p><a href="#Combine-loginFlow-saga">Combine <code>loginFlow</code> saga</a></p>
</li>
</ul>
</li>
<li><p><a href="#Abortable-flow-compensating-transaction">Abortable flow(compensating transaction)</a></p>
<ul>
<li><p><a href="#fork-and-cancel"><code>fork</code> and <code>cancel</code></a></p>
</li>
<li><p><a href="#Test-for-cancelable-flow">Test for cancelable flow</a></p>
</li>
<li><p><a href="#Combine-cancelable-loginFlow">Combine cancelable <code>loginFlow</code></a></p>
</li>
<li><p><a href="#Conclusion">Conclusion</a></p>
</li>
</ul>
</li>
</ul>
<h1 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h1><p>有些人會說 <code>redux-saga</code> 的學習曲線比較陡峭，</p>
<p>其實並不盡然。</p>
<p>會覺得 <code>redux-saga</code> 太過困難，</p>
<p>通常就是因為一次就想直接學會、並應用，</p>
<p>忽略有些預先知識必須要一步一步學習，</p>
<p>而且有些情況，必須拉高一點視角會比較好看清楚，</p>
<p>從概念的角度去看，而不是只關注在前端的實作。</p>
<p>我認為這裡只有三件事情要掌握</p>
<ul>
<li><p>什麼是 saga？</p>
</li>
<li><p>saga 跟前端開發有什麼關係？</p>
</li>
<li><p>redux-saga 的基礎用法</p>
</li>
</ul>
<h1 id="什麼是-Saga"><a href="#什麼是-Saga" class="headerlink" title="什麼是 Saga"></a>什麼是 Saga</h1><p>要學一個東西，把名詞搞懂是很重要的。</p>
<p>像 router 就是個很直覺又常見的名詞，</p>
<p>saga 是什麼呢？</p>
<p><code>redux-saga</code> 有提供一些資源供參考，</p>
<p>包括了最原始提出 saga 這個 pattern 的<a href="http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf" target="_blank" rel="external">論文</a>。</p>
<p>一共 11 頁，不過扣掉 acknowledgment 跟 References ，</p>
<p>就只有 9 頁半啦！</p>
<p>不過論文中是從 Database 的角度看，</p>
<p>另一個影片，是從應用在分散式系統的角度去解釋，</p>
<p>提高了不少複雜度。</p>
<p>基於以前端的角度，這篇講解 saga 主要會以 paper 上為主。</p>
<p>saga 其實是個很簡單的概念，</p>
<p>要應用它也並不困難，</p>
<p>這篇論文在 DBMS 上實作的原因，</p>
<p>主要只是要闡明如何實做一個簡潔、有效率的 sagas，</p>
<p>所以不要擔心接下來講的例子看起來跟 redux 或前端開發沒有關係，</p>
<p>稍後會提到要怎樣在前端開發中應用 saga 這個 pattern。</p>
<p>所以看個幾分鐘之後，腦袋裡會冒出許多的問號：「所以 saga 是⋯⋯？」。</p>
<p>這裡我試著用最簡單的語言解釋 saga 是什麼。</p>
<p><strong>Saga</strong>，就是個滿足特殊條件的 <strong>LLT</strong>(Long lived transaction)。</p>
<blockquote>
<p>待會會說是什麼特殊條件。</p>
<p>如果你不知道什麼是 Transaction：</p>
<p>是 Database 上常會用到（但不僅止侷限於 Database）的名詞，</p>
<p>即是「交易」。</p>
<p>「交易」聽起來很抽象，</p>
<p>其實他要敘述的就是銀貨兩訖後，</p>
<p>一個交易才算是完成，</p>
<p>假如銀貨不兩訖的話，那要退回最一開始的時候，</p>
<p>買賣雙方的狀態會退回交易前的狀態，不會有任何改變。</p>
</blockquote>
<h2 id="Long-lived-transaction-LLT-有什麼問題"><a href="#Long-lived-transaction-LLT-有什麼問題" class="headerlink" title="Long lived transaction (LLT)有什麼問題"></a>Long lived transaction (LLT)有什麼問題</h2><p>Long lived transaction 是什麼呢？</p>
<p>而 LLT 就是一個長時間的 transaction，</p>
<p>就算沒有受到其他影響，</p>
<p>整個完成可能也需要數小時或數天。</p>
<p>聽起來，似乎是很糟糕的概念對吧？</p>
<p>因為為了實現 transaction，我們通常會把正在 transaction 中的 object lock 住，</p>
<p>讓其他人沒辦法更動它。</p>
<p>（維持資料的 consistency）</p>
<p>所以這麼長時間的 transaction，</p>
<p>會造成兩個問題：</p>
<ul>
<li><p>較高的失敗率</p>
</li>
<li><p>dead lock 造成的長時間 delay</p>
</li>
</ul>
<blockquote>
<p>舉個很實際的例子，就是江蕙演唱會的訂票。</p>
<p>購票的時間可能會是某一段時間，</p>
<p>而我們最終要確認訂票的數，這就會是一個 LLT。</p>
</blockquote>
<p>為解決這個問題，</p>
<p>我們這裡可以假設這個 LLT：<code>T</code></p>
<p>可以被拆成許多相互獨立的 subtransaction的集合:<br><code>t_1</code>~<code>t_n</code>。</p>
<p>但如果我們不會希望<code>t_1</code>~<code>t_n</code>分別被送進 DB 並且記錄下來。</p>
<blockquote>
<p>以上述江蕙演唱會的例子，<br>每個小<code>t</code>就會是每筆訂票紀錄</p>
</blockquote>
<p>如下圖：</p>
<p><img src="http://i.imgur.com/sUodUqB.jpg" alt="first state"></p>
<p>假如每個 transaction 都一次就成功，</p>
<p>而且沒有人退票的話，那個 transaction 就會正常的被執行：</p>
<p><img src="http://i.imgur.com/2P9E1wP.jpg" alt="all success"></p>
<p>因為假如有一個失敗的話，</p>
<p>那 <code>T</code> 就不算是完成的 transaction。</p>
<p>儘管如此，這樣做也比一般的 transaction 帶來了一些彈性，</p>
<p>我們可以隨意的插入 subtransaction。</p>
<p>接著就來解釋 saga 運用什麼樣的設計方式來解決這些問題。</p>
<h2 id="Saga-是一種特殊的-LLT"><a href="#Saga-是一種特殊的-LLT" class="headerlink" title="Saga 是一種特殊的 LLT"></a>Saga 是一種特殊的 LLT</h2><p>第一件要注意到的事就是 saga 仍然是個 LLT。</p>
<blockquote>
<p><code>saga</code>: LLT that can be broken up into a collection of subtransactions that can be iterleaved in any way with other transactlons </p>
</blockquote>
<p>作為一個 LLT，</p>
<p>假如任何一個 saga 中的 subtransaction: <code>t_i</code> 單獨執行了，</p>
<p>我們應該要有一個 compensating transaction <code>c_i</code> 可以將它 undo。</p>
<p>這裡的 compensating transaction，</p>
<p>指的是從語意上的觀點來看，</p>
<p>而不是整個系統都得還原到 <code>t_i</code> 發生的那個時間點。</p>
<p>再看一次上面這段話，魔鬼就藏在細節裡，</p>
<p>這正是 saga 為什麼可以解決 LLT 問題的關鍵。</p>
<blockquote>
<p>你可能會覺得這兩件事不是差不多嗎？</p>
<p>舉個例子：</p>
<p>如果有個 LLT : <code>T</code> 是要記住所有買江蕙票的座位數，</p>
<p>底下每個訂票都是一個 subtransaction: <code>t</code> 。</p>
<p>假設 <code>t_i</code> 要被買票的人取消，</p>
<p>我們執行 <code>c_i</code>時，</p>
<p>只是把買的座位數從 database 裡面減掉</p>
<p>而不是讓 database 回到 <code>t_i</code>發生前的時間點</p>
</blockquote>
<p>所以我們可以得到一個簡單的公式，</p>
<p>Saga’s gurantee：</p>
<ul>
<li><p>如果全部都執行成功(Successful saga)：</p>
<ul>
<li><code>t_1</code>, <code>t_2</code>…., <code>t_n</code></li>
</ul>
</li>
</ul>
<p>示意圖：</p>
<p><img src="http://i.imgur.com/RNCrTe0.gif" alt="success gif"></p>
<ul>
<li><p>失敗的話(Unsuccessful saga)：</p>
<ul>
<li><code>t_1</code>, <code>t_2</code>…., <code>t_n</code>, <code>c_n</code>…, <code>c_1</code></li>
</ul>
</li>
</ul>
<p><img src="http://i.imgur.com/thzgNNg.gif" alt="failed"></p>
<blockquote>
<p>這裡可以注意到其實 <code>c4</code> 是沒有做任何事情的，</p>
<p>在實作時候如果是最後一個 transaction failed 掉的話，可以忽略 <code>c4</code></p>
<p>不過就算執行了也不應該會出錯</p>
<p>因為每個執行應該都是 idempotent（冪等）的</p>
</blockquote>
<p>如此一來我們就掌握了對 saga 的基本知識了！</p>
<p>在進入<code>redux-saga</code>前，先來看看我們會遇到什麼問題</p>
<h1 id="Front-end-perspective"><a href="#Front-end-perspective" class="headerlink" title="Front-end perspective"></a>Front-end perspective</h1><h2 id="Login-flow"><a href="#Login-flow" class="headerlink" title="Login flow"></a>Login flow</h2><p>講了這麼多抽象概念的事情，</p>
<p>讓我們回到實務上來看，</p>
<p>來看最開始的這個例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">送出登入 request =&gt;</div><div class="line">畫面進入 loading 畫面 =&gt;</div><div class="line">if (登入成功) &#123;</div><div class="line">    取得並把 token 快取起來 =&gt; </div><div class="line">    拿到`username`以及對應的`token` =&gt; </div><div class="line">    done</div><div class="line">&#125; else &#123;</div><div class="line">    顯示錯誤訊息在首頁上</div><div class="line">    done</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>畫面出來大概是這樣：</p>
<p><img src="http://i.imgur.com/aWm0IqG.gif" alt="login flow"></p>
<blockquote>
<p>以下部分你可能必須要熟悉 <code>redux</code> ，</p>
<p>或是任何單向資料流的架構，</p>
<p>我盡量不預設讀者有任何預備知識來寫以下的文章 XD</p>
<p>不過真的不行的時候，會放上參考資料</p>
</blockquote>
<p>在 redux 中，如果要改變畫面的狀態(state)，</p>
<p>我們必須 dispatch 一個 action 到 store 去，</p>
<p>而對應的 reducer 會根據 action 幫我們生出下一個 state，</p>
<p>並且將 store 中的 state 更新成對應的新 state。</p>
<blockquote>
<p><code>reducer(state , action) =&gt; nextState</code></p>
<p>假如還是很模糊的話，可以看看 redux 優秀的文件：</p>
<p><a href="http://redux.js.org/" target="_blank" rel="external">redux</a></p>
</blockquote>
<p>來看一下 <code>login</code> 的 reducer 會長什麼樣子：</p>
<blockquote>
<p>這裡為了簡化，有刪去一些東西</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">login</span>(<span class="params">state = &#123;</span></span></div><div class="line">    status: 'init'</div><div class="line">&#125;, action) &#123;</div><div class="line">    <span class="keyword">switch</span> (action.type) &#123;</div><div class="line">        <span class="keyword">case</span> LOGIN_REQUEST:</div><div class="line">            <span class="keyword">return</span> &#123;status: <span class="string">'loading'</span>&#125;</div><div class="line">        <span class="keyword">case</span> LOGIN_SUCCESS:</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                status: <span class="string">'logined'</span>,</div><div class="line">                username: action.response.username,</div><div class="line">                token: action.response.token</div><div class="line">            &#125;</div><div class="line">        <span class="keyword">case</span> LOGIN_ERROR:</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                status: <span class="string">'error'</span>,</div><div class="line">                error: action.error</div><div class="line">            &#125;</div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            <span class="keyword">return</span> state</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>歸類成以下幾個結果：</p>
<ul>
<li><p><code>LOGIN_REQUEST</code>：當我們送出<code>LOGIN_REQUEST</code>這個 action 時，會進入 loading 狀態</p>
</li>
<li><p><code>LOGIN_SUCCESS</code>：登入成功，會拿到 <code>username</code> 以及對應的 <code>token</code></p>
</li>
<li><p><code>LOGIN_ERROR</code>：登入失敗，會拿到錯誤訊息</p>
</li>
</ul>
<p>那真正執行的時候該如何執行呢？</p>
<h2 id="Redux-thunk-的解法與問題"><a href="#Redux-thunk-的解法與問題" class="headerlink" title="Redux thunk 的解法與問題"></a>Redux thunk 的解法與問題</h2><p>Thunk？Is it good to drink?</p>
<p>來看一下維基百科的解釋：</p>
<blockquote>
<p>In computer programming, <strong>a thunk is a subroutine that is created, often automatically, to assist a call to another subroutine.</strong></p>
</blockquote>
<p>只截錄一小段，剩下的多看也只是搞混。</p>
<p>簡單說就是我們為了把一個 subroutine A 的工作，</p>
<p>帶到另一個 subroutine B 做完，</p>
<p>中間需要一個橋樑：subroutine C，</p>
<p>這個 C 就是 thunk 啦！</p>
<p>在 redux 中，我們如果要讓一個 action 能夠更新，</p>
<p>必須要 dispatch 它。</p>
<p>所以上述的<code>login</code>流程大概會長這個樣子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">loginFlow</span>(<span class="params">&#123;username, password&#125;</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> (dispatch) =&gt; &#123;</div><div class="line">        dispatch(loginRequest())</div><div class="line">        loginAPI(&#123;username, password&#125;)</div><div class="line">            .then(response =&gt; &#123;</div><div class="line">                dispatch(loginSucess(response))    </div><div class="line">            &#125;)</div><div class="line">            .catch(error =&gt; &#123;</div><div class="line">                dispatch(loginError(error))</div><div class="line">            &#125;)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p><code>loginRequest</code> 是一個 action creator，<br>會回傳 <code>{type: LOGIN_REQUEST}</code>這個 object。</p>
</blockquote>
<p>這裡回傳的就是一個 thunk，</p>
<p>因為我們在這個 action 裡面同時得完成：</p>
<ul>
<li><p>送request</p>
</li>
<li><p>收到 response data</p>
</li>
<li><p>處理錯誤</p>
</li>
</ul>
<p>所以我們必須把 dispatch 給傳進來，</p>
<p>完成原本只靠單個 subroutine(一般的 action creator) 無法做到的事情。</p>
<p>這裡有什麼問題呢？</p>
<ul>
<li><p>你要如何去測試這個一連串的動作？</p>
</li>
<li><p>這裡回傳的是一個 promise，它無法被 abort，如果我們今天想加上取消按鈕呢？</p>
<ul>
<li>更 low level 一點的問法：你要在哪裡 dispatch <code>loginCancel</code>這個 action 呢？</li>
</ul>
</li>
</ul>
<p>當然， login 是一個相對簡易的流程，</p>
<p>假如遇到有更多 state 要處理，</p>
<p>無法寫出測試以及不那麼直覺的語法，</p>
<p>將會為我們的開發帶來一些問題。</p>
<h2 id="Front-end-中的-saga"><a href="#Front-end-中的-saga" class="headerlink" title="Front-end 中的 saga"></a>Front-end 中的 saga</h2><p>這裡的一整個 <code>loginFlow</code>，其實就是一個 LLT(長時間的 transaction)，</p>
<blockquote>
<p><a href="#Long-lived-transaction-LLT-有什麼問題">Long lived transaction 是什麼？</a></p>
<p>可以看完這一段再回到這裡 XD</p>
</blockquote>
<p>底下的 subtransaction 就是各個 action(request, success, error)。</p>
<p>有了這樣的概念之後，剩下來的事就簡單多了。</p>
<p>而且 saga 就是底下每個 transaction 都附帶 compensating transaction 的 LLT，</p>
<p>也就是說上述的 abort ，在 saga pattern 之下是內建的。</p>
<h1 id="Refactor-with-redux-saga"><a href="#Refactor-with-redux-saga" class="headerlink" title="Refactor with redux-saga"></a>Refactor with <code>redux-saga</code></h1><h2 id="Setup"><a href="#Setup" class="headerlink" title="Setup"></a>Setup</h2><blockquote>
<p>這裡跟概念比較沒關係，</p>
<p>但環境設定絕對是許多人卡關的第一步。</p>
</blockquote>
<p>首先要建立一個 sagas 資料夾，</p>
<p>底下有一個 rootSaga，它會是一個 generator function：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>* <span class="title">rootSaga</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> [</div><div class="line">        <span class="comment">// to be done</span></div><div class="line">    ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著在 middleware 中將它跑起來。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> rootSaga <span class="keyword">from</span> <span class="string">'./sagas'</span></div><div class="line"></div><div class="line"><span class="keyword">const</span> sagaMiddleware = createSagaMiddleware()</div><div class="line"></div><div class="line"><span class="keyword">const</span> store = createStore(rootReducer,</div><div class="line">  applyMiddleware(thunkMiddleware, sagaMiddleware)</div><div class="line">)</div><div class="line"></div><div class="line">sagaMiddleware.run(rootSaga)</div></pre></td></tr></table></figure>
<p>這裡的基本設定，其實每次都大同小異，</p>
<p>所以就不再多著墨底下發生什麼事情。</p>
<h2 id="Effect"><a href="#Effect" class="headerlink" title="Effect"></a>Effect</h2><p>前面有提到的 subtransaction，可以很粗略的對應到這裡的 <code>effect</code>。</p>
<p>saga 不出以下幾種情形：</p>
<ul>
<li><p>監聽 action 發生 -&gt; take, takeEvery</p>
</li>
<li><p>執行 transaction -&gt; put </p>
</li>
<li><p>取消 transaction -&gt; cancel</p>
</li>
</ul>
<p>右邊的就是我們在 redux-saga 中對應到的 helper function，</p>
<p>他們就是 action creactor 一樣，會回傳一個物件，</p>
<p>不過這一次是回傳一個 effect ，而不是 action，</p>
<p>e.q: <code>take({type: LOGIN_REQUEST})</code> 就是產生一個拿到 loginRequest 的 effect。</p>
<p>接著就來把 code 改寫吧！</p>
<h2 id="Watch-action"><a href="#Watch-action" class="headerlink" title="Watch action"></a>Watch action</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> &#123;</div><div class="line">    takeEvery</div><div class="line">&#125; <span class="keyword">from</span> <span class="string">'redux-saga/effects'</span></div><div class="line"><span class="keyword">import</span> &#123;</div><div class="line">    LOGIN_REQUEST,</div><div class="line">    LOGIN_SUCCESS,</div><div class="line">    LOGIN_ERROR</div><div class="line">&#125; <span class="keyword">from</span> <span class="string">'../actions/login.js'</span></div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>* <span class="title">watchRequestLogin</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> takeEvery(LOGIN_REQUEST, loginFlow)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>* <span class="title">loginFlow</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="comment">// to be done</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>值得注意的是這裡都是 generator function，</p>
<p>假如你完全對 generator function 沒有概念的話，</p>
<p>推薦你看<a href="http://abalone0204.github.io/2016/05/08/es6-generator-func/" target="_blank" rel="external">這篇文章</a>。</p>
<blockquote>
<p>是我寫的 XD</p>
</blockquote>
<p>這裡的 code 還蠻語義化的，</p>
<p>就是當我們遇到一個 <code>LOGIN_REQUEST</code> 的 action ，</p>
<p>就會執行 <code>loginFlow</code> 這個 function。</p>
<p>接著是前面提到的好測試，</p>
<p>我們來測試這個 saga 吧！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">describe(<span class="string">'Sagas/ login'</span>, () =&gt; &#123;</div><div class="line">    describe(<span class="string">'watchRequestLogin'</span>, () =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> iterator = watchRequestLogin()</div><div class="line">        it(<span class="string">'should take every login request'</span>, () =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> expected = takeEvery(LOGIN_REQUEST, loginFlow)</div><div class="line">            <span class="keyword">const</span> actual = iterator.next().value</div><div class="line">            assert.equal(expected.name, actual.name)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>這裡比較 tricky 是我們測試的是 effect 的名字，</p>
<p>為什麼不是直接 deepEqual 兩個 effect？</p>
<p>我們回傳的 effect 其實就是個 object，長相是下面這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123; name: <span class="string">'takeEvery(LOGIN_REQUEST, loginFlow)'</span>,</div><div class="line">  next: [<span class="built_in">Function</span>: next],</div><div class="line">  <span class="keyword">throw</span>: [<span class="built_in">Function</span>] &#125;</div></pre></td></tr></table></figure>
<p>只要 name 是對的，我們就知道他在對應的 <code>LOGIN_REQUEST</code>進來時，</p>
<p>會執行<code>loginFlow</code> 這個 function。</p>
<blockquote>
<p>而且在JavaScript中會判斷這兩個 next 是不同 function XD</p>
<p>直接測試名字，是我現在想到比較直觀的方法</p>
</blockquote>
<h2 id="Migrate-Login-Flow-to-saga"><a href="#Migrate-Login-Flow-to-saga" class="headerlink" title="Migrate Login Flow to saga"></a>Migrate Login Flow to saga</h2><p>Talk is cheap:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>* <span class="title">loginFlow</span>(<span class="params">action</span>) </span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">const</span> response = <span class="keyword">yield</span> call(loginAPI, &#123;</div><div class="line">            username: action.username,</div><div class="line">            password: action.password</div><div class="line">        &#125;)</div><div class="line">        <span class="keyword">yield</span> put(&#123;type: LOGIN_SUCCESS&#125;)</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">catch</span>(error) &#123;</div><div class="line">        <span class="keyword">yield</span> put(&#123;type: LOGIN_ERROR, error&#125;)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>call 跟我們熟悉的 <code>Function.prototype.call</code> 很像！</p>
<p>不一樣的是，這裡的 call 會回傳的是一個 <code>effect</code>，</p>
<p>這代表什麼？代表我們能夠很好的測試它，</p>
<p>而不是真的去 call loginAPI，帶來了無止盡的 mock。</p>
<p>我們把 loginFlow 的 test 拆成四個部分來看</p>
<ul>
<li><p>Initialize</p>
</li>
<li><p>Call loginAPI</p>
</li>
<li><p>Handle login success</p>
</li>
<li><p>Handle login error</p>
</li>
</ul>
<p>前面的 watch function 會把 request 這個 action 丟進來這裡，</p>
<p>所以我們要先製造出一個待會會用到的 iterator：</p>
<blockquote>
<p>執行 Generator function 會返回一個 iterator，<br>然後我們去對這個 iterator 呼叫 <code>next</code> function<br>感謝 CT 的指正。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> iterator = loginFlow(&#123;</div><div class="line">    type: LOGIN_REQUEST,</div><div class="line">    username: <span class="string">'denny'</span>,</div><div class="line">    password: <span class="string">'12345678'</span></div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>再來則是 call API，注意我們測試的是 call effect，</p>
<p>而不是真的去呼叫這個 API：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">it(<span class="string">'should call loginAPI'</span>, () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> expected = call(loginAPI, &#123;</div><div class="line">        username: <span class="string">'denny'</span>,</div><div class="line">        password: <span class="string">'12345678'</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> actual = iterator.next().value</div><div class="line">    assert.deepEqual(expected, actual)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">it(<span class="string">'should handle login success'</span>, () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> getResponse = () =&gt; (&#123;</div><div class="line">        username: <span class="string">'denny'</span>,</div><div class="line">        token: <span class="string">'fake token'</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> expected = put(&#123;</div><div class="line">        type: LOGIN_SUCCESS,</div><div class="line">        response: &#123;</div><div class="line">            username: <span class="string">'denny'</span>,</div><div class="line">            token: <span class="string">'fake token'</span></div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> actual = iterator.next(getResponse()).value</div><div class="line">    assert.deepEqual(expected, actual)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>這裡我們可以運用 generator 的特性來把假 error 丟進去XD</p>
<p>裡面的 catch 接到 error 之後，就會執行 login error 的流程了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">it(<span class="string">'should handle login error'</span>, () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> error = <span class="string">'error message'</span></div><div class="line">    <span class="keyword">const</span> expected = put(&#123;</div><div class="line">        type: LOGIN_ERROR,</div><div class="line">        error: <span class="string">'error message'</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> actual = generator.throw(error).value</div><div class="line">    assert.deepEqual(expected, actual)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<h2 id="Combine-loginFlow-saga"><a href="#Combine-loginFlow-saga" class="headerlink" title="Combine loginFlow saga"></a>Combine loginFlow saga</h2><p>首先要把 login 的 saga 接到 root saga 去</p>
<p>接著我們要來把原本 dispatch 的 loginFlow action 換成 loginFlowSaga 了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> &#123;watchRequestLogin&#125; <span class="keyword">from</span> <span class="string">'./login.js'</span></div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>* <span class="title">rootSaga</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> [</div><div class="line">        watchRequestLogin()</div><div class="line">    ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來我們只要把原本放 loginFlow action 的地方，</p>
<p>換成 <code>loginRequest</code> 這個相對簡單的 action creator 就行了。</p>
<p>這樣也更符合實際在運作的方式，</p>
<p>他按下這個按鈕做的 action 就只是送出 request 而已，</p>
<p>剩下的部分就是讓 saga 中的 generator 去管理，</p>
<p>而且經由這樣的拆分，我們發現接下來能夠實作 <code>cancel</code> 。</p>
<blockquote>
<p>就是 saga 中的 compensating</p>
</blockquote>
<p>這裡的 code 就請到 github 上面去看了 XD</p>
<p>總之我們得到了一樣的效果，但是更容易測試以及維護：</p>
<p><img src="http://i.imgur.com/aWm0IqG.gif" alt="login flow"></p>
<h1 id="Abortable-flow-compensating-transaction"><a href="#Abortable-flow-compensating-transaction" class="headerlink" title="Abortable flow(compensating transaction)"></a>Abortable flow(compensating transaction)</h1><p>前面有說到要實作取消這個功能，</p>
<p>在 promise 中是很困難的，因為 promise 沒有辦法 abort。</p>
<p>不過我們活用 generator 的，就有辦法很直觀的實作出這個功能來。</p>
<p>首先當然是先做出 cancel 這個 action，</p>
<p>以及讓 reducer 根據這個 action 作出對應的改變。</p>
<p>完成了之後，接下來就是 saga 的重頭戲了。</p>
<h2 id="fork-and-cancel"><a href="#fork-and-cancel" class="headerlink" title="fork and cancel"></a><code>fork</code> and <code>cancel</code></h2><p>首先我們要將原本的 loginFlow 拆分成兩部分，</p>
<p>第一部分是原本的 login 流程：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">authorize</span>(<span class="params">&#123;username, password&#125;</span>)</span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">const</span> response = <span class="keyword">yield</span> call(loginAPI, &#123;</div><div class="line">            username,</div><div class="line">            password</div><div class="line">        &#125;)</div><div class="line">        <span class="keyword">yield</span> put(&#123;</div><div class="line">            type: LOGIN_SUCCESS,</div><div class="line">            response</div><div class="line">        &#125;)</div><div class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</div><div class="line">        <span class="keyword">yield</span> put(&#123;</div><div class="line">            type: LOGIN_ERROR,</div><div class="line">            error</div><div class="line">        &#125;)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>第二部分則是取消 login：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span>* <span class="title">loginFlow</span>(<span class="params">action</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> task = <span class="keyword">yield</span> fork(authorize,&#123;username:action.username, password: action.password&#125;)</div><div class="line">    <span class="keyword">yield</span> take(LOGIN_CANCEL)</div><div class="line">    <span class="keyword">yield</span> cancel(task)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裡我們看到兩個新的 effect，第一個是 fork，</p>
<p>語法基本上跟 call 相同，</p>
<p>不同的部分是 fork 跟我們在 git 上面的 fork 一樣會開一支 branch出來處理，</p>
<p>當 yield fork effect 之後，</p>
<p>就會自動開一條 branch 執行下去，這裡有個 @kuy 做的圖：</p>
<p><img src="https://pbs.twimg.com/media/CidrNh4UUAAJuSt.jpg" alt="process"></p>
<p>而如果我們在上述 task 完成之前，就接收到了 <code>loginCancel</code> 這個 action，</p>
<p>那所有在 <code>task</code> 裡面的動作就會被 abort 掉！</p>
<blockquote>
<p>是不是覺得有 race condition 的概念在裡面，<br>沒錯，<code>redux-saga</code>也提供了 <code>race</code> 這個 effect</p>
</blockquote>
<h2 id="Test-for-cancelable-flow"><a href="#Test-for-cancelable-flow" class="headerlink" title="Test for cancelable flow"></a>Test for cancelable flow</h2><p>這裡一樣也測試以下幾件事情</p>
<ul>
<li><p>是否有 fork 一個新的 task</p>
</li>
<li><p>是否能處理 cancel 這個 function</p>
</li>
<li><p>拆分出來的 authorize 是否正常運作</p>
</li>
</ul>
<p>首先當然是先看進入 loginFlow 之後有沒有 fork ：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">it(<span class="string">'should fork to authorize'</span>, () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> expected = fork(authorize, &#123;</div><div class="line">        username: <span class="string">'denny'</span>,</div><div class="line">        password: <span class="string">'12345678'</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> actual = iterator.next().value</div><div class="line">    assert.deepEqual(expected, actual)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>接下來是是否能處裡 cancel，</p>
<p>這裡我們就需要用到 mock 了，</p>
<p>在最外層的地方從 <code>redux-saga/utils</code> 引用 <code>createMockTask</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> task = createMockTask()</div><div class="line">it(<span class="string">'should take cancel login action'</span>,  () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> expected = take(LOGIN_CANCEL)</div><div class="line">    <span class="keyword">const</span> actual = iterator.next(task).value</div><div class="line">    assert.deepEqual(expected, actual)            </div><div class="line">&#125;)</div><div class="line"></div><div class="line">it(<span class="string">'should cancel the login task'</span>,  () =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> expected = cancel(task)</div><div class="line">    <span class="keyword">const</span> actual = iterator.next().value</div><div class="line">    assert.deepEqual(expected, actual)            </div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>這裡仍然是運用了 generator 的特性來做 mock，</p>
<p>因為我們再隔一個動作才能取消 task，</p>
<p>所以在這之前我們要先把 mock 起來的 task 丟進去。</p>
<p>最後則是確認原本的 authorize 流程還是能正常運作，</p>
<p>基本上只是把原本的 test case 丟進另一個 describe 的 block 而已，</p>
<p>詳情可以去看 repo 裡的 code。</p>
<h2 id="Combine-cancelable-loginFlow"><a href="#Combine-cancelable-loginFlow" class="headerlink" title="Combine cancelable loginFlow"></a>Combine cancelable loginFlow</h2><p>其實這裡蠻簡單的，</p>
<p>只是新增一個按鈕，按了會 dispatch<code>cancelLogin</code>這個action，</p>
<p>一切就結束了。 </p>
<p>像是底下這個樣子：</p>
<p><img src="http://i.imgur.com/CWhs8xi.gif" alt="cancel"></p>
<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>結論就是我們現在終於將 saga pattern 應用在前端了，</p>
<p>每一個好的 UX 都會是一個 transaction，</p>
<p>而且比起原本的論文中，我們多了一些彈性，</p>
<p>可以選擇要不要加上 compensating transiction。</p>
<p>如此一來我們的非同步 action 變得更好測試，</p>
<p>而且也不用擔心在每次處理過度複雜的資料流時，</p>
<p>沒有依據可找了，因為我們都是在組合各種 effect 而已XD</p>
<h1 id="參考資料"><a href="#參考資料" class="headerlink" title="參考資料"></a>參考資料</h1><ul>
<li><p><a href="http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf" target="_blank" rel="external">sagas original paper by Hector Garcia-Molina &amp; Kenneth Salem</a></p>
</li>
<li><p><a href="https://github.com/abalone0204/redux-thunk-to-saga-tutorial" target="_blank" rel="external">redux-thunk-to-saga-tutorial</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;blockquote&gt;
&lt;p&gt;這是篇長文，你可以直接跳到&lt;a href=&quot;/2016/05/14/redux-saga/#Catalogue&quot;&gt;你想看的地方&lt;/a&gt;就好&lt;br&gt;或是直接在 github 上面看我 step by step 的教學&lt;br&gt;&lt;a href=&quot;https://github.com/abalone0204/redux-thunk-to-saga-tutorial/commit/1a4455b23ce6bc434d17a8c2ebcbf9e80e922be5&quot;&gt;redux-thunk-to-saga-tutorial&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;先把結論講在一開始，這並不只是一個 library 的使用方法介紹而已，&lt;/p&gt;
&lt;p&gt;因為學習 saga pattern 對於前端工程師是有幫助的，&lt;/p&gt;
&lt;p&gt;主要不出以下三個概念：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;好的 UI/UX 該是一個畫面的 transaction&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;User 隨時能夠取消 transaction&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;滿足上述條件實作出來的資料流是要容易被測試的&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;那&lt;code&gt;redux-saga&lt;/code&gt;到底是在解決什麼問題呢？&lt;/p&gt;
&lt;p&gt;答案：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;讓我們的非同步 action 能夠更好被開發、維護、測試。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;讓我們用不同的方式來思考非同步的前端資料流&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
    
    </summary>
    
    
      <category term="redux" scheme="http://abalone0204.github.com/tags/redux/"/>
    
      <category term="saga" scheme="http://abalone0204.github.com/tags/saga/"/>
    
      <category term="redux-saga" scheme="http://abalone0204.github.com/tags/redux-saga/"/>
    
  </entry>
  
  <entry>
    <title>淺入淺出 Generator Function</title>
    <link href="http://abalone0204.github.com/2016/05/08/es6-generator-func/"/>
    <id>http://abalone0204.github.com/2016/05/08/es6-generator-func/</id>
    <published>2016-05-08T21:43:08.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>es 2015 中有一項新的 feature 叫做 <strong>generator function</strong>，</p>
<p>假如熟稔其他語言的人，</p>
<p>可能都知道 generator function 是什麼，</p>
<p>不過對於一位平常都在寫原生 JavaScript 的人，這就很新鮮了。</p>
<blockquote>
<p>當然，generator 就算在 es 裡面也不算是什麼太新鮮的東西。<br>畢竟跟 JavaScript 有關的東西大概超過一個月就算舊的了</p>
</blockquote>
<p>使用 Generator function 並不是一件求新求潮的一件事情，</p>
<p>活用 Generator function 能讓測試以及開發非同步的程式碼都變得更直觀。</p>
<p>這篇文章就來淺淺的介紹一下 Generator function 究竟是什麼。</p>
<a id="more"></a>
<p>之所以是<strong>淺淺的介紹</strong>是因為，</p>
<p>我認為深入介紹太多不同的特性，</p>
<p>沒有搭配實際的應用，</p>
<p>那其實只是一篇寫的比較詳細的 document，</p>
<p>所以這篇只打算介紹到「可以用」的程度而已。</p>
<p><img src="http://www.rumproast.com/images/uploads/shallow_end_thumb.jpg" alt="shallow"></p>
<p>這篇文章的圖片就是在提醒你這是一篇淺淺的文章，</p>
<p>讓我們慢慢跳進去，才不會一開始就把頭撞爛。</p>
<blockquote>
<p>其實本來是要寫關於<code>redux-saga</code>的，<br>只是不先介紹 generator 真的講不下去 Q_Q</p>
</blockquote>
<p>這篇會包含以下幾個主題：</p>
<ul>
<li><p><a href="#Generator-function-是什麼">Generator function 是什麼</a></p>
</li>
<li><p><a href="#Syntax">Syntax</a></p>
<ul>
<li><p><a href="#宣告一個-generator-function">宣告一個 Generator function</a></p>
</li>
<li><p><a href="#yield"><code>yield</code></a></p>
</li>
<li><p><a href="#next"><code>next</code></a></p>
</li>
<li><p><a href="#在-next-中傳入參數">在 <code>next</code> 中傳入參數</a></p>
</li>
<li><p><a href="#for-of"><code>for...of</code></a></p>
</li>
<li><p><a href="#Error-handling-Optional">Error handling(optional)</a></p>
</li>
<li><p><a href="#Delegating-Generators-Generator-中的-generator-optional">Delegating Generators - Generator 中的 generator (optional)</a></p>
</li>
</ul>
</li>
<li><p><a href="#如何啟用-Generator-function">如何啟用 Generator function</a></p>
</li>
<li><p><a href="#實際上的應用">實際上的應用</a></p>
</li>
</ul>
<hr>
<h1 id="Generator-function-是什麼"><a href="#Generator-function-是什麼" class="headerlink" title="Generator function 是什麼"></a>Generator function 是什麼</h1><p>先來講講我們熟悉的 function：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;=<span class="number">1E10</span>; i++) &#123;</div><div class="line">        <span class="built_in">console</span>.log(i);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 0, 1, 2.... 1E10</span></div></pre></td></tr></table></figure>
<p>是個 run-to-completion 的 function，</p>
<p>一旦進去了，就會一直執行到結束，</p>
<p>看上述的 code 就知道這個東西會執行的非常非常久，</p>
<p>因為它一旦進入，就要執行到被完成為止。</p>
<p>generator function 特別的地方就是它可以被暫停，</p>
<p>等到下次進來時再繼續呼叫它。</p>
<p>先看下方這個改寫過後的小例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">generatorFoo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;=<span class="number">1E10</span>; i++) &#123;</div><div class="line">        <span class="built_in">console</span>.log(i)</div><div class="line">        <span class="keyword">yield</span> i</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> iterator = generatorFoo()</div><div class="line"></div><div class="line">iterator.next() <span class="comment">// 0</span></div><div class="line">iterator.next() <span class="comment">// 1</span></div><div class="line">iterator.next() <span class="comment">// 2</span></div></pre></td></tr></table></figure>
<p>可能會有點不熟悉這樣的語法，</p>
<p>不過可以先感受一下一次拿一個值出來，</p>
<p>以及可以被暫停的 function 是長什麼樣子。</p>
<p>下面來更清楚地敘述一下 generator function 的語法。</p>
<h1 id="Syntax"><a href="#Syntax" class="headerlink" title="Syntax"></a>Syntax</h1><h2 id="宣告一個-generator-function"><a href="#宣告一個-generator-function" class="headerlink" title="宣告一個 generator function"></a>宣告一個 generator function</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">generatorFoo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>function</code> 後面或多個 <code>*</code>。</p>
<blockquote>
<p>有人會爭論到底是要放在 function 關鍵字後面，<br>還是直接放在 function 名字前面<br>e.q: <code>function *generatorFoo</code><br>兩個都是合格的語法，<br>不過我習慣放在 <code>function</code> 關鍵字後面，<br>我認為這是個不同的 <code>function</code>，<br>而且 function name 本身並不該包含 <code>*</code><br>至於參考資料裡面有附上 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*" target="_blank" rel="external">MDN 中對於 generator function 的語法介紹</a>，<br>也將 <code>*</code> 放在緊接著 <code>function</code> 關鍵字的後方。<br>這一部份還沒做過更全面的研究，<br>畢竟最近也才在實作中加入 generator function 而已</p>
</blockquote>
<h2 id="yield"><a href="#yield" class="headerlink" title="yield"></a><code>yield</code></h2><p>這個關鍵字估計就是 generator 中最特別的概念了，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">generatorFoo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;=<span class="number">1E10</span>; i++) &#123;</div><div class="line">        <span class="built_in">console</span>.log(i)</div><div class="line">        <span class="keyword">yield</span> i</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>當我們呼叫 <code>generatorFoo</code> 時，</p>
<p>會得到一個 iterator，</p>
<p>當我們每次呼叫這個 iterator 的 <code>next</code> 方法時，</p>
<p>就會執行 <code>generatorFoo</code>，一直到出現 <code>yield</code> 關鍵字的地方，</p>
<p>接下來會暫停，直到下次呼叫 <code>next</code>。</p>
<blockquote>
<p>我知道還有 <code>yield*</code>，不過這個概念等後面再說</p>
</blockquote>
<h2 id="next"><a href="#next" class="headerlink" title="next"></a><code>next</code></h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> iterator = generatorFoo()</div><div class="line"></div><div class="line">iterator.next() <span class="comment">// 0</span></div></pre></td></tr></table></figure>
<p>像以上的例子，第一次呼叫 <code>next</code> 時，</p>
<p>就會執行到 <code>yield i</code> 這個位置，接著暫停這個函數，</p>
<p>直到下次執行<code>next</code>。</p>
<ul>
<li><code>next()</code> 返回什麼？</li>
</ul>
<p><code>next</code> function 會返回一個物件，裡面包含著兩個 properties，</p>
<p>分別是 <code>value</code> 和 <code>done</code>：</p>
<p><code>value</code>，就是我們在前一段中從 <code>yield</code> 那個位置，</p>
<p>接到的「值」。</p>
<p><code>done</code> 是個 boolean 值，</p>
<p>假如這個 generator function 完全被執行完的話，</p>
<p><code>done</code>就會變成 <code>true</code>，反之亦然。</p>
<p>這裡要注意的是當執行到最後一個 <code>yield</code> 時，</p>
<p><code>done</code> 仍然會是 <code>false</code>，</p>
<p>再執行一次才會得到 <code>done</code> 為 <code>true</code> 的結果。</p>
<p>而 generator function 仍然是一個 function，</p>
<p>我們可以在裡面 <code>return</code> 東西，</p>
<p>如此在執行到 <code>return</code> 這一行時，</p>
<p><code>next</code> 就會返回 <code>value</code> 為 <code>return</code>的東西，</p>
<p>並且 <code>done</code> 為 <code>true</code>。</p>
<blockquote>
<p><strong>提醒</strong>：<br>如果你真的需要 return，那你很可能只需要普通的 function 就足夠<br>在 generator function 裡面 return 東西，<br>容易令人感到困惑，簡言之，沒事別這樣做。</p>
</blockquote>
<h2 id="在-next-中傳入參數"><a href="#在-next-中傳入參數" class="headerlink" title="在 next 中傳入參數"></a>在 <code>next</code> 中傳入參數</h2><p>我們可以這樣做：<code>next(x)</code> ，</p>
<p>這樣做的結果就是將<code>x</code>塞入前一個 <code>yield</code> 產生的地方。</p>
<p>直接看例子會更有感覺</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// source from:  https://davidwalsh.name/es6-generators</span></div><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params">x</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> y = <span class="number">2</span> * (<span class="keyword">yield</span> (x + <span class="number">1</span>));</div><div class="line">    <span class="keyword">const</span> z = <span class="keyword">yield</span> (y / <span class="number">3</span>);</div><div class="line">    <span class="keyword">return</span> (x + y + z);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> iterator = foo(<span class="number">5</span>);</div><div class="line"></div><div class="line"><span class="built_in">console</span>.log(iterator.next());       <span class="comment">// &#123; value:6, done:false &#125;</span></div><div class="line"><span class="built_in">console</span>.log( iterator.next( <span class="number">12</span> ) );   <span class="comment">// &#123; value:8, done:false &#125;</span></div><div class="line"><span class="built_in">console</span>.log( iterator.next( <span class="number">13</span> ) );   <span class="comment">// &#123; value:42, done:true &#125;</span></div></pre></td></tr></table></figure>
<p>第一個 <code>next</code> 不傳入參數是因為在這之前，</p>
<p>不會有前面一個 <code>yield</code>。</p>
<p>而第二個 <code>next</code> 中傳入的 <code>12</code>完全替代掉了前面 <code>x+1</code> 的值，</p>
<p>所以後面的 <code>z</code> 會等於 <code>12*2/3</code>，也就是 <code>8</code>。</p>
<p>最後一個傳入 <code>13</code>，是替代掉第二個 <code>yield</code> 所產生的值，</p>
<p>這裡已經可以完全忽略 <code>y/3</code> 是什麼，直接替代成 <code>13</code>了。</p>
<p>將上述的值全部替代進去會長成下面這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params">x</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> y = <span class="number">2</span>* (<span class="number">12</span>)</div><div class="line">    <span class="keyword">const</span> z = (<span class="number">13</span>)</div><div class="line">    <span class="keyword">return</span> <span class="number">5</span>+<span class="number">24</span>+<span class="number">13</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>看起來很蠢沒錯，<br>不過這樣替代值的方式也許比直接文字描述來的更直觀一些</p>
</blockquote>
<h2 id="for-of"><a href="#for-of" class="headerlink" title="for...of"></a><code>for...of</code></h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> <span class="number">0</span></div><div class="line">    <span class="keyword">yield</span> <span class="number">1</span></div><div class="line">    <span class="keyword">return</span> <span class="number">2</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我們一樣可以使用 <code>for</code> 來遍歷整個 iterator，</p>
<p>不過要注意的是，我們只會拿出 <code>done</code>為 <code>false</code> 的值，</p>
<p>也就是說上述的 <code>2</code> 並不會在 <code>for...of</code> 中被拿到。</p>
<h2 id="Error-handling-Optional"><a href="#Error-handling-Optional" class="headerlink" title="Error handling (Optional)"></a>Error handling (Optional)</h2><p>雖然說是 optional，</p>
<p>不過為了在實戰中時寫出更 robust 的程式碼，</p>
<p>瞭解 error 要如何處理是很重要的，</p>
<p>畢竟你連丟出來都沒辦法， unit-test 就測不了啦！</p>
<p>在 generator 中可以用我們熟悉的 try…catch 技法來做到 error handling：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">const</span> x = <span class="keyword">yield</span> <span class="number">3</span>;</div><div class="line">        <span class="built_in">console</span>.log( <span class="string">"x: "</span> + x ); <span class="comment">// may never get here!</span></div><div class="line">    &#125;</div><div class="line">    <span class="keyword">catch</span> (err) &#123;</div><div class="line">        <span class="built_in">console</span>.log( <span class="string">"Error: "</span> + err );</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>不一樣的是我們能在外面直接把 error 丟進去：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> iterator = foo()</div><div class="line">iterator.next() <span class="comment">// x: 3</span></div><div class="line">                <span class="comment">// &#123;value: 3, done: false&#125;</span></div><div class="line">iterator.throw(<span class="string">'error messages'</span>) <span class="comment">// Error: error messages</span></div></pre></td></tr></table></figure>
<p>這裡有個比較 tricky 的地方是我們把 error 給丟進去後，</p>
<p>如果在 generator 內部沒有catch 到，</p>
<p>這個 error 就會丟出來外面被 catch 住：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params"></span>) </span>&#123; &#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> iterator = foo();</div><div class="line"><span class="keyword">try</span> &#123;</div><div class="line">    iterator.throw( <span class="string">"error message"</span> );</div><div class="line">&#125;</div><div class="line"><span class="keyword">catch</span> (err) &#123;</div><div class="line">    <span class="built_in">console</span>.log( <span class="string">"Error: "</span> + err ); <span class="comment">// Error: error message</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Delegating-Generators-Generator-中的-generator-optional"><a href="#Delegating-Generators-Generator-中的-generator-optional" class="headerlink" title="Delegating Generators - Generator 中的 generator (optional)"></a>Delegating Generators - Generator 中的 generator (optional)</h2><p>我其實不喜歡用 delegate 這個字來解釋，</p>
<p>總覺得有點在賣弄的感覺 XD。</p>
<p>簡言之就是將遍歷 generator 的控制權交（delegate=委託）給內層的 generator。</p>
<p>Talk is cheap, show me the code:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> <span class="number">3</span></div><div class="line">    <span class="keyword">yield</span> <span class="number">4</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span>* <span class="title">bar</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">yield</span> <span class="number">1</span></div><div class="line">    <span class="keyword">yield</span> <span class="number">2</span></div><div class="line">    <span class="keyword">yield</span>* foo() <span class="comment">// `yield *` delegates iteration control to `foo()`</span></div><div class="line">    <span class="keyword">yield</span> <span class="number">5</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">for</span> (<span class="keyword">let</span> v <span class="keyword">of</span> bar()) &#123;</div><div class="line">    <span class="built_in">console</span>.log(v)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>執行到 <code>yield* foo()</code> 時，</p>
<p>就會把控制權交到 <code>foo()</code> 所產生的 iterator 上，</p>
<p>所以最後那個 <code>for...of</code> 就會印出 1~5 。</p>
<p>基本上就是這樣而已，我認為了解到這點就已足夠，</p>
<p>在這裡敘述太多語法卻沒加上實際應用，</p>
<p>真的只會搞混而已，</p>
<p>所以請容我到之後應用篇時再繼續說明 delegating 的好處。</p>
<p>如果現在就想再鑽下去，可以看下方的參考資料。</p>
<h1 id="如何啟用-Generator-function"><a href="#如何啟用-Generator-function" class="headerlink" title="如何啟用 Generator function"></a>如何啟用 Generator function</h1><p>假如你是使用 webpack 來做前端資源的打包，</p>
<p>恭喜你，這是一件再簡單不過的事情；</p>
<p>假如不是的話，你可以：</p>
<ul>
<li><p>學會使用 webpack</p>
</li>
<li><p>或是想辦法跟 Babel 搭起來</p>
</li>
</ul>
<p>我們這裡會運用 babel 來幫我們非常簡便的在專案中啟用 generator function。</p>
<blockquote>
<p><a href="https://babeljs.io/" target="_blank" rel="external">https://babeljs.io/</a></p>
</blockquote>
<p>當然，如果要連 webpack 一起介紹會太囉唆，</p>
<p>以下都假設你已經會實際使用 webpack 的 babel-loader：</p>
<p>es2015 這個 preset 已經包含了 generator function。</p>
<p>preset 只幫我們做到 transform 的功能，</p>
<p>真正要在實際環境中動起來還需要 polyfill 的幫忙：</p>
<p>所以我們必須要安裝：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">npm install --save-dev babel-preset-es2015</div><div class="line">npm install --save babel-polyfill</div></pre></td></tr></table></figure>
<p>接著在 <code>.babelrc</code> 中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  <span class="string">"presets"</span>: [<span class="string">"es2015"</span>, <span class="string">"react"</span>]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最後在你要用到 generator function 的地方加上 <code>import &#39;babel-polyfill&#39;</code>。</p>
<blockquote>
<p>其實這裡不一定需要用到整包 polyfil，<br>只要有<code>regeneratorRuntime</code>被定義好就行了<br>有興趣的人可以參考一下 facebook 的 <a href="https://github.com/facebook/regenerator" target="_blank" rel="external">regenerator</a><br>babel-polyfill 裡面也是用到這個 project</p>
</blockquote>
<h1 id="實際上的應用"><a href="#實際上的應用" class="headerlink" title="實際上的應用"></a>實際上的應用</h1><p>其實這篇文章主要是系統性的介紹 generator 到底是什麼，</p>
<p>下篇文章會介紹我們實際在應用時，</p>
<p>generator 能幫助我們做到什麼。</p>
<p>如果要一言以蔽之的話，</p>
<p>那就是：</p>
<p>「能將非同步的程式碼，用同步的語法來呈現。」</p>
<p>乍看之下很神奇，</p>
<p>但在了解 generator function 不過就是個能夠暫停、繼續的 function 後，</p>
<p>就大概能對他能做到的事有最初步的想像了。</p>
<h1 id="參考資料"><a href="#參考資料" class="headerlink" title="參考資料"></a>參考資料</h1><ul>
<li><p><a href="https://davidwalsh.name/es6-generators" target="_blank" rel="external">The Basics Of ES6 Generators</a></p>
</li>
<li><p><a href="https://davidwalsh.name/es6-generators-dive" target="_blank" rel="external">Diving Deeper With ES6 Generators</a></p>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*" target="_blank" rel="external">function*</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;es 2015 中有一項新的 feature 叫做 &lt;strong&gt;generator function&lt;/strong&gt;，&lt;/p&gt;
&lt;p&gt;假如熟稔其他語言的人，&lt;/p&gt;
&lt;p&gt;可能都知道 generator function 是什麼，&lt;/p&gt;
&lt;p&gt;不過對於一位平常都在寫原生 JavaScript 的人，這就很新鮮了。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;當然，generator 就算在 es 裡面也不算是什麼太新鮮的東西。&lt;br&gt;畢竟跟 JavaScript 有關的東西大概超過一個月就算舊的了&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;使用 Generator function 並不是一件求新求潮的一件事情，&lt;/p&gt;
&lt;p&gt;活用 Generator function 能讓測試以及開發非同步的程式碼都變得更直觀。&lt;/p&gt;
&lt;p&gt;這篇文章就來淺淺的介紹一下 Generator function 究竟是什麼。&lt;/p&gt;
    
    </summary>
    
    
      <category term="es6" scheme="http://abalone0204.github.com/tags/es6/"/>
    
      <category term="generator" scheme="http://abalone0204.github.com/tags/generator/"/>
    
      <category term="function" scheme="http://abalone0204.github.com/tags/function/"/>
    
  </entry>
  
  <entry>
    <title>Super tiny compiler</title>
    <link href="http://abalone0204.github.com/2016/04/25/Super-tiny-compiler/"/>
    <id>http://abalone0204.github.com/2016/04/25/Super-tiny-compiler/</id>
    <published>2016-04-25T23:04:37.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>造一個超級小又可愛的 Compiler，</p>
<p>沒有組語，只有 JavaScript。</p>
<a id="more"></a>
<p><img width="731" alt="THE SUPER TINY COMPILER" src="https://cloud.githubusercontent.com/assets/952783/14413766/134c4068-ff39-11e5-996e-9452973299c2.png"></p>
<h1 id="前言：被玩壞的工具鏈"><a href="#前言：被玩壞的工具鏈" class="headerlink" title="前言：被玩壞的工具鏈"></a>前言：被玩壞的工具鏈</h1><p>之前看到 react-motion 的作者說了這句話：</p>
<p><blockquote class="twitter-tweet" data-lang="zh-tw"><p lang="en" dir="ltr">Lisp: everything&#39;s data<br>Smalltalk: everything&#39;s an object<br>Haskell: everything&#39;s computation<br>JavaScript: everything&#39;s a library</p>&mdash; Cheng Lou (@_chenglou) <a href="https://twitter.com/_chenglou/status/722640025092009986" target="_blank" rel="external">2016年4月20日</a></blockquote></p>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<p>老實說，不知道從什麼時候開始，</p>
<p>我們前端工程師大多都變成工具的使用者，而不是設計者了，</p>
<p>真正基礎和有價值的事物其實一直都隱藏在我們常使用的工具底下，</p>
<p>像是我們為了使用 es6 語法的 babel 就是一個很好的例子，</p>
<p>好好靜下心來寫一個小小的 lisp compiler，瞭解底下發生了什麼事情，</p>
<p>以及弄懂 compiler 究竟是多麽偉大的想法，</p>
<p>對於一個前端工程師的身心健康都頗有幫助。</p>
<blockquote>
<p>至少對我來說是這樣啦！</p>
</blockquote>
<h1 id="Compiler"><a href="#Compiler" class="headerlink" title="Compiler"></a>Compiler</h1><p>提到 Compiler 總是讓人望而生卻，</p>
<p>在 ember conf 上， James Kyle講的這個 <a href="https://www.youtube.com/watch?v=Tar4WgAfMr4" target="_blank" rel="external">talk</a>，</p>
<p>讓我覺得該記錄一下這篇文章，</p>
<p>好好推廣一下 Babel 底下發生了什麼事情。</p>
<p>首先先來談談 Compiler 是在做什麼的，</p>
<p>Compiler 的工作是將「來源代碼」轉成「目標語言」。</p>
<p>除了我們熟知的 gcc 之外，還有 Babel，</p>
<p>沒錯，我們的生活周遭充滿了 compiler，</p>
<p>就算是寫 JavaScript，</p>
<p>如果要使用 es6 以上的語法，</p>
<p>你就必須得用到 Babel 這個 compiler。</p>
<p>將你寫的 code(來源代碼)轉成現在瀏覽器上跑得動的 JavaScript（目標代碼）。</p>
<blockquote>
<p>關於這樣子使用是否合法，已經在 twitter 問過作者，</p>
<p>相關的 license 也放在最下方了。</p>
</blockquote>
<h1 id="Prerequisite"><a href="#Prerequisite" class="headerlink" title="Prerequisite"></a>Prerequisite</h1><ul>
<li><p>懂 JavaScript(老實說不懂也沒什麼差)</p>
</li>
<li><p>不需要懂 Lisp（沒錯，雖然我很喜歡 Lisp）</p>
</li>
</ul>
<blockquote>
<p>有人要一起開 SICP 的讀書會嗎？XD</p>
</blockquote>
<ul>
<li><p>懂得寫出簡單的遞回函數</p>
</li>
<li><p>Regular Expression</p>
</li>
</ul>
<p>這裡不會使用 ES 6 的語法，</p>
<p>主要原因只是想讓環境配置盡量單純簡單，</p>
<p>只要有辦法使用 JavaScript 的人就可以讓這個小 compiler 跑起來。</p>
<p>這裡要 compile 的不是 babel 或 js，</p>
<p>而是 lisp，原因是因為語法單純簡單得多，</p>
<p>能夠讓我們更專注在 compiler 的概念和抽象化上。</p>
<h1 id="三個步驟"><a href="#三個步驟" class="headerlink" title="三個步驟"></a>三個步驟</h1><p>影片中有提到，要做出一個 compiler，</p>
<p>基本上只需要三步就完成了：</p>
<ul>
<li><p>Parsing：將 code 轉成抽象化的樹狀格式，方便轉化。</p>
</li>
<li><p>Trasformation：將 Abastract syntax tree（之後會講到）轉化成好生成 code 的形式</p>
</li>
<li><p>Code Generation：產生目標的程式碼，這裡是 JavaScript</p>
</li>
</ul>
<p>坦白說現在看起來是蠻直觀的想法，</p>
<p>但這種事情，都碼是你想出來之後就覺得很簡單，</p>
<p>所以做完一遍之後，反而更能感受到設計 compiler 是一件多麽偉大的事情。</p>
<blockquote>
<p>想當年臉書紅的時候，多少人說過自己當年也想要做一個社群網站呢 XD</p>
</blockquote>
<h1 id="Goal"><a href="#Goal" class="headerlink" title="Goal"></a>Goal</h1><p>開始之前，先定義一下我們要完成什麼事情。</p>
<p>我們要將：</p>
<figure class="highlight scheme"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(<span class="name">add</span> <span class="number">22</span> (<span class="name">subtract</span> <span class="number">43</span> <span class="number">2</span>))</div></pre></td></tr></table></figure>
<p>Compile 成：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">add(<span class="number">22</span>, subtract(<span class="number">43</span>, <span class="number">2</span>))</div></pre></td></tr></table></figure>
<p>就是這樣而已。<del>應該沒有很難吧？</del></p>
<p>綜合一下前面講的，我們要寫的 compiler 會長這個樣子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">compiler</span>(<span class="params">input</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> tokens = lexer(input);</div><div class="line">    <span class="keyword">var</span> ast = parser(tokens);</div><div class="line">    <span class="keyword">var</span> nextAst = transformer(ast);</div><div class="line">    <span class="keyword">var</span> output = codeGenerator(nextAst);</div><div class="line">    <span class="keyword">return</span> output;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="1-Parsing"><a href="#1-Parsing" class="headerlink" title="1. Parsing"></a>1. Parsing</h1><p>Parser（或稱 lexer），</p>
<p>會將 raw code 先切成一塊一塊後，</p>
<p>再根據這些小塊的語義來建立一個 <strong>Abstract Syntax Tree</strong>（以下簡稱 AST）。</p>
<p>這裡很明顯的分成兩個步驟：</p>
<ol>
<li><p><strong>Lexical Analysis</strong>：就是分詞啦！把 code 切成一塊塊的 tokens。</p>
</li>
<li><p><strong>Syntatic Analysis</strong>：將上一個步驟的 tokens 轉成 AST</p>
</li>
</ol>
<h2 id="1-a-Parsing-Lexical-Analysis"><a href="#1-a-Parsing-Lexical-Analysis" class="headerlink" title="1-a Parsing: Lexical Analysis"></a>1-a Parsing: Lexical Analysis</h2><p>Lisp 的語法相當簡單，而且我們沒有要實作所有的語法 XD</p>
<p>目前看到的就是分成三種：Letters、Numbers，跟 Paranthesis。</p>
<blockquote>
<p>會將多餘的空白忽略，因為空白的區隔是為了讓開發者好讀</p>
</blockquote>
<p>就以這三個去分，先寫出三個 regular expression 來：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> WHITE_SPACE = <span class="regexp">/[\s]/</span>;</div><div class="line"><span class="keyword">var</span> NUMBERS = <span class="regexp">/[0-9]/</span>;</div><div class="line"><span class="keyword">var</span> LETTERS = <span class="regexp">/[a-z]/i</span>;</div></pre></td></tr></table></figure>
<p>接著要 iterate 輸入的 raw code：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> current = <span class="number">0</span>;</div><div class="line"><span class="keyword">var</span> tokens = [];</div><div class="line"><span class="keyword">while</span>(current &lt; input.length) &#123;</div><div class="line">    <span class="comment">// Lexical analysis</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>首先第一個就是先略過空白</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (WHITE_SPACE.test(char)) &#123;</div><div class="line">    current += <span class="number">1</span>;</div><div class="line">    <span class="keyword">continue</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來是括號</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (char === <span class="string">'('</span> || char === <span class="string">')'</span>) &#123;</div><div class="line">    tokens.push(&#123;type: <span class="string">'parenthesis'</span>, value: char&#125;)</div><div class="line">    current += <span class="number">1</span>; </div><div class="line">    <span class="keyword">continue</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最後兩個有點像，分別是 <code>NUMBERS</code> 和 <code>LETTERS</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (NUMBERS.test(char)) &#123;</div><div class="line">    <span class="keyword">var</span> value = <span class="string">''</span>;</div><div class="line">    <span class="keyword">while</span>(NUMBERS.test(char)) &#123;</div><div class="line">        value += char</div><div class="line">        current += <span class="number">1</span>;</div><div class="line">        char = input[current];</div><div class="line">    &#125;</div><div class="line">    tokens.push(&#123;type: <span class="string">'number'</span>, value: value&#125;);</div><div class="line">    <span class="keyword">continue</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">if</span> (LETTERS.test(char)) &#123;</div><div class="line">    <span class="keyword">var</span> value = <span class="string">''</span>;</div><div class="line">    <span class="keyword">while</span>(LETTERS.test(char)) &#123;</div><div class="line">        value += char</div><div class="line">        current += <span class="number">1</span>;</div><div class="line">        char = input[current];</div><div class="line">    &#125;</div><div class="line">    tokens.push(&#123;type: <span class="string">'name'</span>, value: value&#125;);</div><div class="line">    <span class="keyword">continue</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>以數字為例，只要碰到了第一個數字，</p>
<p>就會接著把剩下遇到連續的數字一起推進去。</p>
<p>所以這一階段我們會得到一個 tokens：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">[ &#123; type: <span class="string">'parenthesis'</span>, value: <span class="string">'('</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'name'</span>, value: <span class="string">'add'</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'number'</span>, value: <span class="string">'22'</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'parenthesis'</span>, value: <span class="string">'('</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'name'</span>, value: <span class="string">'subtract'</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'number'</span>, value: <span class="string">'43'</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'number'</span>, value: <span class="string">'2'</span> &#125;,</div><div class="line">  &#123; type: <span class="string">'parenthesis'</span>, value: <span class="string">')'</span> &#125; ]</div></pre></td></tr></table></figure>
<p>最後，如果沒有對應的 type，</p>
<p>會丟出一個 Type Error：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'I dont know what this character is: '</span> + char);</div></pre></td></tr></table></figure>
<p>完整的 <code>lexer</code> 在<a href="https://github.com/abalone0204/super-tiny-compiler-practice/blob/master/super-tiny-compiler.js#L1:L56" target="_blank" rel="external">這裡</a>可以看到</p>
<blockquote>
<p>為了方便寫成文章，所以做了一些改寫 XD</p>
<p>順序也有所調動。</p>
<p>畢竟原本是在半小時內要講完的事情，</p>
<p>原作者 James Kyle 也樂見有更多人對 Compiler 有興趣，</p>
<p>詳細情形見最下方 License，請不要擔心。</p>
</blockquote>
<h2 id="1-b-Parsing-Syntatic-Analysis"><a href="#1-b-Parsing-Syntatic-Analysis" class="headerlink" title="1-b. Parsing: Syntatic Analysis"></a>1-b. Parsing: Syntatic Analysis</h2><p>這一階段的任務就是把 tokens 轉成 <strong>AST</strong>。</p>
<p>這裡應該是最容易卡關的部分 XD，</p>
<p>不過讓我們慢慢來，並感受一下為什麼要這樣做。</p>
<p>這裡會運用到遞迴，減少各種迴圈，大大減低了 code 的數量，</p>
<p>也提高了可讀性，而且看起來還很帥。</p>
<p>有句話說得好：</p>
<blockquote>
<p>「嫩嫩迴圈，大大遞迴。」</p>
</blockquote>
<p>只要能遞迴，就一定要遞迴一下。</p>
<p>來看一下 parser 的結構是怎麼樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">parser</span>(<span class="params">tokens</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> current = <span class="number">0</span>;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">walk</span>(<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="comment">// Walk</span></div><div class="line">    &#125;</div><div class="line">    <span class="keyword">var</span> ast = &#123;</div><div class="line">        type: <span class="string">'Program'</span>,</div><div class="line">        body: []</div><div class="line">    &#125;;</div><div class="line">    <span class="keyword">while</span> (current &lt; tokens.length) &#123;</div><div class="line">        ast.body.push(walk());</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> ast;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到我們這裡還是會移動 current 來遍歷每個 token，</p>
<p>只是改成呼叫 <code>walk</code>函數，利用 JavaScript closure 的特性，</p>
<p>呼叫並且更改 current。</p>
<blockquote>
<p>如果對 closure 和 funcitonal programming with js有興趣，</p>
<p>可以參考一下這篇文章：</p>
<p><a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-pt-2-functional-programming-a63aa53a41a4#.ggszw4hmu" target="_blank" rel="external">The Two Pillars of JavaScript — Pt 2: Functional Programming</a></p>
</blockquote>
<p>來看看 <code>walk</code>：</p>
<p>首先當然是先拿到 token：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">walk</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> token = tokens[current];</div><div class="line">    <span class="comment">// get token</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>先看一下比較單純的遇到數字該怎麼辦（以下幾個 type 的確認都在 walk 裡完成）：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (token.type === <span class="string">'number'</span>) &#123;</div><div class="line">    current += <span class="number">1</span>;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        type: <span class="string">'NumberLiteral'</span>,</div><div class="line">        value: token.value</div><div class="line">    &#125;;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來是如果遇到 <code>(</code> 該做什麼事，</p>
<p>直接看一整段太長了，所以我將它拆成兩半：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (token.type === <span class="string">'parenthesis'</span>) &#123;</div><div class="line">    <span class="keyword">if</span> (token.value === <span class="string">'('</span>) &#123;</div><div class="line">        </div><div class="line">        current += <span class="number">1</span>;</div><div class="line">        token = tokens[current];</div><div class="line"></div><div class="line">        <span class="keyword">var</span> node = &#123;</div><div class="line">            type: <span class="string">'CallExpression'</span>,</div><div class="line">            name: token.value,</div><div class="line">            params: []</div><div class="line">        &#125;;</div><div class="line"></div><div class="line">        current += <span class="number">1</span>;</div><div class="line">        token = tokens[current];</div><div class="line">        <span class="comment">// To be continued with part 2</span></div><div class="line">        </div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>往後移一個，拿到下一個 token ，按照 lisp 的語法，</p>
<p>這裡會是一個 expression 的名字（可以想成 function name）。</p>
<p>建立一個 node object，params 裡面放的就是這個 expression 吃的參數。</p>
<p>再來繼續往下看下個 token，</p>
<p>這裡會比較困難一點點：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (token.type === <span class="string">'parenthesis'</span>) &#123;</div><div class="line">    <span class="keyword">if</span> (token.value === <span class="string">'('</span>) &#123;</div><div class="line">        <span class="comment">// ....</span></div><div class="line">        <span class="comment">// 接續前面 part 1</span></div><div class="line">        <span class="keyword">while</span> (</div><div class="line">            (token.type !== <span class="string">'parenthesis'</span>) ||</div><div class="line">            (token.type === <span class="string">'parenthesis'</span> &amp;&amp; token.value !== <span class="string">')'</span>)</div><div class="line">        ) &#123;</div><div class="line">            node.params.push(walk());</div><div class="line">            token = tokens[current];</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        current += <span class="number">1</span>;</div><div class="line"></div><div class="line"></div><div class="line">        <span class="keyword">return</span> node;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>假如不是 <code>)</code> 的話，就會繼續往下走，</p>
<p>因為expression 中可能還是會有 expression：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">(add (add 2 1) (subtract 1 2))</div></pre></td></tr></table></figure>
<p>所以假如遇到 <code>(</code>，就會在執行一次 walk，</p>
<p>前面已經知道 walk 的功用就是解析一個expression，</p>
<p>要解析一個 expression 中的 expression 的方法，</p>
<p>那就在 <code>walk</code> 裡面再 call 一次 <code>walk</code> 就好了，</p>
<p>我想可以人體 compile 一下上面的那行 lisp，</p>
<p>會更理解這個概念。</p>
<p>最後在 walk 函數的最後，一樣加上 type error 的 handling</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(token.type);</div></pre></td></tr></table></figure>
<p>實作完 <code>walk</code> 函數以後，要建出 AST 就簡單多了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">parser</span>(<span class="params">tokens</span>) </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">walk</span>(<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="comment">// plz ref to source code</span></div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="keyword">var</span> ast = &#123;</div><div class="line">        type: <span class="string">'Program'</span>,</div><div class="line">        body: []</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    <span class="keyword">while</span> (current &lt; tokens.length) &#123;</div><div class="line">        ast.body.push(walk());</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">return</span> ast;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>語法盡量寫的非常淺顯易懂，除了講解容易之外</p>
<p>在很難設中斷點的 js 裡，寫太聰明的 code 只是在搞自己而已。</p>
<p>這裡一樣附上完整的原碼: <a href="https://github.com/abalone0204/super-tiny-compiler-practice/blob/master/super-tiny-compiler.js#L58:L116" target="_blank" rel="external">parser</a></p>
<h1 id="2-Transformation"><a href="#2-Transformation" class="headerlink" title="2. Transformation"></a>2. Transformation</h1><p>這一階段的目標是要將 AST 轉成專為生成 JavaScript 而生的 <code>nextAST</code>，</p>
<p>我認為稍微抽象一點的應該就是 Traverser 的部份，</p>
<p>不過如果你有遍歷各種樹的概念，那以下應該會是非常簡單的事情。</p>
<p>這裡要分成兩個函數來實作：</p>
<ul>
<li><p>Traverser：去遍歷我們前面造出來的 AST，並執行我們想要執行在每個節點上的 function</p>
</li>
<li><p>Transformer：利用前面做出來的 Traverser 轉化成專為 JavaScript 而生的 <code>nextAst</code></p>
</li>
</ul>
<p>為了更清楚知道我們在做什麼，先看一下 transform 的結果：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * ----------------------------------------------------------------------------</div><div class="line"> *   Original AST                     |   Transformed AST</div><div class="line"> * ----------------------------------------------------------------------------</div><div class="line"> *   &#123;                                |   &#123;</div><div class="line"> *     type: 'Program',               |     type: 'Program',</div><div class="line"> *     body: [&#123;                       |     body: [&#123;</div><div class="line"> *       type: 'CallExpression',      |       type: 'ExpressionStatement',</div><div class="line"> *       name: 'add',                 |       expression: &#123;</div><div class="line"> *       params: [&#123;                   |         type: 'CallExpression',</div><div class="line"> *         type: 'NumberLiteral',     |         callee: &#123;</div><div class="line"> *         value: '22'                 |           type: 'Identifier',</div><div class="line"> *       &#125;, &#123;                         |           name: 'add'</div><div class="line"> *         type: 'CallExpression',    |         &#125;,</div><div class="line"> *         name: 'subtract',          |         arguments: [&#123;</div><div class="line"> *         params: [&#123;                 |           type: 'NumberLiteral',</div><div class="line"> *           type: 'NumberLiteral',   |           value: '22'</div><div class="line"> *           value: '43'               |         &#125;, &#123;</div><div class="line"> *         &#125;, &#123;                       |           type: 'CallExpression',</div><div class="line"> *           type: 'NumberLiteral',   |           callee: &#123;</div><div class="line"> *           value: '2'               |             type: 'Identifier',</div><div class="line"> *         &#125;]                         |             name: 'subtract'</div><div class="line"> *       &#125;]                           |           &#125;,</div><div class="line"> *     &#125;]                             |           arguments: [&#123;</div><div class="line"> *   &#125;                                |             type: 'NumberLiteral',</div><div class="line"> *                                    |             value: '43'</div><div class="line"> * ---------------------------------- |           &#125;, &#123;</div><div class="line"> *                                    |             type: 'NumberLiteral',</div><div class="line"> *                                    |             value: '2'</div><div class="line"> *                                    |           &#125;]</div><div class="line"> *  (sorry the other one is longer.)  |         &#125;]</div><div class="line"> *                                    |       &#125;</div><div class="line"> *                                    |     &#125;]</div><div class="line"> *                                    |   &#125;</div><div class="line"> * ----------------------------------------------------------------------------</div><div class="line"> */</div></pre></td></tr></table></figure>
<h2 id="2-a-Traverser"><a href="#2-a-Traverser" class="headerlink" title="2-a. Traverser"></a>2-a. Traverser</h2><p>為了要遍歷我們的 AST，</p>
<p>我們要先寫一個 helper function 來 traverse 每一個 token 的節點。</p>
<p>以下一樣把 traverser 分成兩部分來看，</p>
<p>現在先只要專注在最上方的 <code>traverseArray</code> 就行了：</p>
<p>traverseArray會做的事情就是對每個子節點執行 traverseNode。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">traverser</span>(<span class="params">ast, visitor</span>) </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseArray</span>(<span class="params">array, parent</span>) </span>&#123;</div><div class="line">        array.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">child</span>) </span>&#123;</div><div class="line">          traverseNode(child, parent);</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseNode</span>(<span class="params">node, parent</span>) </span>&#123;</div><div class="line">        <span class="comment">// to be continued</span></div><div class="line">    &#125;</div><div class="line">    traverseNode(ast, <span class="literal">null</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>traverser 裡面的 <code>visitor</code>，</p>
<p>面放著我們<strong>「拜訪」</strong>每個節點時要執行的方法，</p>
<p>Transform 的工作就是由 visitor 完成的，這裡先不要急，</p>
<p>到 <code>transform</code>這個函數時就會看到 visitor 是如何作用的。</p>
</blockquote>
<p>首先我們根據子節點的 type 呼叫對應執行的 method，</p>
<p>找到的話執行它，待會一再對子節點要執行的就是這一部份：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">traverser</span>(<span class="params">ast, visitor</span>) </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseArray</span>(<span class="params">array, parent</span>) </span>&#123;</div><div class="line">        array.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">child</span>) </span>&#123;</div><div class="line">          traverseNode(child, parent);</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseNode</span>(<span class="params">node, parent</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> method = visitor[node.type];</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (method) &#123;</div><div class="line">            method(node, parent);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// to be continued</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    traverseNode(ast, <span class="literal">null</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著再根據子節點的 type，去執行 <code>traverseArray</code>，</p>
<p>Program 的子節點是 <code>body</code>，</p>
<p>CallExpression 的事 <code>params</code>，</p>
<p>而單純的 NumberLiteral 則沒有子節點需要被遍歷。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">traverser</span>(<span class="params">ast, visitor</span>) </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseArray</span>(<span class="params">array, parent</span>) </span>&#123;</div><div class="line">        array.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">child</span>) </span>&#123;</div><div class="line">          traverseNode(child, parent);</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">traverseNode</span>(<span class="params">node, parent</span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> method = visitor[node.type];</div><div class="line"></div><div class="line">        <span class="keyword">if</span> (method) &#123;</div><div class="line">            method(node, parent);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">switch</span>(node.type) &#123;</div><div class="line">            <span class="keyword">case</span> <span class="string">'Program'</span>:</div><div class="line">                traverseArray(node.body, node);</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'CallExpression'</span>:</div><div class="line">                traverseArray(node.params, node);</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'NumberLiteral'</span>:</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">default</span>:</div><div class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(node.type);</div><div class="line">        &#125;        </div><div class="line">    &#125;</div><div class="line"></div><div class="line">    traverseNode(ast, <span class="literal">null</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li><a href="https://github.com/abalone0204/super-tiny-compiler-practice/blob/master/super-tiny-compiler.js#L118:L148" target="_blank" rel="external">traverser source code</a></li>
</ul>
<h2 id="2-b-Transformer"><a href="#2-b-Transformer" class="headerlink" title="2-b. Transformer"></a>2-b. Transformer</h2><p>再來則是重頭戲： <code>transformer</code>，</p>
<p><code>transformer</code>是個相當 powerful 的概念，</p>
<p><del>至少在麥考貝拍爛它之前都是</del>。</p>
<p>將我們一路 parse 過來的東西，轉成跟目標語言非常相近的 <strong>AST</strong>。</p>
<p>首先先造出一個新的 <code>nextAst</code>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">transformer</span>(<span class="params">ast</span>) </span>&#123;</div><div class="line">    <span class="comment">// init</span></div><div class="line">    <span class="keyword">var</span> nextAst = &#123;</div><div class="line">        type: <span class="string">'Program'</span>,</div><div class="line">        body: []</div><div class="line">    &#125;;</div><div class="line">    <span class="comment">// To be continued</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來這裡是有點 tricky 的部份，</p>
<p>我們對 ast 底下增加了一個隱藏的屬性：<code>_context</code>，</p>
<p>下面我們對子節點的操作也會常常用到這個非常 naive 的方法。</p>
<blockquote>
<p>其實只是在名字前面加上底線，並不是真正的隱藏</p>
</blockquote>
<p>再來則是前面有提的的 <code>visitor</code>，</p>
<p>這裡就能夠看出為什麼選擇 Lisp 了，</p>
<p>語法非常的簡單且直觀，</p>
<p>但 <code>transformer</code>仍然是一個相較之下較為複雜的函數：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">transformer</span>(<span class="params">ast</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> nextAst = &#123;</div><div class="line">        type: <span class="string">'Program'</span>,</div><div class="line">        body: []</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    ast._context = nextAst.body;</div><div class="line"></div><div class="line">    <span class="keyword">var</span> visitor = &#123;</div><div class="line">        NumberLiteral: <span class="function"><span class="keyword">function</span> (<span class="params">node, parent</span>) </span>&#123;</div><div class="line">            parent._context.push(&#123;</div><div class="line">                type: <span class="string">'NumberLiteral'</span>,</div><div class="line">                value: node.value</div><div class="line">            &#125;);</div><div class="line">        &#125;,</div><div class="line">        CallExpression: <span class="function"><span class="keyword">function</span> (<span class="params">node, parent</span>) </span>&#123;</div><div class="line">            <span class="comment">// to be continued</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    traverser(ast, visitor)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>NumberLiteral</code> 這個 method，做的事情並不難，</p>
<p>只是 push 一個節點到父節點的 <code>_context</code> 中而已。</p>
<p>假如今天我們的程式什麼都沒有，只有一個單純的數字：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">2</div></pre></td></tr></table></figure>
<p>那 transfomer 會造出來的<code>nextAst</code>就是這樣</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    type: <span class="string">'Program'</span></div><div class="line">    body: [&#123;type: <span class="string">'NumberLiteral'</span>, value: <span class="string">'2'</span>&#125;]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>跟前面的 ast 幾乎是沒有差的。</p>
<p>接著看如果遇到 function call 時要怎麼做，</p>
<p>為了簡潔我省略了其他部分的 code。</p>
<p>我們同樣先造出一個 expression 的 object，</p>
<p>包含一個 callee 屬性。</p>
<blockquote>
<p>callee 就是被呼叫的 function</p>
<p><code>(add 2 3)</code> 中，被呼叫的就是 <code>add</code> 這個 expression</p>
</blockquote>
<p>再來同樣在這個節點建立一個 <code>_context</code>，</p>
<p>並將其指到我們剛剛剛創造的 <code>expression</code>，</p>
<p>以下是 <code>CallExpression</code> 這個 method 的 上半部：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">transformer</span>(<span class="params">ast</span>) </span>&#123;</div><div class="line">    <span class="comment">// pass</span></div><div class="line">    <span class="keyword">var</span> visitor = &#123;</div><div class="line">        <span class="comment">// pass</span></div><div class="line">        CallExpression: <span class="function"><span class="keyword">function</span> (<span class="params">node, parent</span>) </span>&#123;</div><div class="line">            <span class="keyword">var</span> expression = &#123;</div><div class="line">                type: <span class="string">'CallExpression'</span>,</div><div class="line">                callee: &#123;</div><div class="line">                    type: <span class="string">'Itentifier'</span>,</div><div class="line">                    name: node.name</div><div class="line">                &#125;,</div><div class="line">                <span class="built_in">arguments</span>: []</div><div class="line">            &#125;;</div><div class="line"></div><div class="line">            node._context = expression.arguments;</div><div class="line">            <span class="comment">// pass</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    traverser(ast, visitor)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來則是跟 JavaScript 比較相關的部份，</p>
<p>因為 JavaScript 最上層的 Call Expression 其實是 statement，</p>
<p>所以在確定該個 expression 的父節點 type 不是 <code>CallExpression</code> 時，</p>
<p>要再多加一層 <code>ExpressionStatement</code>。</p>
<blockquote>
<p>Statement 就是敘述句，像是 <code>var i = 0</code>；</p>
<p>Expression 則是會產生值的，像是<code>yo()</code>。</p>
<p>但你知道的，有些 Statement 的地方我們仍然可以產生值，</p>
<p>因此也就有了 <code>Expression Statement</code> 的存在。</p>
<p>如此概括是有點草率，不過這裡還是將重點放在我們的 Compiler 上。</p>
<p>關於 Expression 和 Statement 在下方補充資料有放上一篇我覺得既短小又很不錯的文章！</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">transformer</span>(<span class="params">ast</span>) </span>&#123;</div><div class="line">    <span class="comment">// pass</span></div><div class="line">    <span class="keyword">var</span> visitor = &#123;</div><div class="line">        <span class="comment">// pass</span></div><div class="line">        CallExpression: <span class="function"><span class="keyword">function</span> (<span class="params">node, parent</span>) </span>&#123;</div><div class="line">            <span class="keyword">var</span> expression = &#123;</div><div class="line">                type: <span class="string">'CallExpression'</span>,</div><div class="line">                callee: &#123;</div><div class="line">                    type: <span class="string">'Itentifier'</span>,</div><div class="line">                    name: node.name</div><div class="line">                &#125;,</div><div class="line">                <span class="built_in">arguments</span>: []</div><div class="line">            &#125;;</div><div class="line"></div><div class="line">            node._context = expression.arguments;</div><div class="line">            <span class="keyword">if</span> (parent.type !== <span class="string">'CallExpression'</span>) &#123;</div><div class="line">                expression = &#123;</div><div class="line">                      type: <span class="string">'ExpressionStatement'</span>,</div><div class="line">                      expression: expression</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">            parent._context.push(expression);</div><div class="line"></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    traverser(ast, visitor)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>於是我們就完成了 <code>transformer</code> 了！</p>
<p>下一階段就是根據這個 <code>nextAst</code> 來生成 code 了。</p>
<p>一樣附上 <code>transformer</code> 的 <a href="https://github.com/abalone0204/super-tiny-compiler-practice/blob/master/super-tiny-compiler.js#L150:L192" target="_blank" rel="external">code</a></p>
<h1 id="3-Code-Generator"><a href="#3-Code-Generator" class="headerlink" title="3. Code Generator"></a>3. Code Generator</h1><p>終於到最後啦！</p>
<p>其實有了前一段專為 JavaScript 生成的 <code>nextAst</code>之後，</p>
<p>要生成 JavaScript 真的是毫不費力。</p>
<p>直接來看 <code>codeGenerator</code> 這個函數，</p>
<ul>
<li><p><code>Program</code>: 用換行來區分各個小 Program。</p>
</li>
<li><p><code>Expression</code>:再來是在每個 Expression 後面加上 <code>;</code>。</p>
</li>
<li><p><code>CallExpression</code>: </p>
<ul>
<li><code>callee</code> 就是被呼叫的函數，</li>
<li><code>arguments</code> 則會被逗號分開來，如果 argument 是 expression 的話會繼續遞迴的呼叫 <code>codeGenerator</code></li>
</ul>
</li>
<li><p><code>Identifier</code>: expression （函數）的的名稱。</p>
</li>
<li><p><code>NumberLiteral</code>: 毫無反應，就是個數字。</p>
</li>
<li><p>最後則是不包含以上 type 的 node，就會丟出 type error。<del>真的是非常 robust。</del></p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">codeGenerator</span>(<span class="params">node</span>) </span>&#123;</div><div class="line">    <span class="keyword">switch</span>(node.type) &#123;</div><div class="line">        <span class="keyword">case</span> <span class="string">'Program'</span>:</div><div class="line">            <span class="keyword">return</span> node.body.map(codeGenerator)</div><div class="line">                .join(<span class="string">'\n'</span>);</div><div class="line">        <span class="keyword">case</span> <span class="string">'ExpressionStatement'</span>:</div><div class="line">            <span class="keyword">return</span> (</div><div class="line">                codeGenerator(node.expression) + <span class="string">';'</span></div><div class="line">                )</div><div class="line">        <span class="keyword">case</span> <span class="string">'CallExpression'</span>:</div><div class="line">            <span class="keyword">return</span> (</div><div class="line">                codeGenerator(node.callee)+</div><div class="line">                <span class="string">'('</span>+</div><div class="line">                node.arguments.map(codeGenerator).join(<span class="string">', '</span>)+</div><div class="line">                <span class="string">')'</span> </div><div class="line">            );</div><div class="line">        <span class="keyword">case</span> <span class="string">'Identifier'</span>:</div><div class="line">            <span class="keyword">return</span> node.name;</div><div class="line">        <span class="keyword">case</span> <span class="string">'NumberLiteral'</span>:</div><div class="line">            <span class="keyword">return</span> node.value;</div><div class="line">        <span class="keyword">default</span>:</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(node.type);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li><a href="https://github.com/abalone0204/super-tiny-compiler-practice/blob/master/super-tiny-compiler.js#L194:L217" target="_blank" rel="external">source</a></li>
</ul>
<h1 id="Super-Tiny-Compiler"><a href="#Super-Tiny-Compiler" class="headerlink" title="Super Tiny Compiler"></a>Super Tiny Compiler</h1><p>將以上的 function 組合起來，</p>
<p>就是一個 compiler 了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">compiler</span>(<span class="params">input</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> tokens = lexer(input);</div><div class="line">    <span class="keyword">var</span> ast = parser(tokens);</div><div class="line">    <span class="keyword">var</span> nextAst = transformer(ast);</div><div class="line">    <span class="keyword">var</span> output = codeGenerator(nextAst);</div><div class="line">    <span class="keyword">return</span> output;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="後記"><a href="#後記" class="headerlink" title="後記"></a>後記</h1><p>很多時候我們都會覺得有好用的工具，</p>
<p>幹麻要自己造輪子呢？</p>
<p>但在造輪子的過程中，我們獲得的往往更多，</p>
<p>畢竟盲目的 call api 和使用 library 並不能體現一個軟體工作者的價值，</p>
<p>懂得何時該使用，甚至創造工具才是我們的天職所在。</p>
<p>能掌握更多知識，就能設計出更有創意的東西，</p>
<p>因為我們更了解所謂的「極限」在哪裡。</p>
<p>雖然只是一個「簡單的」from lisp to js compiler，</p>
<p>但相較於過度困難的屠龍本而言，</p>
<p>我想這是一個能相對友善了解 compiler 的起點。</p>
<h1 id="References"><a href="#References" class="headerlink" title="References"></a>References</h1><ul>
<li><p>可以到我的 repo 去看：<a href="https://github.com/abalone0204/super-tiny-compiler-practice" target="_blank" rel="external">Super tiny compiler practice</a>，也可以看下方原作的XD 有些微妙的不同</p>
</li>
<li><p><a href="https://github.com/thejameskyle/the-super-tiny-compiler" target="_blank" rel="external">Super tiny compiler</a></p>
</li>
<li><p><a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-pt-2-functional-programming-a63aa53a41a4#.ggszw4hmu" target="_blank" rel="external">The Two Pillars of JavaScript — Pt 2: Functional Programming</a></p>
</li>
<li><p><a href="http://www.2ality.com/2012/09/expressions-vs-statements.html" target="_blank" rel="external">Expressions versus statements in JavaScript</a></p>
</li>
</ul>
<h1 id="License"><a href="#License" class="headerlink" title="License"></a>License</h1><ul>
<li><a href="http://creativecommons.org/licenses/by/4.0/" target="_blank" rel="external">licensed through Creative Commons</a></li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;造一個超級小又可愛的 Compiler，&lt;/p&gt;
&lt;p&gt;沒有組語，只有 JavaScript。&lt;/p&gt;
    
    </summary>
    
    
      <category term="compiler" scheme="http://abalone0204.github.com/tags/compiler/"/>
    
      <category term="JavaScript" scheme="http://abalone0204.github.com/tags/JavaScript/"/>
    
  </entry>
  
  <entry>
    <title>搬家到 Hexo</title>
    <link href="http://abalone0204.github.com/2016/04/25/migrate-to-hexo/"/>
    <id>http://abalone0204.github.com/2016/04/25/migrate-to-hexo/</id>
    <published>2016-04-25T01:17:12.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>雖然是在同個 repository，而且也是用 github page 來 host，</p>
<p>但這次把 travis CI 加進來以後，改部落格變得方便多了！</p>
<p>這樣就沒有理由阻止自己偷懶不寫文章了吧 XD</p>
<a id="more"></a>
<ul>
<li><a href="https://hexo.io/" target="_blank" rel="external">hexo</a></li>
</ul>
<p>跟蠻多 static page generators 一樣，</p>
<p>可以跟 github page 做很好的搭配，</p>
<p>只是這一次，把 travis CI 也整進來了。</p>
<p>原因很簡單，個人的部落格，內容是<strong>公開的</strong>，</p>
<p>而 travis CI 對於 open source 的專案則是永久免費的。</p>
<p>實在沒有不用的理由 XD</p>
<p>不過部署的時候，會需要有寫入 repository 的權限，</p>
<p>我參考了以下這篇文章：</p>
<ul>
<li><a href="https://zespia.tw/blog/2015/01/21/continuous-deployment-to-github-with-travis/" target="_blank" rel="external">用 Travis CI 自動部署網站到 GitHub</a></li>
</ul>
<p>寫的很清楚 XD</p>
<p>我自己是另外 gen 了一個 public key 跟 private key，</p>
<p>所以會需要注意一下命名，</p>
<p>卡了半小時在那邊處理字打錯的白痴錯誤。</p>
<p>基本設定這樣就足以，接下來再來把 ga 和 留言功能加進來了。</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;雖然是在同個 repository，而且也是用 github page 來 host，&lt;/p&gt;
&lt;p&gt;但這次把 travis CI 加進來以後，改部落格變得方便多了！&lt;/p&gt;
&lt;p&gt;這樣就沒有理由阻止自己偷懶不寫文章了吧 XD&lt;/p&gt;
    
    </summary>
    
      <category term="DevOps" scheme="http://abalone0204.github.com/categories/DevOps/"/>
    
    
      <category term="hexo" scheme="http://abalone0204.github.com/tags/hexo/"/>
    
      <category term="CI" scheme="http://abalone0204.github.com/tags/CI/"/>
    
  </entry>
  
  <entry>
    <title>做中學 Cycle.js（下）</title>
    <link href="http://abalone0204.github.com/2016/02/01/circle-js-3/"/>
    <id>http://abalone0204.github.com/2016/02/01/circle-js-3/</id>
    <published>2016-02-01T00:00:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>Model-View-Intent &amp; Component</p>
<a id="more"></a>
<h1 id="Intro"><a href="#Intro" class="headerlink" title="Intro"></a>Intro</h1><p>我們會希望寫出來的 code 能夠做成被複用的 Component，</p>
<p>不過首先要來拆解一下越來越肥大的 main function。</p>
<p>而 main 就可以被拆成 Model、View 、Intent。</p>
<h1 id="Model-View-Intent"><a href="#Model-View-Intent" class="headerlink" title="Model View Intent"></a>Model View Intent</h1><p>先看一下上次 BMI example 的 main function</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> changeWeight$ = sources.DOM.select(<span class="string">'.weight'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">70</span>);</div><div class="line">    <span class="keyword">const</span> changeHeight$ = sources.DOM.select(<span class="string">'.height'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">170</span>);</div><div class="line">    <span class="keyword">const</span> state$ = Rx.Observable.combineLatest(</div><div class="line">        changeWeight$,</div><div class="line">        changeHeight$, (weight, height) =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> heightM = height/<span class="number">100</span>;</div><div class="line">            <span class="keyword">const</span> bmi = <span class="built_in">Math</span>.round(weight / (heightM * heightM));</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                bmi, weight, height</div><div class="line">            &#125;</div><div class="line">        &#125;)</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: state$.map(state =&gt;</div><div class="line">            div([</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Weight: <span class="subst">$&#123;state.weight&#125;</span>kg`</span>),</div><div class="line">                    input(<span class="string">'.weight'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">40</span>,</div><div class="line">                        max: <span class="number">150</span>,</div><div class="line">                        value: state.weight</div><div class="line">                    &#125;)</div><div class="line">                ]),</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Height: <span class="subst">$&#123;state.height&#125;</span>cm`</span>),</div><div class="line">                    input(<span class="string">'.height'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">140</span>,</div><div class="line">                        max: <span class="number">250</span>,</div><div class="line">                        value: state.height</div><div class="line">                    &#125;)</div><div class="line"></div><div class="line">                ]),</div><div class="line">                h1(<span class="string">`BMI is <span class="subst">$&#123;state.bmi&#125;</span>`</span>)</div><div class="line">            ])</div><div class="line">        )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這麼大一包看起來絕對不是好事。</p>
<p>所以我們會把 main 分成三塊，</p>
<p>分別是 Model, Intent, View</p>
<ul>
<li><p>Intent: to listen to the user</p>
</li>
<li><p>Model: to process information </p>
</li>
<li><p>View: to output back to the user</p>
</li>
</ul>
<h2 id="Intent"><a href="#Intent" class="headerlink" title="Intent"></a>Intent</h2><p>第一塊是「Intent」，</p>
<p>簡單說就是 User 想對 UI 做什麼事情的 Intent，</p>
<p>在這裡當然就是指雙方互動的部分：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// input event 就是這個簡單 app 中 User 跟 UI 互動的部分</span></div><div class="line"><span class="keyword">const</span> changeWeight$ = sources.DOM.select(<span class="string">'.weight'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">70</span>);</div><div class="line"><span class="keyword">const</span> changeHeight$ = sources.DOM.select(<span class="string">'.height'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">170</span>);</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">intent</span> (<span class="params">DOMSource</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> changeWeight$ = DOMSource.select(<span class="string">'.weight'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">70</span>);</div><div class="line">    <span class="keyword">const</span> changeHeight$ = DOMSource.select(<span class="string">'.height'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value).startWith(<span class="number">170</span>);</div><div class="line">    <span class="keyword">return</span> &#123;changeWeight$,changeHeight$&#125;;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Model"><a href="#Model" class="headerlink" title="Model"></a>Model</h2><p>model 則是處理資料流的部分：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">model</span>(<span class="params">changeWeight$, changeHeight$</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> state$ = Rx.Observable.combineLatest(</div><div class="line">        changeWeight$,</div><div class="line">        changeHeight$, (weight, height) =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> heightM = height/<span class="number">100</span>;</div><div class="line">            <span class="keyword">const</span> bmi = <span class="built_in">Math</span>.round(weight / (heightM * heightM));</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                bmi, weight, height</div><div class="line">            &#125;</div><div class="line">        &#125;)</div><div class="line">    <span class="keyword">return</span> state$;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="View"><a href="#View" class="headerlink" title="View"></a>View</h2><p>這裏則是依照 Model 中的資料去建 Virtual DOM tree</p>
<blockquote>
<p>我們不會把最後要 return 給 Driver 的東西也放在這</p>
<p>僅放跟 UI 生成相關的而已</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">view</span>(<span class="params">state$</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> vtree$ = state$.map(state =&gt;</div><div class="line">            div([</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Weight: <span class="subst">$&#123;state.weight&#125;</span>kg`</span>),</div><div class="line">                    input(<span class="string">'.weight'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">40</span>,</div><div class="line">                        max: <span class="number">150</span>,</div><div class="line">                        value: state.weight</div><div class="line">                    &#125;)</div><div class="line">                ]),</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Height: <span class="subst">$&#123;state.height&#125;</span>cm`</span>),</div><div class="line">                    input(<span class="string">'.height'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">140</span>,</div><div class="line">                        max: <span class="number">250</span>,</div><div class="line">                        value: state.height</div><div class="line">                    &#125;)</div><div class="line"></div><div class="line">                ]),</div><div class="line">                h1(<span class="string">`BMI is <span class="subst">$&#123;state.bmi&#125;</span>`</span>)</div><div class="line">            ])</div><div class="line">        )</div><div class="line">    <span class="keyword">return</span> vtree$;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="MVI"><a href="#MVI" class="headerlink" title="MVI"></a>MVI</h2><p>然後我們的 main 變得簡潔許多，</p>
<p>看起來只是 function 組合起來而已:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> &#123;changeWeight$,changeHeight$&#125; = intent(sources.DOM);</div><div class="line">    <span class="keyword">const</span> state$ = model(changeWeight$, changeHeight$);</div><div class="line">    <span class="keyword">const</span> vtree$ = view(state$);</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: vtree$</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Component"><a href="#Component" class="headerlink" title="Component"></a>Component</h2><p>那我們該如何減少重複的 Code 呢？</p>
<p>當 UI 的操作越變越複雜以後，</p>
<p>我們不會希望所有事情都能在一個 main 裡面解決，</p>
<p>這時候我們可以把重複的部分抽出來變成 component。</p>
<p>egghead 課程裡面有更精簡的怎麼把 main 提煉成 component 的過程，</p>
<p>不過核心精神蠻簡單的，就是 <strong>props 也是 stream。</strong></p>
<p>因為 props 是會跟著傳下來的「資料」，</p>
<p>所以很自然的我們就會選擇處理資料的 model 下手。</p>
<p>而 model 收到的 sources 是從 Drivers 來的，</p>
<p>第一步就是先更動 drivers</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">    DOM: makeDOMDriver(<span class="string">'#app'</span>),</div><div class="line">    props: () =&gt; Rx.Observable.of(&#123;</div><div class="line">        label: <span class="string">'Height'</span>,</div><div class="line">        unit: <span class="string">'cm'</span>,</div><div class="line">        min: <span class="number">100</span>,</div><div class="line">        max: <span class="number">220</span>,</div><div class="line">        init: <span class="number">170</span></div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>再來就是把 props 傳進去：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> state$ = model(upcomingValue$, sources.props);</div></pre></td></tr></table></figure>
<blockquote>
<p>記住： props 也是 Observable</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">model</span>(<span class="params">upcomingValue$, props$</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> initValue$ = props$.map(props =&gt; props.init).first();</div><div class="line">    <span class="keyword">const</span> value$ = initValue$.concat(upcomingValue$);</div><div class="line">    <span class="keyword">const</span> state$ = Rx.Observable.combineLatest(value$, props$, </div><div class="line">        (value, props) =&gt; &#123;</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                label: props.label,</div><div class="line">                unit: props.unit,</div><div class="line">                min: props.min,</div><div class="line">                max: props.max,</div><div class="line">                value: value</div><div class="line">            &#125;</div><div class="line">        &#125;)</div><div class="line">    <span class="keyword">return</span> state$</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>initial value 的 stream concat 新進來 value 的 stream，</p>
<p>取代原本的 <code>startWith</code></p>
<p>下一步就是把 label 的名字和單位給 return 出來，</p>
<p>變成一條 UI component 可以吃到的 state stream，</p>
<p>再把對應的值塞進 view 裡面，就能得到我們想要的 vtree$ 了。</p>
<h2 id="Using-component-with-Main-function"><a href="#Using-component-with-Main-function" class="headerlink" title="Using component with Main function"></a>Using component with Main function</h2><p>我們現在每個 component 中都會有個 main function，</p>
<p>事實上我們能把 main 改成這個 component 的名字，</p>
<p>並且在更上層的 main 中去使用它，</p>
<p>因為事實上他就是一個 function，在 functional programming 中，</p>
<p>“composable” 可以說是最重要的概念之一。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">LabelSlider</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> upcomingValue$ = intent(sources.DOM);</div><div class="line">    <span class="keyword">const</span> state$ = model(upcomingValue$, sources.props);</div><div class="line">    <span class="keyword">const</span> vtree$ = view(state$);</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: vtree$,</div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span> (<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> LabelSlider(sources)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>而事實上，我們可以把 props 這件事移到 main 中去做</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span> (<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> props$ = Rx.Observable.of(&#123;</div><div class="line">        label: <span class="string">'Height'</span>,</div><div class="line">        unit: <span class="string">'cm'</span>,</div><div class="line">        min: <span class="number">100</span>,</div><div class="line">        max: <span class="number">220</span>,</div><div class="line">        init: <span class="number">170</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">return</span> LabelSlider(&#123;DOM: sources.DOM, props: props$&#125;)</div><div class="line">&#125;</div><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">    DOM: makeDOMDriver(<span class="string">'#app'</span>),</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Multiple-Components"><a href="#Multiple-Components" class="headerlink" title="Multiple Components"></a>Multiple Components</h2><p>如果只有ㄧ個 component 的話，那 cycle.js 也太慘，</p>
<p>我們當然是可以組合多個 components，</p>
<p>只是該怎麼做呢？</p>
<p>很簡單，先把 sinks 個別抽出來：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span> (<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> weightProps$ = Rx.Observable.of(&#123;</div><div class="line">        label: <span class="string">'Weight'</span>,</div><div class="line">        unit: <span class="string">'kg'</span>,</div><div class="line">        min: <span class="number">30</span>,</div><div class="line">        max: <span class="number">220</span>,</div><div class="line">        init: <span class="number">70</span></div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> weightSinks$ = LabelSlider(&#123;DOM: sources.DOM, props: weightProps$&#125;)</div><div class="line">    </div><div class="line">    <span class="keyword">const</span> heightProps$ = Rx.Observable.of(&#123;</div><div class="line">        label: <span class="string">'Height'</span>,</div><div class="line">        unit: <span class="string">'cm'</span>,</div><div class="line">        min: <span class="number">100</span>,</div><div class="line">        max: <span class="number">220</span>,</div><div class="line">        init: <span class="number">170</span></div><div class="line">    &#125;);</div><div class="line">    <span class="keyword">const</span> heightSinks$ = LabelSlider(&#123;DOM: sources.DOM, props: heightProps$&#125;)</div><div class="line"></div><div class="line">    <span class="keyword">const</span> vtree$ = Rx.Observable.combineLatest(weightSinks$.DOM, heightSinks$.DOM, </div><div class="line">        (weightVtree, heightVtree) =&gt; </div><div class="line">        div([</div><div class="line">            weightVtree,</div><div class="line">            heightVtree</div><div class="line">            ]))</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: vtree$</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裏會發現一個問題，就是當我們移動其中一個 slider 時，</p>
<p>另一個也會被影響 ，使用者的互動 =&gt; intent</p>
<p>因為兩個的 class 都是 slider，</p>
<p>而 intent 中監聽的又是 “.slider” 底下的 input。</p>
<p>其實我們在 LabelSlider 裡就可以讓兩條 stream 分流，</p>
<p>因為我們傳進去的 <code>sources.DOM</code>，是可以只要選取 weight 或 height 就好：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> weightSinks$ = LabelSlider(&#123;</div><div class="line">        DOM: sources.DOM.select(<span class="string">'.weight'</span>),</div><div class="line">        props: weightProps$</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>這裏做的事情就等於在 intent 裡面這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">intent</span>(<span class="params">DOMSource</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> change$ = DOMSource.select(<span class="string">'.weight'</span>).select(<span class="string">'.slider'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value);</div><div class="line">    <span class="keyword">return</span> change$;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我們 <strong>pre-select</strong> 了在 DOM 上面 class name 為 ‘.weight’的 stream。</p>
<h1 id="Isolate-component"><a href="#Isolate-component" class="headerlink" title="Isolate component"></a>Isolate component</h1><ul>
<li><p><a href="https://github.com/cyclejs/isolate" target="_blank" rel="external">Isolate</a></p>
</li>
<li><p>要隔離開每個 Component 如果都像上面那樣做應該會瘋掉，<br>所以 Cyclejs 其實提供給我們一個 helper function： isolate</p>
</li>
<li><p>使用方法是傳入一個 Component function 當作 argument<br>再來會回傳一個 scoped 的 component function，<br>同樣吃 sources 進去，吐 sinks 出來</p>
</li>
<li><p><code>isolate(dataflowComponent, scope)</code>：第二個參數是 optional 的，如同看到的一樣</p>
</li>
</ul>
<blockquote>
<p>可能會有人覺得沒什麼差別，但如果單純使用 <code>isolate(dataflowComponent)</code>，</p>
<p>那會是一個不純的 function ，因為每次呼叫都會 return 一個不一樣的 scoped component function</p>
<p>但如果我們指定了 scope，那每次回來的就是同一個 scope 下的 component function</p>
<p>真正的濃醇香！</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> WeightSlider = isolate(LabelSlider, <span class="string">'weight'</span>);</div><div class="line"><span class="keyword">const</span> weightSinks$ = WeightSlider(&#123;</div><div class="line">    DOM: sources.DOM,</div><div class="line">    props: weightProps$</div><div class="line">&#125;);</div><div class="line"><span class="keyword">const</span> weightVtree$ = weightSinks$.DOM;</div></pre></td></tr></table></figure>
<p>如此一來又減少了一些 boiler plate</p>
<h2 id="Final-BMI"><a href="#Final-BMI" class="headerlink" title="Final BMI"></a>Final BMI</h2><p>目前缺的就是把 bmi 給算出來了，</p>
<p>首先我們知道這個運算會放在 main 裡面，</p>
<p>因為這就是這個簡單小 App 的主要<strong>邏輯</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> bmi$ = Rx.Observable.combineLatest(weightValue$, heightValue$, (weight, height) =&gt; &#123;</div><div class="line">    <span class="keyword">const</span> heightMeters = height * <span class="number">0.01</span>;</div><div class="line">    <span class="keyword">const</span> bmi = <span class="built_in">Math</span>.round(weight/(heightMeters*heightMeters))</div><div class="line">    <span class="keyword">return</span> bmi;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>現在問題來了：我們要怎樣得到 weightValue$ 以及 heightValue$ 呢？</p>
<p>從 sources 拿啊！</p>
<p>概念很簡單，我們從 main 中拿到的 source，</p>
<p>其實就是從前一層 component 中吐出來的 sinks，</p>
<p>所以我們自然從前一層 component 中回傳的 sinks 下手：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">LabelSlider</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> upcomingValue$ = intent(sources.DOM);</div><div class="line">    <span class="keyword">const</span> state$ = model(upcomingValue$, sources.props);</div><div class="line">    <span class="keyword">const</span> vtree$ = view(state$);</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: vtree$,</div><div class="line">        value: state$.map(state=&gt; state.value)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>實作起來也是這麼簡單。</p>
<p>最後我們回到 main 中，</p>
<p>把 bmi$ 也加進去就成啦！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> vtree$ = Rx.Observable.combineLatest(bmi$, weightVtree$, heightVtree$, (bmi, weightVtree, heightVtree) =&gt;</div><div class="line">        div([</div><div class="line">            weightVtree,</div><div class="line">            heightVtree,</div><div class="line">            h1(<span class="string">`BMI is: <span class="subst">$&#123;bmi&#125;</span>`</span>)</div><div class="line">        ]))</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: vtree$</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>總計 21 回的課程算不上太長，很推薦有興趣的人去把它看完，</p>
<p>儘管實際上要弄懂 Cycle.js 的概念的確需要花點時間，</p>
<p>但學習 FRP 是值得的，畢竟我們就是在處理 dataflow + UI，</p>
<p>再加上 pure function 好測試、composable 的特性，</p>
<p>不由得感慨 Rx 寫起來真是爽。</p>
<p>相較於 React，Cycle.js 當然更接近 functinoal programming，</p>
<p>不論這個東西將來會不會用到產品上，</p>
<p>純函數式的東西總會莫名的吸引我。</p>
<blockquote>
<p>如果要追求 fp，更應該要感受一下 <a href="http://elm-lang.org/" target="_blank" rel="external">elm</a></p>
</blockquote>
<p>這一堂課的影片幾乎都在 jsfiddle 上完成，</p>
<p>（不曉得作者為啥要這樣XD）</p>
<p>我中間練習的程式碼有放在 <a href="https://github.com/abalone0204/Learning-Cycle.js-By-Building-it" target="_blank" rel="external">github</a> 上面，</p>
<p>筆記等年假再來好好整理一番。</p>
<hr>
<h1 id="參考資料"><a href="#參考資料" class="headerlink" title="參考資料"></a>參考資料</h1><ul>
<li><p><a href="http://cycle.js.org/model-view-intent.html" target="_blank" rel="external">Official doc: Model View Intent</a></p>
</li>
<li><p><a href="http://www.codemag.com/Article/1601071" target="_blank" rel="external">How Functional Reactive Programming (FRP) is Changing the Face of Web Development</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Model-View-Intent &amp;amp; Component&lt;/p&gt;
    
    </summary>
    
    
      <category term="cycle.js" scheme="http://abalone0204.github.com/tags/cycle-js/"/>
    
      <category term="observable" scheme="http://abalone0204.github.com/tags/observable/"/>
    
  </entry>
  
  <entry>
    <title>做中學 Cycle.js（中）</title>
    <link href="http://abalone0204.github.com/2016/01/24/circle-js-2/"/>
    <id>http://abalone0204.github.com/2016/01/24/circle-js-2/</id>
    <published>2016-01-24T00:00:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>Drivers 和一些簡單的例子</p>
<a id="more"></a>
<p>還沒看過上一篇的可以先去看上一篇了解 Cycle.js，</p>
<p>這一篇會從 driver 開始講。</p>
<p>drivers 是在控制畫面的 render，</p>
<p>但是我們目前的 driver 都是只能回傳字串，</p>
<p>這一章節我們要真的來認真的操作 DOM，</p>
<p>並且實作幾個小例子來看看 Cycle.js 這個框架是怎樣改變我們思考資料流的方式。</p>
<h2 id="Making-DOM-driver-more-flexible"><a href="#Making-DOM-driver-more-flexible" class="headerlink" title="Making DOM driver more flexible"></a>Making DOM driver more flexible</h2><p>這裏要來認真處理一下如何去從 object 去表示一個 DOM，</p>
<p>假如你之前實作過一個 Virtual DOM 的話，</p>
<p>我想會相當有幫助。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">createElement</span>(<span class="params">obj</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> element = <span class="built_in">document</span>.createElement(obj.tagName);</div><div class="line">    obj.children</div><div class="line">            .filter(c =&gt; <span class="keyword">typeof</span> c === <span class="string">'object'</span>)</div><div class="line">            .map(createElement)</div><div class="line">            .forEach(c =&gt; element.appendChild(c));</div><div class="line">        obj.children</div><div class="line">            .filter(c =&gt; <span class="keyword">typeof</span> c === <span class="string">'string'</span>)</div><div class="line">            .forEach(c =&gt; element.innerHTML += c);</div><div class="line">    <span class="keyword">return</span> element;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>目前還只是沒加上 props 的簡化版。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">DOMDriver</span>(<span class="params">obj$</span>) </span>&#123;</div><div class="line">    obj$.subscribe(obj =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">        <span class="keyword">const</span> element = createElement(obj)</div><div class="line">        <span class="comment">// Refresh</span></div><div class="line">        container.innerHTML = <span class="string">''</span>;</div><div class="line">        container.appendChild(element);</div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> DOMSource = Observable.fromEvent(<span class="built_in">document</span>, <span class="string">"click"</span>);</div><div class="line">    <span class="keyword">return</span> DOMSource</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裏使用了 appendChild，所以如果不每次都清空的話，</p>
<p>等於每次都會 append 東西上來。</p>
<h2 id="在-DOM-source-掌控更多事情"><a href="#在-DOM-source-掌控更多事情" class="headerlink" title="在 DOM source 掌控更多事情"></a>在 DOM source 掌控更多事情</h2><p>回頭看一下我們的 Main，</p>
<p>發現我們唯一能從 DOM 拿到的 event stream，</p>
<p>居然只有 click$，這並不符合我們日常的開發情境，</p>
<p>現在就來解決這個問題。</p>
<p>解法很簡單，就是在 return DOMSource 的時候，</p>
<p>給個能夠選取 tag 和 event type 的 interface。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> DOMSource = &#123;</div><div class="line">    selectEvents: <span class="function"><span class="keyword">function</span>(<span class="params">tagName, eventType</span>) </span>&#123;</div><div class="line">        <span class="keyword">return</span> Observable.fromEvent(<span class="built_in">document</span>, eventType)</div><div class="line">            .filter(e =&gt; e.target.tagName === tagName.toUpperCase());</div><div class="line">    &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>這裏當然還是不夠 general 的版本，</p>
<p>不過這樣我們在 main function 裡面就能夠簡單的選取另一個 event 了。</p>
<h2 id="h"><a href="#h" class="headerlink" title="h()"></a>h()</h2><p>一開始我也很疑惑 h 是啥？</p>
<p>答案很簡單， “h” stands for html</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">function h(tagName, children) &#123;</div><div class="line">    return &#123;</div><div class="line">        tagName,</div><div class="line">        children</div><div class="line">    &#125;</div><div class="line">&#125; </div><div class="line"></div><div class="line">function h1(children) &#123;</div><div class="line">    return h(&apos;H1&apos;, children);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>讓我們在 main 中要建造 elements 時省去不少力氣。</p>
<p>而 h1、h2、span⋯⋯等等你想得到的 tag，</p>
<p>都能藉由 function 來表示，</p>
<p>並且語法看起來也很簡單，</p>
<p>連我到後來都不禁思考：「<strong>我們真的需要 jsx 嗎</strong>？」</p>
<p>目前只是比較簡單的語法，還沒考慮到 properties，</p>
<p>在 main 中的長相大概會像這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">Observable.timer(<span class="number">0</span>, <span class="number">1000</span>)</div><div class="line">          .map(i =&gt;</div><div class="line">                h1([</div><div class="line">                    span([</div><div class="line">                        <span class="string">`Seconds elapsed <span class="subst">$&#123;i&#125;</span>`</span></div><div class="line">                    ])</div><div class="line">                ]))</div></pre></td></tr></table></figure>
<h2 id="Way-to-Real-Driver"><a href="#Way-to-Real-Driver" class="headerlink" title="Way to Real Driver"></a>Way to Real Driver</h2><p>處理完語法後，我們來看看怎樣寫出一個更 serious 一點的 driver。</p>
<p>第一個發現的問題就是我們又把整個 Component 要 mount 的地方寫死了，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">DOMDriver(obj$) =&gt; &#123;</div><div class="line">        obj$.subscribe(obj =&gt; &#123;</div><div class="line">            <span class="comment">// hard code</span></div><div class="line">            <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">            <span class="keyword">const</span> element = createElement(obj)</div><div class="line">            container.innerHTML = <span class="string">''</span>;</div><div class="line">            container.appendChild(element);</div><div class="line">        &#125;)</div><div class="line">        <span class="keyword">const</span> DOMSource = &#123;</div><div class="line">            selectEvents: <span class="function"><span class="keyword">function</span>(<span class="params">tagName, eventType</span>) </span>&#123;</div><div class="line">                <span class="keyword">return</span> Observable.fromEvent(<span class="built_in">document</span>, eventType)</div><div class="line">                    .filter(e =&gt; e.target.tagName === tagName.toUpperCase());</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">        <span class="keyword">return</span> DOMSource</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>這樣的寫法讓我們必須要在 DOM 上一定要有 id 為 app 的 element，</p>
<p>才能夠啟用 DOMDriver。</p>
<p>DOMDriver 是一個 function，</p>
<p>所以我們只要能回傳一個「客製化」的 function，</p>
<p>這件事情不就解決了嗎？</p>
<p>這裏運用到了 JavaScript 中「閉包(Closure)」的概念，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">makeDOMDriver</span>(<span class="params">mountSelector</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> (obj$) =&gt; &#123;</div><div class="line">        obj$.subscribe(obj =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(mountSelector);</div><div class="line">            <span class="keyword">const</span> element = createElement(obj)</div><div class="line">            container.innerHTML = <span class="string">''</span>;</div><div class="line">            container.appendChild(element);</div><div class="line">        &#125;)</div><div class="line">        <span class="keyword">const</span> DOMSource = &#123;</div><div class="line">            selectEvents: <span class="function"><span class="keyword">function</span>(<span class="params">tagName, eventType</span>) </span>&#123;</div><div class="line">                <span class="keyword">return</span> Observable.fromEvent(<span class="built_in">document</span>, eventType)</div><div class="line">                    .filter(e =&gt; e.target.tagName === tagName.toUpperCase());</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">        <span class="keyword">return</span> DOMSource</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">    DOM: makeDOMDriver(<span class="string">'#app'</span>),</div><div class="line">    Log: consoleLogDriver,</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>下一個問題則是：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">container.innerHTML = <span class="string">''</span>;</div></pre></td></tr></table></figure>
<p>假如要 bind 到 DOM 上面是一個很大的 object，</p>
<p>那我們會遭遇到效能的問題。</p>
<p>再來則是 <code>selectEvents</code> 這個 function：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">selectEvents: <span class="function"><span class="keyword">function</span>(<span class="params">tagName, eventType</span>) </span>&#123;</div><div class="line">    ...</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>它只能指定 tagName，</p>
<p>不能用更方便的 selector 來選取想要的 element，</p>
<p>我們應該要提供一個更聰明一點的 API 來做這件事情。</p>
<p>關於這兩個問題點該怎麼重構，</p>
<p>作者並沒有詳細說明，但我們可以直接去看 source code，</p>
<p>這也是我們要將 CycleDOM import 進來的時候。</p>
<blockquote>
<p>小記一下，</p>
<p>假如我們繼續用舊有版本的 run，</p>
<p>那 <code>selectEvents</code> 會沒有被綁進去 source 裡面。</p>
<p>蠻好玩的，可以想一想要怎麼解這一個問題。</p>
</blockquote>
<p>接下來的正式引進 cycle-dom 中的 makeDOMDriver，</p>
<p>而原本的程式碼也要跟著做變動。</p>
<p>沒有意外的，首先需要更動的就是 selectEvents </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> mouseover$ = sources.DOM.select(<span class="string">'span'</span>).events(<span class="string">'mouseover'</span>);</div></pre></td></tr></table></figure>
<p>這底下有一個 virtual dom來 handle 重繪，</p>
<p>不會像我們先前一樣，每次一有更動，</p>
<p>就重新 flush 整個畫面。</p>
<p>而 h1, h 也變得更加強大，可以試試看在第一個參數傳入物件，</p>
<p>可以自訂 attributes，以及調整 style。</p>
<h2 id="Hello-Wolrd"><a href="#Hello-Wolrd" class="headerlink" title="Hello Wolrd"></a>Hello Wolrd</h2><p>啊！終於要開始 Hello world 了，</p>
<p>跟以往不一樣的是我們已經跑了一次的底下大概會發生什麼事情，</p>
<p>才跟世界說 hello。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="comment">// return a sinks</span></div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: Rx.Observable.of(</div><div class="line">            div([</div><div class="line">                label(<span class="string">'Name:'</span>),</div><div class="line">                input(<span class="string">'.field'</span>, &#123;</div><div class="line">                    type: <span class="string">"text"</span></div><div class="line">                &#125;),</div><div class="line">                hr(),</div><div class="line">                h1(<span class="string">'Hello !'</span>)</div><div class="line">            ]))</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>現在我們用剛剛學到的 select跟 events 來處理一下 input 的 events。</p>
<p>注意到我們在 input function 那裏的第一個參數寫下 <code>.filed</code>，</p>
<p>會自動變成帶有 field class 的 input 。</p>
<p>（準確一點來說應該是 return 一個 virtual dom 的 element）</p>
<p>長這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;tagName: <span class="string">"INPUT"</span>, properties: <span class="built_in">Object</span>, children: <span class="built_in">Array</span>[<span class="number">0</span>], key: <span class="literal">undefined</span>, namespace: <span class="literal">null</span>…&#125;</div></pre></td></tr></table></figure>
<p>再來則是把 input event 以及 值給拿出來：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> inputEv$ = sources.DOM.select(<span class="string">'.field'</span>).events(<span class="string">'input'</span>); </div><div class="line"><span class="keyword">const</span> name$ = inputEv$.map(ev =&gt; ev.target.value);</div></pre></td></tr></table></figure>
<p>再來要做的事情很直觀，</p>
<p>就是把 name$ 裏的值給 map 到 DOM 上面去……嗎？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">name$.map(name =&gt; </div><div class="line">        div([</div><div class="line">            label(<span class="string">'Name:'</span>),</div><div class="line">            input(<span class="string">'.field'</span>, &#123;</div><div class="line">                type: <span class="string">"text"</span></div><div class="line">            &#125;),</div><div class="line">            hr(),</div><div class="line">            h1(<span class="string">'Hello !'</span>)</div><div class="line">        ]))</div></pre></td></tr></table></figure>
<p>實際上這樣的作法會讓畫面上什麼都沒有，</p>
<p>因為 name$ 是 inputEv$ map 過後的結果，</p>
<p>而一開始 inputEv$ 是空的，自然沒有任何東西會 return 啦！</p>
<p>但要解決這個問題也很簡單，只需要<code>startWith</code>這個好用的 operator 即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> inputEv$ = sources.DOM.select(<span class="string">'.field'</span>).events(<span class="string">'input'</span>);</div><div class="line">    <span class="keyword">const</span> name$ = inputEv$</div><div class="line">        .map(ev =&gt; ev.target.value)</div><div class="line">        .startWith(<span class="string">'World'</span>);</div><div class="line">    <span class="comment">// return a sinks</span></div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: name$.map(name =&gt;</div><div class="line">            div([</div><div class="line">                label(<span class="string">'Name:'</span>),</div><div class="line">                input(<span class="string">'.field'</span>, &#123;</div><div class="line">                    type: <span class="string">"text"</span></div><div class="line">                &#125;),</div><div class="line">                hr(),</div><div class="line">                h1(<span class="string">`Hello <span class="subst">$&#123;name&#125;</span>!`</span>)</div><div class="line">            ]))</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>Hello world 完成啦！</p>
<h2 id="Counter"><a href="#Counter" class="headerlink" title="Counter"></a>Counter</h2><p>在開始之前得提醒一下，</p>
<p>跟 Redux 在開發之前得先想好 StateTree 的道理有點像，</p>
<p>在 Cycle 中，我們會體會到要怎樣設計一個 Stream 的流向，</p>
<p>而 UI 只要跟著這個 Flow 去變化就行了</p>
<p>（狀態顯示為 Reactive 狂粉）</p>
<blockquote>
<p>來個經典的 Counter example 。</p>
</blockquote>
<p>廢話不多說，</p>
<p>就先把頁面和 increment 以及 decrement 的 click stream 弄出來：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> decrementClick$ = sources.DOM.select(<span class="string">'#decrement'</span>).events(<span class="string">'click'</span>);</div><div class="line">    <span class="keyword">const</span> incrementClick$=sources.DOM.select(<span class="string">'#increment'</span>).events(<span class="string">'click'</span>);</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: Rx.Observable.of(</div><div class="line">            div([</div><div class="line">                button(<span class="string">'#decrement'</span>, <span class="string">'Decrement'</span>),</div><div class="line">                button(<span class="string">'#increment'</span>, <span class="string">'Increment'</span>),</div><div class="line">                p([</div><div class="line">                    label(<span class="string">'0'</span>)</div><div class="line">                    ])</div><div class="line">                ])</div><div class="line">            )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>拿到 Stream 之後呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> decrementAction$ = decrementClick$.map(ev =&gt; <span class="number">-1</span>);</div><div class="line">    <span class="keyword">const</span> incrementAction$ = incrementClick$.map(ev =&gt; <span class="number">1</span>);</div><div class="line">    <span class="keyword">const</span> number$ = Rx.Observable.of(<span class="number">0</span>)</div><div class="line">        .merge(decrementAction$)</div><div class="line">        .merge(incrementAction$);</div></pre></td></tr></table></figure>
<p>這裏並沒有得到我們想要的東西，</p>
<p>來看一下 merge stream 是怎樣運作的，</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">0---------------- number$</div><div class="line">--(-1)-(-1)------ decrementAction$</div><div class="line">-------------1---incrementAction$</div><div class="line">    [merge]</div><div class="line">0-(-1)-(-1)--1---[merged$]</div></pre></td></tr></table></figure>
<p>我們必須有個東西把 Stream 上所有的值給加總，</p>
<p>想到 array 的 reduce 了嗎？</p>
<p>其實 Rx 有提供一個 Operator 給我們做類似的操作：</p>
<p>它叫做 <code>scan</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">const</span> number$ = Rx.Observable.of(<span class="number">0</span>)</div><div class="line">        .merge(decrementAction$)</div><div class="line">        .merge(incrementAction$)</div><div class="line">        .scan((prev, cur) =&gt; prev+cur);</div></pre></td></tr></table></figure>
<p>Cycle 強迫我們在一開始就想好資料的流向，</p>
<p>以及事件的處理，如此我們在開發的時候能夠更深思熟慮一點，</p>
<p>不會讓整個 Project 變得很 crazy。</p>
<p>在簡單的 Counter 下這好處還不明顯，我目前也沒用 Cycle 寫過大型的產品，</p>
<p>所以且讓我們繼續看下去。</p>
<h2 id="Cycle-Http-Driver"><a href="#Cycle-Http-Driver" class="headerlink" title="Cycle Http Driver"></a>Cycle Http Driver</h2><p>開發 web，我們當然會需要送 http request，</p>
<p>所以我們就需要 http driver。</p>
<p>這裏我們要從 github 的 api 來拿 users 資料。</p>
<p>一樣先把基本的頁面弄出來</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: Rx.Observable.of(</div><div class="line">            div([</div><div class="line">                button(<span class="string">'.get_first'</span>, [<span class="string">'Get first user'</span>]),</div><div class="line">                div(<span class="string">'.user_details'</span>, [</div><div class="line">                    h1(<span class="string">'.user_name'</span>, <span class="string">'(name)'</span>),</div><div class="line">                    h4(<span class="string">'.email'</span>, <span class="string">'(email)'</span>),</div><div class="line">                    a(<span class="string">'.web'</span>, &#123;href: <span class="string">'google.com'</span>&#125;,<span class="string">'(url)'</span>)</div><div class="line">                    ])</div><div class="line">                ])</div><div class="line">            )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我們想讓使用者點下 get_first 的按鈕後，</p>
<p>就拿到 user 的資料。</p>
<p>前面有提到什麼是 read effect 跟 write effect，</p>
<p>effect 會因應 logics 規則的變化，真正影響到外在世界。</p>
<p>實際講起來太抽象了，我們現在把這個 App 中會發生的 effect 以及分類列出來，</p>
<p>會清楚很多：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">DOM Read effect : button clicked</div><div class="line">HTTP Write effect: send request</div><div class="line">HTTP Read effect: receive response</div><div class="line">DOM Write effect: user&apos;s data displayed</div></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line">    <span class="comment">// DOM Read effect : button clicked</span></div><div class="line">    <span class="keyword">const</span> clickEv$ = sources.DOM</div><div class="line">        .select(<span class="string">'.get_user'</span>).events(<span class="string">'click'</span>);</div><div class="line">    <span class="comment">// HTTP Write effect: send request</span></div><div class="line">    <span class="keyword">const</span> request$ = clickEv$.map(_ =&gt; &#123;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> &#123;</div><div class="line">            url: API_URL,</div><div class="line">            method: <span class="string">'GET'</span>,</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">    <span class="comment">// HTTP Read effect: receive response</span></div><div class="line">    <span class="keyword">const</span> response$$ = sources.HTTP</div><div class="line">        .filter(response$ =&gt; response$.request.url === API_URL)</div><div class="line">    <span class="keyword">const</span> response$ = response$$.<span class="keyword">switch</span>();</div><div class="line">    <span class="keyword">const</span> firstUser$ = response$.map(res =&gt; res.body)</div><div class="line">    .startWith(&#123;&#125;);</div><div class="line"></div><div class="line">    <span class="comment">// DOM Write effect: user's data displayed</span></div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: firstUser$.map(user =&gt;</div><div class="line">            div([</div><div class="line">                button(<span class="string">'.get_user'</span>, [<span class="string">'Get user'</span>]),</div><div class="line">                div(<span class="string">'.user_details'</span>, [</div><div class="line">                    h1(<span class="string">'.user_name'</span>, user.name),</div><div class="line">                    h4(<span class="string">'.email'</span>, user.email),</div><div class="line">                    a(<span class="string">'.web'</span>, &#123;</div><div class="line">                        href: user.url</div><div class="line">                    &#125;, user.url)</div><div class="line">                ])</div><div class="line">            ])</div><div class="line">        ),</div><div class="line">        HTTP: request$</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="BMI"><a href="#BMI" class="headerlink" title="BMI"></a>BMI</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">sources</span>) </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">const</span> changeWeight$ = sources.select(<span class="string">'.weight'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value);</div><div class="line">    <span class="keyword">const</span> changeHeight$ = sources.select(<span class="string">'.height'</span>).events(<span class="string">'input'</span>)</div><div class="line">        .map(ev =&gt; ev.target.value);</div><div class="line">    <span class="comment">// Need to combine two $,</span></div><div class="line">    <span class="comment">// Like we use `zip` to arrays.</span></div><div class="line">    <span class="keyword">const</span> state$ = Rx.Observable.combineLatest(</div><div class="line">        changeWeight$,</div><div class="line">        changeHeight$, (weight, height) =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> heightM = height/<span class="number">100</span>;</div><div class="line">            <span class="keyword">const</span> bmi = <span class="built_in">Math</span>.round(weight / (heightM * heightM));</div><div class="line">            <span class="keyword">return</span> &#123;</div><div class="line">                bmi, weight, height</div><div class="line">            &#125;</div><div class="line">        &#125;)</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: state$.map(state =&gt;</div><div class="line">            div([</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Weight: <span class="subst">$&#123;state.weight&#125;</span>kg`</span>),</div><div class="line">                    input(<span class="string">'.weight'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">40</span>,</div><div class="line">                        max: <span class="number">150</span>,</div><div class="line">                        value: state.weight</div><div class="line">                    &#125;)</div><div class="line">                ]),</div><div class="line">                div([</div><div class="line">                    label(<span class="string">`Height: <span class="subst">$&#123;state.height&#125;</span>cm`</span>),</div><div class="line">                    input(<span class="string">'.height'</span>, &#123;</div><div class="line">                        type: <span class="string">'range'</span>,</div><div class="line">                        min: <span class="number">140</span>,</div><div class="line">                        max: <span class="number">250</span>,</div><div class="line">                        value: state.height</div><div class="line">                    &#125;)</div><div class="line"></div><div class="line">                ]),</div><div class="line">                h1(<span class="string">`BMI is <span class="subst">$&#123;state.bmi&#125;</span>`</span>)</div><div class="line">            ])</div><div class="line">        )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在處理 Stream 時，往 Collection 的方向想會舒服很多，</p>
<p>因為我們處理 Array 也是如此，</p>
<p>最後一篇我們將會來看看 Cycle.js 怎樣提高我們程式碼的複用性，</p>
<p>學習用另一種方式去思考該怎樣拆解每個 Component。</p>
<hr>
<h1 id="參考資料"><a href="#參考資料" class="headerlink" title="參考資料"></a>參考資料</h1><ul>
<li><p><a href="http://openhome.cc/Gossip/JavaScript/Closure.html" target="_blank" rel="external">閉包</a></p>
</li>
<li><p><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36#.arfskyb6g" target="_blank" rel="external">Master the JavaScript Interview: What is a Closure?</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Drivers 和一些簡單的例子&lt;/p&gt;
    
    </summary>
    
    
      <category term="cycle.js" scheme="http://abalone0204.github.com/tags/cycle-js/"/>
    
      <category term="observable" scheme="http://abalone0204.github.com/tags/observable/"/>
    
  </entry>
  
  <entry>
    <title>做中學 Cycle.js（上）</title>
    <link href="http://abalone0204.github.com/2016/01/23/cycle-js-1/"/>
    <id>http://abalone0204.github.com/2016/01/23/cycle-js-1/</id>
    <published>2016-01-23T00:00:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>之前 Redux 和 Cycle.js 作者在爭辯何者才是較好的 paradigm，</p>
<p>其實軟體開發裡面沒有銀彈，</p>
<p>不過這種爭辯也更能夠激發出我們寫出更棒的軟體，</p>
<p>並且去反思現行流行的東西真的是「好」的嗎？</p>
<a id="more"></a>
<p>Cycle.js 的作者也寫下一篇他認為為什麼 Redux + React 不那麼好的原因：</p>
<ul>
<li><a href="http://staltz.com/why-react-redux-is-an-inferior-paradigm.html" target="_blank" rel="external">WHY REACT/REDUX IS AN INFERIOR PARADIGM</a></li>
</ul>
<p>同時間在 egghead.io 上也 release 了一個 Cycle.js 的課程：</p>
<ul>
<li><a href="https://egghead.io/lessons/rxjs-the-cycle-js-principle-separating-logic-from-effects" target="_blank" rel="external">Lessons of Cycle.js</a></li>
</ul>
<p>(等等，這時機推出課程，真的不是在打廣告嗎？)</p>
<p>我認為這個課程還蠻推薦的原因有底下兩點：</p>
<ul>
<li><p><strong>作者會告訴我們 Cycle.js 這樣設計的理念</strong><br>對我來說在學習一個框架時，<br>如果你不能理解為什麼要這樣設計，<br>那你就是用硬背的，這樣很容易忘記；<br>但如果你知道為什麼要命名成這樣、為什麼要這樣設計，<br>你等於進入了框架本身去使用它，<br>而不是被它框住。</p>
</li>
<li><p><strong>Observable 給我們不一樣的方式來思考如何 Handle events</strong><br>可以看看 Netflix 的<a href="https://www.youtube.com/watch?v=XRYN2xt11Ek&amp;hd=1" target="_blank" rel="external">例子</a></p>
</li>
</ul>
<p>週末在家拉肚子之餘，順便把課程課完並做了一些筆記。</p>
<p>先來看一下 Cycle.js 的 Get started code，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> Cycle <span class="keyword">from</span> <span class="string">'@cycle/core'</span>;</div><div class="line"><span class="keyword">import</span> CycleDOM <span class="keyword">from</span> <span class="string">'@cycle/dom'</span>;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params"></span>) </span>&#123;</div><div class="line">  <span class="comment">// ...</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">  DOM: CycleDOM.makeDOMDriver(<span class="string">'#app'</span>)</div><div class="line">&#125;;</div><div class="line"></div><div class="line">Cycle.run(main, drivers);</div></pre></td></tr></table></figure>
<p>現在看起來很不習慣，但這篇會從無到有的建一個簡單版的 Cycle.js 出來，</p>
<p>第一篇預計會實作很 primitve 的 drivers 以及 main，</p>
<p>接著會把 run 給重構到幾乎跟現在 Cycle 核心中的寫法一樣。</p>
<p>（當然還是只重概念說明的簡化版）</p>
<p>不過這都只是個人的學習筆記，</p>
<p>還是在大大推一下 egghead.io 上的課程</p>
<ul>
<li><a href="https://egghead.io/lessons/rxjs-the-cycle-js-principle-separating-logic-from-effects" target="_blank" rel="external">Lessons of Cycle.js</a></li>
</ul>
<h2 id="Prerequisite"><a href="#Prerequisite" class="headerlink" title="Prerequisite"></a>Prerequisite</h2><ul>
<li><p>了解如何操作 collection<br>沒錯，Observable 和 array（或list）都是 collection</p>
</li>
<li><p>可以試試這個互動的課程，再來看這系列會更有感覺：<br><a href="http://reactivex.io/learnrx/" target="_blank" rel="external">http://reactivex.io/learnrx/</a></p>
</li>
<li><p>對於 Rx 已經有基礎的認識</p>
</li>
</ul>
<h2 id="Cycle-js"><a href="#Cycle-js" class="headerlink" title="Cycle.js"></a>Cycle.js</h2><h3 id="Basic-Principle"><a href="#Basic-Principle" class="headerlink" title="Basic Principle"></a>Basic Principle</h3><ul>
<li>第一條規則就是要將「logics」跟「effect」分開</li>
</ul>
<p>要來分清楚這兩個東西是什麼就要先來看一下程式碼了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Logic</span></div><div class="line">Observable.timer(<span class="number">0</span>, <span class="number">1000</span>)</div><div class="line">    .map(i =&gt; <span class="string">`Seconds elapsed <span class="subst">$&#123;i&#125;</span>`</span>)</div><div class="line"><span class="comment">// Effect </span></div><div class="line">    .subscribe(text =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">        container.textContent = text;</div><div class="line">    &#125;)</div></pre></td></tr></table></figure>
<p>這是一個從 0 開始每一秒一數的計數器，</p>
<p>詳情請見 <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timer.md" target="_blank" rel="external">Timer</a>。</p>
<p>上半部的部分是「Logic」，</p>
<p>而 subscribe 那一行開始，就是他怎樣呈現的 「Effect」。</p>
<p>這裏有個很巧妙的概念，</p>
<p>就是 Effect 才是真正影響到外面世界的地方（DOM），</p>
<p>正如他的名字一樣；</p>
<p>而 Logic 裏的東西只是單純的 Event stream，</p>
<p>我們不去 Subscribe 他們，就不會有任何事情發生。</p>
<p>Cycle.js 的原則就是將這兩大部分分開，</p>
<p><code>Effect</code> 的部分是 Imperative 的，讓 Framework 幫你完成，</p>
<p>身為開發者我們只要關心 <code>Logic</code> 的部分就夠了，</p>
<p>而 Logic 的部分是 functional 的。</p>
<h3 id="Main-以及-Effect"><a href="#Main-以及-Effect" class="headerlink" title="Main 以及 Effect"></a>Main 以及 Effect</h3><p>前面提到我們會將 logic 和 effect 分開，</p>
<p>在 Cycle 中我們習慣會將 Logic 放到 main 裡面。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: Observable.timer(<span class="number">0</span>, <span class="number">1000</span>)</div><div class="line">                       .map(i =&gt; <span class="string">`Seconds elapsed <span class="subst">$&#123;i&#125;</span>`</span>),</div><div class="line">        Log: Observable.timer(<span class="number">0</span>, <span class="number">2000</span>)</div><div class="line">                       .map(i =&gt; <span class="number">2</span>*i)</div><div class="line">        &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">DOMEffect</span>(<span class="params">text$</span>) </span>&#123;</div><div class="line">    text$.subscribe(text =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">        container.textContent = text;</div><div class="line">    &#125;)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">consoleLogEffect</span> (<span class="params">msg$</span>) </span>&#123;</div><div class="line">    msg$.subscribe(msg =&gt; <span class="built_in">console</span>.log(msg));</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> sink = main();</div><div class="line">DOMEffect(sink.DOM);</div><div class="line">consoleLogEffect(sink.Log);</div></pre></td></tr></table></figure>
<p>我們在 Main 裡面建了兩條不同的 stream，</p>
<p>看起來已經將邏輯集中起來放，</p>
<p>但是最下方從 sink 開始，</p>
<p>似乎還是太 imperative 地去做這些事情。</p>
<blockquote>
<p>我們 Hard Coding 的去指定 consoleLogEffect 這個函數，</p>
<p>一旦我們今天把 main 中的 log 拔掉，</p>
<p>那整個程式就會報錯了，</p>
<p>Cycle.js 中不希望我們每次更動 Logic 時需要注意一大堆 effect</p>
</blockquote>
<p>再來就要介紹一下 <code>run</code> 這個 function。</p>
<h3 id="run"><a href="#run" class="headerlink" title="run"></a><code>run</code></h3><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">mainFn, effects</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> sinks = mainFn();</div><div class="line">    <span class="built_in">Object</span>.keys(effects)</div><div class="line">    .forEach(key =&gt; &#123;</div><div class="line">        effects[key](sinks[key])</div><div class="line">    &#125;)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> effectsFunctions = &#123;</div><div class="line">    DOM: DOMEffect,</div><div class="line">    Log: consoleLogEffect,</div><div class="line">&#125;</div><div class="line"></div><div class="line">run(main, effectsFunctions);</div></pre></td></tr></table></figure>
<p><code>run</code> 會吃兩個參數，第一個就是我們管邏輯的 main，</p>
<p>第二個則是 effect，</p>
<p>我們如果不想要他在畫面上做事情，</p>
<p>把在 effectFunctions 中的那個 key 給註解掉就行了，</p>
<p>因為我們並沒有很 hard coding 的去呼叫每個 effectFunction。</p>
<p>但是這裡要重新命名一下，將 effectFunctions 改成 drivers，</p>
<p>一來是因為 effectFunctions 聽起來並不是個好命名方式XD</p>
<p>二來是 drivers 即是我們熟悉的驅動程式，建立了硬體和軟體中間溝通的介面；</p>
<p>而這裡的 driver 可以想成我們的程式(logic)，和畫面(effect)中間溝通的介面；</p>
<p>還是很抽象嗎？</p>
<p>那就從字面上的意思來看， driver 就是駕駛員，</p>
<p>現在有一個駕駛員負責開著一台小車車，</p>
<p>嘟嘟嘟的把我們寫的邏輯運送到畫面上，</p>
<p>我們只要寫好邏輯、還有要送去的地方跟方式，</p>
<p>剩下的就交給 driver 幫我們處理啦！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">mainFn, drivers</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> sinks = mainFn();</div><div class="line">    <span class="built_in">Object</span>.keys(drivers)</div><div class="line">    .forEach(key =&gt; &#123;</div><div class="line">        drivers[key](sinks[key])</div><div class="line">    &#125;)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">    DOM: DOMDriver,</div><div class="line">    Log: consoleLogDriver,</div><div class="line">&#125;</div><div class="line"></div><div class="line">run(main, drivers);</div></pre></td></tr></table></figure>
<p>這是我們手刻出來的簡單版本，</p>
<p>而 Cycle.js 首頁的 get started 例子中，</p>
<p>輪廓的確就是這樣子，</p>
<p>只是在 driver 的部分，</p>
<p>Cycle.js 幫我們做了更多事情。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params"></span>) </span>&#123;</div><div class="line">  <span class="keyword">return</span> &#123;</div><div class="line">    DOM: Rx.Observable.interval(<span class="number">1000</span>)</div><div class="line">      .map(i =&gt; CycleDOM.h1(<span class="string">''</span> + i + <span class="string">' seconds elapsed'</span>))</div><div class="line">  &#125;;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">const</span> drivers = &#123;</div><div class="line">  DOM: CycleDOM.makeDOMDriver(<span class="string">'#app'</span>)</div><div class="line">&#125;;</div><div class="line"></div><div class="line">Cycle.run(main, drivers);</div></pre></td></tr></table></figure>
<h3 id="Read-effects-from-the-External-world"><a href="#Read-effects-from-the-External-world" class="headerlink" title="Read effects from the External world"></a>Read effects from the External world</h3><p>前面有提過 Netflix 解決複雜電影選單的方式，</p>
<p>就是透過 Observable 來重新思考處理 Events 的方式，</p>
<p>但到目前為止，我們都還沒有用到最精髓的部分，</p>
<p>而是把內部 Logic 寫好，沒有接收任何外來的 event stream。</p>
<p>奠基於 Rx 上面的 Cycle.js 最精華的也正是這一段處理 event 的方式，</p>
<p>同時這也是 <strong>Cycle</strong> 這名字的由來。</p>
<p>首先先看前面寫的程式碼：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">DOMDriver</span>(<span class="params">text$</span>) </span>&#123;</div><div class="line">    text$.subscribe(text =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">        container.textContent = text;</div><div class="line">    &#125;)</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: Observable.timer(<span class="number">0</span>, <span class="number">1000</span>)</div><div class="line">            .map(i =&gt; <span class="string">`Seconds elapsed <span class="subst">$&#123;i&#125;</span>`</span>),</div><div class="line">        Log: Observable.timer(<span class="number">0</span>, <span class="number">2000</span>)</div><div class="line">            .map(i =&gt; <span class="number">2</span> * i)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到它只有 input，沒有 output。</p>
<p>而 main function 則反之，</p>
<p>我們想從外部 read something ，就代表我們的 main 必須要有 input。</p>
<blockquote>
<p>這裏的前提是你照著 cycle.js 的單向資料流架構走</p>
</blockquote>
<p>所以我們先在 main 和 driver 各加上 input 和 output。</p>
<p>接下來在 <code>run</code> 中會改回 hard code 的方式，</p>
<p>這是為了更容易去理解，接著就會遇到最奇妙的地方：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">DOMDriver</span>(<span class="params">text$</span>) </span>&#123;</div><div class="line">    text$.subscribe(text =&gt; &#123;</div><div class="line">        <span class="keyword">const</span> container = <span class="built_in">document</span>.querySelector(<span class="string">'#app'</span>);</div><div class="line">        container.textContent = text;</div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> DOMSource = Observable.fromEvent(<span class="built_in">document</span>, <span class="string">"click"</span>);</div><div class="line">    <span class="keyword">return</span> DOMSource</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">mainFn, drivers</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> sinks = mainFn(DOMSource);</div><div class="line">    <span class="keyword">const</span> DOMSource = drivers.DOM(sinks.DOM);</div><div class="line"> </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我們看到 run 中間，DOMSource 需要 sinks 才能建立，</p>
<p>但 sinks 也需要 DOMSource 才能被建立，</p>
<p>形成一個很微妙的循環，是一個雞生蛋蛋生雞的問題。</p>
<p>在更抽象化一點就是：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">a = f(b)</div><div class="line">b = g(a)</div></pre></td></tr></table></figure>
<p>想要解決這件事其實沒那麼難，</p>
<p>想法上是這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">bProxy = ...</div><div class="line">a = f(bproxy)</div><div class="line">b = g(a)</div><div class="line">bProxy.imitate(b)</div></pre></td></tr></table></figure>
<p>這裏要靠 rx 裡面的 subject 來建立我們的 proxy。</p>
<blockquote>
<p>瞭解更多關於 Subject: </p>
<p>from <a href="http://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/subjects.html" target="_blank" rel="external">rx-book</a></p>
<p>簡言之它同時繼承了 Observable 跟 Observer，</p>
<p>所以我們既可以 subscribe 它，（Observable）</p>
<p>又能夠對他呼叫 onNext、onError，以及 onCompleted（這就是 Observer 在做的事情）</p>
</blockquote>
<p>這裏就比較困難要分段看了，</p>
<p>先到 run 裡面看看我們要怎麼按照上方的 pattern 來加入 proxy。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">mainFn, drivers</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> proxyDOMSource = <span class="keyword">new</span> Subject();</div><div class="line">    <span class="keyword">const</span> sinks = mainFn(proxyDOMSource);</div><div class="line">    <span class="keyword">const</span> DOMSource = drivers.DOM(sinks.DOM);</div><div class="line">    DOMSource.subscribe(click =&gt; proxyDOMSource.onNext(click))</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>DOMDriver 回傳了一個 click-event 的 stream（Observable），</p>
<p>所以我們 subscribe 它，並且每一次呼叫 click 的 stream，</p>
<p>跟我們前面創造的 proxy 整合在一起，</p>
<p>下來再來看 proxy 傳進 main 發生了什麼事情。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">main</span>(<span class="params">DOMSource</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> click$ = DOMSource;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        DOM: click$</div><div class="line">        .startWith(<span class="literal">null</span>)</div><div class="line">        .flatMapLatest(() =&gt;</div><div class="line">            Observable.timer(<span class="number">0</span>, <span class="number">1000</span>)</div><div class="line">            .map(i =&gt; <span class="string">`Seconds elapsed <span class="subst">$&#123;i&#125;</span>`</span>)</div><div class="line">        ), </div><div class="line">        Log: Observable.timer(<span class="number">0</span>, <span class="number">2000</span>)</div><div class="line">            .map(i =&gt; <span class="number">2</span> * i)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>簡單說就是我們每次在螢幕上按一下(click)，</p>
<p>就會重啟整個 timer。</p>
<blockquote>
<p>歸功於 flapMapLatest 這個 operator，</p>
<p>假如這裡改用 flapMap 的話，會發現舊的 stream 還在繼續跑，</p>
<p>整個 timer 會被搗亂，假如還不熟 flatMap 該怎麼用</p>
<p>請至 prerequisite 玩一下 <a href="http://reactivex.io/learnrx/" target="_blank" rel="external">learn-rx</a></p>
</blockquote>
<p>而 <code>startWith(null)</code> 則是製造一次「假的」 event，</p>
<p>來觸發第一次還沒 click 之前的 effect。</p>
<p>現在的 code 看起來很糟糕，尤其是在 main 中 hard code DOMSource 這一點。</p>
<p>首先先從 run 中下手：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">mainFn, drivers</span>) </span>&#123;</div><div class="line">    <span class="keyword">const</span> proxySources = &#123;&#125;;</div><div class="line">    <span class="built_in">Object</span>.keys(drivers).forEach(key =&gt;&#123;</div><div class="line">        proxySources[key] = <span class="keyword">new</span> Subject();</div><div class="line">    &#125;)</div><div class="line">    <span class="keyword">const</span> sinks = mainFn(proxySources);</div><div class="line">    <span class="built_in">Object</span>.keys(drivers)</div><div class="line">          .forEach(key =&gt; &#123;</div><div class="line">            <span class="keyword">const</span> source = drivers[key](sinks[key])</div><div class="line">            source.subscribe(x =&gt; proxySources[key].onNext(x))</div><div class="line">          &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如此一來我們就不用去 hard code 的指定每個 proxySource，</p>
<p>而在 main 中簡單多了，只要把 click$ 的來源變成 sources.DOM 就好了，</p>
<p>但在這裡我們可能會對一個 undefined 呼叫 subscribe。</p>
<blockquote>
<p>consoleLogDriver 並沒有 return 任何東西（nothing to be read）</p>
</blockquote>
<p>要避免這點只要加個判斷式就能夠解決，</p>
<p>不過截至目前為止，我們其實已經把 Cycle core 中的 run 給實作的差不多了！</p>
<ul>
<li><a href="https://github.com/cyclejs/cycle-core/blob/master/src/cycle.js#L97:L118" target="_blank" rel="external">source code of run in Cycle.js</a></li>
</ul>
<blockquote>
<p>當然還是有些差異在，像是 error-handling，</p>
<p>以及在 Cycle core 的 proxy 中是用 <code>ReplaySubject</code> 而不是 <code>Subject</code></p>
</blockquote>
<hr>
<h1 id="參考資料"><a href="#參考資料" class="headerlink" title="參考資料"></a>參考資料</h1><ul>
<li><p><a href="http://staltz.com/why-react-redux-is-an-inferior-paradigm.html" target="_blank" rel="external">WHY REACT/REDUX IS AN INFERIOR PARADIGM</a></p>
</li>
<li><p><a href="http://staltz.com/unidirectional-user-interface-architectures.html" target="_blank" rel="external">UNIDIRECTIONAL USER INTERFACE ARCHITECTURES</a></p>
</li>
<li><p><a href="https://xgrommx.github.io" target="_blank" rel="external">Rx-book</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;之前 Redux 和 Cycle.js 作者在爭辯何者才是較好的 paradigm，&lt;/p&gt;
&lt;p&gt;其實軟體開發裡面沒有銀彈，&lt;/p&gt;
&lt;p&gt;不過這種爭辯也更能夠激發出我們寫出更棒的軟體，&lt;/p&gt;
&lt;p&gt;並且去反思現行流行的東西真的是「好」的嗎？&lt;/p&gt;
    
    </summary>
    
    
      <category term="cycle.js" scheme="http://abalone0204.github.com/tags/cycle-js/"/>
    
      <category term="observable" scheme="http://abalone0204.github.com/tags/observable/"/>
    
  </entry>
  
  <entry>
    <title>我的前端工程師之路</title>
    <link href="http://abalone0204.github.com/2016/01/18/way-to-fed/"/>
    <id>http://abalone0204.github.com/2016/01/18/way-to-fed/</id>
    <published>2016-01-18T00:00:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>「這個畫面幫我稍微調一下應該沒有很難吧？」</p>
<a id="more"></a>
<p>Hi 大家，先簡介一下自己背景：</p>
<ul>
<li>非資工資科資管系(也就是所謂的非本科系)</li>
</ul>
<blockquote>
<p>其實我覺得第一點不是很重要、我也很討厭強調，</p>
<p>但偏偏就是很常被問，</p>
<p>要不然就是別人聽到你大學是XX系就會：「蛤？」</p>
<p>索性就把它列出來了。</p>
</blockquote>
<ul>
<li><p>興趣使然的前端工程師，擅長一鍵跑版</p>
</li>
<li><p>沒上過資策會、巨匠，或任何各種職訓班，但買過 tree house 的課程和幾本書</p>
</li>
<li><p>學習時間：一年半（從碼盲到現在終於可以改一些 code）</p>
</li>
<li><p>稍微熟一點的技能： JavaScript, CSS, html, React.js</p>
</li>
<li><p>預計未來要學的東西：Haskell, golang, Angular(2.0), Rx.js</p>
</li>
<li><p>這是之前相關的<a href="http://westudent-blog.sudo.com.tw/denny-sudo.html" target="_blank" rel="external">專訪</a>，但我一直都想自己寫一篇，也不是 William 寫得不好，但總覺得哪裡不對勁，也許自幹就是一種工程師的浪漫吧！</p>
</li>
</ul>
<blockquote>
<p>後來想想，也許是整篇文章太強調「本科」影響不大</p>
<p>事實上我想說的是：「非本科不該是阻擋你寫程式的理由。」</p>
</blockquote>
<ul>
<li><p>總之這篇就是來介紹一下我是怎麼慢慢上手這個職業，中間會提到一些我覺得很棒的學習資源，和吸收新知的方式。</p>
</li>
<li><p>說到吸收新知，目前首推<a href="http://weekly.codetengu.com/" target="_blank" rel="external">碼天狗</a>，它讓我禮拜一早上都會很焦慮的重新整理，大家可以感受一下。</p>
</li>
</ul>
<h1 id="Porjects"><a href="#Porjects" class="headerlink" title="Porjects"></a>Porjects</h1><ul>
<li><p>這是我簡介自己做過 projects 的<a href="http://slides.com/dennyku/deck-1#/" target="_blank" rel="external">slide</a></p>
</li>
<li><p>會放這個是因為我本來要買月費專案($7/month)，卻手滑買到年費專案($70/year)，gan，只好多多利用它了。</p>
</li>
</ul>
<hr>
<h1 id="Get-started"><a href="#Get-started" class="headerlink" title="Get started"></a>Get started</h1><p>其實我本來立志成為一個 Data Scientist ，</p>
<p>只是不小心被擺到前端的位置上去……</p>
<p>回顧這一年半的旅程，前端的東西真的太多太雜了，</p>
<p>更容易完全只知其然而不知其所以然的就開始用某個新框架、library，</p>
<p>所以對我來說，<strong>「學什麼」是副課題，「不學什麼」才是真正的關鍵</strong>。</p>
<hr>
<p>因為我前端工程師的路還沒走完，</p>
<p>所以應該在我退休或換職業（去賣雞排）之前，</p>
<p>都會繼續寫下去。</p>
<p>目前寫完三點：</p>
<ol>
<li><p>非本科系 v.s 本科系</p>
</li>
<li><p>從哪裡開始學習？</p>
</li>
<li><p>前端工程師該懂後端嗎？</p>
</li>
</ol>
<hr>
<h2 id="1-非本科系-v-s-本科系"><a href="#1-非本科系-v-s-本科系" class="headerlink" title="1. 非本科系 v.s 本科系"></a>1. 非本科系 v.s 本科系</h2><p>就來說說<strong>「本科系」</strong>來到底有沒有差。</p>
<p>首先，我們都知道學校裡的課程，</p>
<p>很少是真的專注在所謂「<strong>前端工程</strong>」上；</p>
<p>這是可以理解的，一來因為前端變化太快，</p>
<p>學期初才在說好棒棒的東西，</p>
<p>到了學期末可能就變 deprecated了。</p>
<p>所以這就代表非本科系跟本科系的人站在相同的學習立足點上了嗎？</p>
<p>No，你得面對現實，本科生就是有他的優勢在。</p>
<p>這裏要講個實習的故事。</p>
<p>我第一間去實習的新創公司，應徵的是行銷，</p>
<p>CEO 是個自己學習 JavaScript 並且把產品做出來的人，</p>
<p>更重要的是他是個很願意教的人，</p>
<p>在我表示我想朝這方向前進的意願時，</p>
<p>他很大方的說：「如果你對 JavaScript 有興趣可以教你。」</p>
<p>當時還有另一位是資管系的同學也一起，</p>
<p>第一次的作業是用 Angular 做表單的驗證，</p>
<p>怎麼讓使用者不能繼續輸入資料呢？</p>
<p>（當時的我連 JavaScript、html 都不會寫）</p>
<p>我的做法是非常土炮的將 input 換成 div 然後加上紅色的邊框，</p>
<p>另一位實習生則是使用了 disabled 這個 property，就搞定了。</p>
<p>講起來也沒什麼了不起的技巧，但不知道就是不知道。</p>
<p>我問他怎麼會知道有 disabled 這個特性，</p>
<p>他的回答也很簡單：「查文件啊！」</p>
<p>也是這次教訓，我知道要先<strong>查文件</strong>。</p>
<p>講起來蠻白癡，</p>
<p>不過會上 <a href="http://stackoverflow.com/" target="_blank" rel="external">stackoverflow</a> 和 google 找答案和看官方文件，</p>
<p>都是最基本的能力。</p>
<p>為什麼他會知道？</p>
<p>很簡單，因為平常他們在寫作業或作專題就需要這個能力。</p>
<p><img src="http://i.imgur.com/B8wms6V.png" alt="rtfm"></p>
<blockquote>
<p>既然我們遇到不會的字會查字典，<br>那為什麼我們寫軟體遇到問題時，不需要讀 doc 呢？</p>
</blockquote>
<p>而對於整個電腦的理解，非本科系的人絕對也是被甩在幾條街之外，</p>
<p>因為我們不需要修資料結構、演算法，</p>
<p>更別說對於資料庫，</p>
<p>作業系統、計算機結構、計算機組織、編譯器理解的淺薄，</p>
<p>一定要掌握上述這些知識才能寫前端嗎？</p>
<p>這是一個很大的疑問；</p>
<p>但一個了解底下發生什麼事情的人，才會更知道極限在哪裏，</p>
<p>這個絕對是肯定的。</p>
<p>有時候你寫程式時會卡在一個小小的點，想出來之後覺得沒什麼，</p>
<p>而本科系的人能從以前上述課程中的經驗去延伸，</p>
<p>（不管是演算法或是系統相關的事情）</p>
<p>比你更快速得到答案。</p>
<p>畢竟，人家花了那麼多時間了解電腦，</p>
<p>你如果不是天縱英才，要比他們理解電腦就得更努力跟上才行。</p>
<p>這裏推薦一個很棒的課程，<a href="http://www.nand2tetris.org/" target="_blank" rel="external">nand2tetris</a>，</p>
<p>上面有很詳細的指示，如果你需要影片和評分系統的話，</p>
<p>coursera 上也有開課了:<a href="https://www.coursera.org/course/nand2tetris1" target="_blank" rel="external">https://www.coursera.org/course/nand2tetris1</a>。</p>
<p>這門課會從最基本的 nand(not and) 邏輯閘開始講起，</p>
<p>用模擬器組合出自己的 CPU、記憶體，定義自己的組合語言，</p>
<p>用習慣的程式語言寫出組譯器，</p>
<p>再寫出一個超簡易版的 JVM，最後用一個簡化過後的 Java 語言（真的超簡化），</p>
<p>寫出一個俄羅斯方塊來。</p>
<p>整台電腦、軟體，都是由你一手寫出來的，不覺得很熱血嗎？</p>
<p>而且你終於也能夠看懂這張圖的笑點在哪了：</p>
<p><img src="https://media.giphy.com/media/3oEdv6pGyOH00ZiRH2/giphy.gif" alt="gif"></p>
<p>當然，如果你在學習途中發現你對系統的東西很有興趣，</p>
<p>那也恭喜你發現新天地啦！</p>
<p>想當初為了所謂堅實的基礎，還跑去圖書館借白算盤來啃，</p>
<p>那又是另一個故事了。</p>
<p>總結一下這一段，</p>
<p><strong>前端工程師也是軟體工程師</strong>，</p>
<p>對電腦一無所知的人寫出來的軟體，你敢用嗎？</p>
<p>我認為至少玩過一輪 nand2tetris 對於非本科系的人會相當有幫助，</p>
<p>本科系的人來寫前端確實是有一點優勢在，</p>
<p>但這不是認輸的藉口，</p>
<p>而是你必須比別人更努力找方法變強的原因。</p>
<p>另外，</p>
<p>千萬不要以為念研究所的人是只會讀書的書呆子，</p>
<p>比你聰明、比你努力，又比你勇敢的人永遠都多的是。</p>
<hr>
<h2 id="2-從哪裡開始學習？"><a href="#2-從哪裡開始學習？" class="headerlink" title="2. 從哪裡開始學習？"></a>2. 從哪裡開始學習？</h2><p>先來說說「單純」的前端從哪裡開始，</p>
<p>主要分成兩塊：</p>
<p>第一塊是 html 和 CSS：</p>
<p>我以前學習 html 和 CSS 的方法就是把 <a href="http://www.w3schools.com/" target="_blank" rel="external">w3schools</a>看完，</p>
<p>不能說有什麼不好，不過真的是看完大部分都忘記，</p>
<p>畢竟很多東西都馬是要用到的時候再去查。</p>
<p>但現在我會推薦 <a href="https://www.codecademy.com/" target="_blank" rel="external">codecademy</a>，</p>
<p>邊寫點東西邊學絕對是很有效的學習方式。</p>
<p>而學會基礎後，</p>
<p>要怎麼設計出好維護又乾淨的 html and CSS 那又是另一個很長的故事。</p>
<p>第二塊則是 JavaScript：</p>
<p>坦白說一年半過去，我仍然認為自己在 JavaScript 的知識上很貧瘠。</p>
<p>這裏有篇 <a href="https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.k5wxhl2s1" target="_blank" rel="external">10 個面試時應該要知道的問題</a>，</p>
<p>可以探一下自己到底對 JavaScript 理解多少。</p>
<p>這裏如果把教學全部列出來，真的是完全列不完，</p>
<p>但學習的流程是這樣子：</p>
<ul>
<li><p>掌握了基礎的語法和原則</p>
</li>
<li><p>實作練習</p>
</li>
<li><p>回頭研究基礎再繼續實作</p>
</li>
<li><p>重複以上循環不斷的把你的武器磨的更亮</p>
</li>
</ul>
<p>至於掌握基礎的語法，你可以到以下任一網站，</p>
<p>挑一個你喜歡的，上完基礎 JavaScript 課程：</p>
<ul>
<li><p><a href="https://teamtreehouse.com/" target="_blank" rel="external">tree house</a> </p>
</li>
<li><p><a href="https://www.codeschool.com/" target="_blank" rel="external">codeschool</a></p>
</li>
<li><p><a href="https://egghead.io/" target="_blank" rel="external">egghead.io</a></p>
</li>
</ul>
<p>練習一段時間後，你會發現又有好多新工具冒出來了，</p>
<p>這時候你可以先辦個 github 帳號，</p>
<p>首先 watch awesome 這個 repo: <a href="https://github.com/sindresorhus/awesome" target="_blank" rel="external">https://github.com/sindresorhus/awesome </a>，</p>
<p>看一下你喜歡的領域有沒有什麼好東西，</p>
<p>再挑幾個你最有興趣的 repo 按下 watch，</p>
<p>最後再開始訂閱各大框架或社群的 weekly，</p>
<p>接著就是準備被源源不絕的資訊轟炸、不斷的學習和升級。</p>
<p>而值得一提的是， JavaScript 有很多工具可以用，</p>
<p>不管是 library 還是 framework，</p>
<p>學習之前，真的必須想一想：</p>
<p><strong>「你真的需要用它嗎？」</strong></p>
<p>舉例來說：</p>
<p>React 的確相當的好用，</p>
<p>但是你的畫面真的有那麼多 state 要處理嗎？</p>
<p>有些人簡單的認為 SPA(Single Page Application)就要用 React，</p>
<p>我得說不一定，假如根本沒有那麼複雜，</p>
<p>也許你只是需要一個 template engine 而已，</p>
<p>而把 React 當作 html 的 template 來用，</p>
<p>實在是有點太小看它了。</p>
<p>什麼時候該用 React 或是 React 到底好在哪裏，</p>
<p>這個議題其實已經超出了本篇文章的範圍，</p>
<p>有興趣的可以看這篇：<a href="https://medium.com/@dan_abramov/react-components-elements-and-instances-90800811f8ca" target="_blank" rel="external">React Components, Elements, and Instances by Dan Abramov(Redux 作者)</a></p>
<p>這也是為什麼我一直遲遲沒有碰 Angular 的原因，</p>
<p>（因為我還沒遇過複雜到需要用到它的情境）</p>
<p>但我認為在選擇前端的框架時，這篇文章很值得一看再看：</p>
<ul>
<li><a href="https://github.com/livoras/blog/issues/11" target="_blank" rel="external">界面之下：還原真實的MV*模式 </a></li>
</ul>
<p>裡面並沒有太多的程式碼，只有比較 high level 的概念，</p>
<p>但看完你會比較理解別人說 MVC、MVP、MVVM、Model 2 是在說些什麼，</p>
<p>前端主要工作之一就是處理使用者介面（UI），</p>
<p>我認為理解這些模式是一個前端工程師必備的 common sense，</p>
<p>這些概念比起淘汰迅速的工具們，是比較能夠保值的，</p>
<p>並且也會漸漸影響你挑選工具的眼光。</p>
<p>而 medium 上也有許多好文章可以看，</p>
<p>twitter 上面也有很多大神可以讓你追蹤，</p>
<p>不要把這些事情當作是在大拜拜，</p>
<p>覺得追蹤越多人自己越屌，</p>
<p>重要的是你看他們生產的內容時得到了什麼。</p>
<p>另外臉書上的前端社團也很值得加入，台灣人的軟體能力是很強悍的：</p>
<ul>
<li><p><a href="https://www.facebook.com/groups/f2e.tw/?fref=ts" target="_blank" rel="external">Front-End Developers Taiwan</a></p>
</li>
<li><p><a href="https://www.facebook.com/groups/augularjs.tw/?fref=ts" target="_blank" rel="external">AngularJS.tw</a></p>
</li>
<li><p><a href="https://www.facebook.com/groups/reactjs.tw/?fref=ts" target="_blank" rel="external">ReactJS.tw</a></p>
</li>
<li><p><a href="https://www.facebook.com/groups/javascript.tw" target="_blank" rel="external">JavaScript.tw</a></p>
</li>
</ul>
<p>重要的是在上面發問，也會有人很熱心的回答你。</p>
<p>假如這樣都還是讓你資訊焦慮，可以開始訂閱一些技術週刊，</p>
<p>像是<a href="http://weekly.codetengu.com/" target="_blank" rel="external">碼天狗</a>、<a href="http://weekly.techbridge.cc/" target="_blank" rel="external">TechBridge</a>，</p>
<p>讓 curators 來幫你整理一些技術上的新知。</p>
<p>已經盡量精簡了資訊來源，希望能讓新手們不要太無所適從。</p>
<hr>
<h2 id="3-前端工程師該懂後端嗎？"><a href="#3-前端工程師該懂後端嗎？" class="headerlink" title="3. 前端工程師該懂後端嗎？"></a>3. 前端工程師該懂後端嗎？</h2><p>後端跟前端是完全不一樣的專業，</p>
<p>有人說 Node.js 能讓前端工程師跨足到後端去。</p>
<p>(Isomorphic？)</p>
<p>事實上前端工程師想往後端走還是有許多需要學習的，</p>
<p>不管是資料庫或是系統面，都不是平常前端會碰觸到的領域，</p>
<p>認為自己會寫 JavaScript 就硬上的下場通常是：</p>
<ul>
<li><p>效能有問題</p>
</li>
<li><p>資安有問題</p>
</li>
<li><p>整個 server-side 的 code 都他媽很有問題</p>
</li>
</ul>
<p>聽起來是很糟糕的事情，所以請千萬尊重專業，</p>
<p>讓我們前端歸前端、政治歸政治（欸？）。</p>
<p>那前端到底要理解後端到怎樣的程度呢？</p>
<p>這是一個很 tricky 的問題，</p>
<p>大部份人會說：<strong>「至少要會接資料啦！」</strong></p>
<p>但要學到會接資料揪竟是需要怎樣的能力呢？</p>
<p>真的有人學到剛剛好就喊停的嗎？</p>
<p>最好的方法其實就是自己去玩一套網頁框架，</p>
<p>後端前端都寫一遍。</p>
<p>Rails, Laravel, Django 都是我認為不錯的選擇，</p>
<p>（Koa 也很不錯啦……）</p>
<p>重點是去感受一下自己要怎樣設計 DB 的 Schema，</p>
<p>怎樣做正規化、怎樣避免 N+1 Query，</p>
<p>以及整個框架的架構為什麼要這樣設計，</p>
<p>最後再跟自己拉的頁面整合在一起，然後部署上去，</p>
<p>（用 heroku 是有點偷懶，不過如果你對 server 真的沒興趣，還是可以考慮這樣做沒差）</p>
<p>等做到這一步，「至少要會接資料」這一點，</p>
<p>早就迎刃而解了。</p>
<p>對了，</p>
<p>記得也不要因為自己寫過後端的 code 就說自己是 full-stack，</p>
<p>這就跟你會收發 email 就說自己懂電腦一樣會被笑。</p>
<p>(IT crowd 真的是個不錯的影集)</p>
<p>有興趣可以看看這篇：</p>
<ul>
<li><a href="http://www.infoq.com/cn/articles/nodejs-in-front-end-engineer-view" target="_blank" rel="external">一個前端工程師眼中的 Node.js</a></li>
</ul>
<p>可以略懂 Async 在 server 端和 client 端的差異。</p>
<hr>
<p>目前大概走到這裡，還有很多沒說到，</p>
<p>但學個基礎開始實作後就能體會到許多了。</p>
<blockquote>
<p>至於實作，</p>
<p>可以選擇自己寫個身體健康、參與 open source，</p>
<p>或是去實習都是非常好的選擇</p>
</blockquote>
<p>不管是 RWD、mobile web、跨瀏覽器的處理、SEO，</p>
<p>動畫該用 CSS3 或是 JavaScript 還是 SVG？</p>
<p>每天都有新的問題可以鑽研，</p>
<p>目前就先寫到這裡啦！</p>
<p>希望可以改變一些覺得前端工程師只是在切切版的想法，</p>
<p>也希望能幫助到想往前端工程師邁進的人。</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;「這個畫面幫我稍微調一下應該沒有很難吧？」&lt;/p&gt;
    
    </summary>
    
    
      <category term="front-end" scheme="http://abalone0204.github.com/tags/front-end/"/>
    
      <category term="career" scheme="http://abalone0204.github.com/tags/career/"/>
    
  </entry>
  
  <entry>
    <title>CSS Modules: 模組化 CSS</title>
    <link href="http://abalone0204.github.com/2016/01/09/css-modules/"/>
    <id>http://abalone0204.github.com/2016/01/09/css-modules/</id>
    <published>2016-01-09T00:00:00.000Z</published>
    <updated>2016-09-26T13:55:44.058Z</updated>
    
    <content type="html"><![CDATA[<p>時至今日，我最討厭的東西就是亂七八糟的 CSS 還有 KMT，</p>
<p>這兩個東西有一點很一致：</p>
<blockquote>
<p>不管我們再怎麼討厭它，<br>都還是得面對它、處理它。</p>
</blockquote>
<h2 id="先說結論："><a href="#先說結論：" class="headerlink" title="先說結論："></a>先說結論：</h2><ul>
<li><p>如果討厭寫 CSS，就更應該用這種方式來寫</p>
</li>
<li><p>我們應該用 module 化的方式來思考每個畫面上的東西</p>
</li>
<li><p>讓需要「工人智慧」的地方減到最少</p>
</li>
</ul>
<blockquote>
<p>「如果你覺得 CSS 很亂的話，那代表你心中沒有架構。」</p>
</blockquote>
<h2 id="Prerequisite"><a href="#Prerequisite" class="headerlink" title="Prerequisite"></a>Prerequisite</h2><ul>
<li><p>會使用 webpack（幾乎只要會改 config 就行了）</p>
</li>
<li><p>把 CSS 當一回事的人</p>
</li>
</ul>
<hr>
<h2 id="為什麼需要去思考-CSS-的「架構」？"><a href="#為什麼需要去思考-CSS-的「架構」？" class="headerlink" title="為什麼需要去思考 CSS 的「架構」？"></a>為什麼需要去思考 CSS 的「架構」？</h2><p>曾幾何時，我也覺得 CSS 是一個他媽有夠亂七八糟的東西，</p>
<p>直到不小心開始寫前端，我才發現前端不只是 JavaScript，</p>
<p>從 CSS 到 html 的設計，都需要仔細去思考「架構」這件事，</p>
<p>否則很容易讓技術債債台高築，到最後一發不可收拾。</p>
<p>使用起來合邏輯的東西，不代表能夠用很「邏輯化」的方式寫出來，</p>
<p>這正是 CSS 為什麼很容易亂七八糟的原因，</p>
<p>因為我們常常需要去指定很多畫面上的細節（imperative）：</p>
<blockquote>
<p>「欸欸，你這邊 width 要 300px，然後 margin 要設成 0 auto 才能置中」</p>
</blockquote>
<p>而不是直觀的用程式碼來宣告我們想要畫面長怎樣（declarative）：</p>
<blockquote>
<p>「我們要一個看起來不錯的畫面」</p>
</blockquote>
<p>處理太多細節很容易出錯，像是螢幕或視窗大小不一樣 300px 就不一定 ok 了，</p>
<p>而第二個 declarative way 似乎又太過理想化。</p>
<p>而我認為折衷的方式就是 module 化 CSS，</p>
<p>雖然也需要去實作 module 內的細節（imperative），</p>
<p>但完成之後，就可以將這些 module 組裝起來，</p>
<p>重複使用時就不需要去實做那麼多的細節，</p>
<p>沒錯，我們又往 declarative programming更進一步了。</p>
<p>現在看起來還是比較 high level 的概念，</p>
<p>但我認為知道為什麼要這樣做很重要，</p>
<p>稍後會在例子裏看到這樣做的好處是什麼。</p>
<hr>
<p>在開始之前先講解一下兩個會推薦使用的工具，</p>
<p>（你也可以依自己喜歡的配置啦！）</p>
<p>分別是 Autoprefixer 以及 PostCSS。</p>
<h2 id="Autoprefixer"><a href="#Autoprefixer" class="headerlink" title="Autoprefixer"></a>Autoprefixer</h2><p>假如熟悉 postcss 和 autoprefixer 在幹嘛的人可以直接跳下一段了。</p>
<p>其實我們平常在寫 CSS 的時候，為了處理跨瀏覽器的問題，</p>
<p>常常需要寫很噁心的 prefix，</p>
<p>就算有 SASS 的 include 語法，prefix 還是很噁心。</p>
<p>看到 autoprefixer 出現真是讓人痛哭流涕的一件事，</p>
<p>因為這代表以後有人會幫我們處理好 prefix，</p>
<p>同時還會把太舊的 prefix 給移除掉。（像是 <code>border-radius</code>）</p>
<p>這裏就直接來安裝進專案吧！</p>
<p><code>webpack.config.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> autoprefixer = <span class="built_in">require</span>(<span class="string">'autoprefixer'</span>);</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports = &#123;</div><div class="line">    <span class="built_in">module</span>: &#123;</div><div class="line">        loaders: [</div><div class="line">            &#123;</div><div class="line">                test:   <span class="regexp">/\.css$/</span>,</div><div class="line">                loader: <span class="string">"style-loader!css-loader!postcss-loader"</span></div><div class="line">            &#125;</div><div class="line">        ]</div><div class="line">    &#125;,</div><div class="line">    postcss: [ autoprefixer(&#123; browsers: [<span class="string">'last 2 versions'</span>] &#125;) ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>唯一需要說明一下的就是可以指定我們要 support 到多老舊的 browser啦！</p>
<p>就這樣，恭喜你！</p>
<hr>
<h2 id="PostCSS"><a href="#PostCSS" class="headerlink" title="PostCSS"></a>PostCSS</h2><p>PostCSS 是一個可以用 JavaScript plugins 將 style 轉成我們想要樣子的工具。</p>
<p>（包括 lint, variables, mixins，以及好多東西……）</p>
<p>確切一點來說， PostCSS 是一個 node.js 的 package，</p>
<p>它可以將我們原本的 CSS 檔案轉成 AST(Abstraction Syntax Tree)，</p>
<p>接著我們就可以藉由這個 API 來對 CSS 做事情，</p>
<p>做完後再將它轉成 String，輸出成我們想要的 CSS，</p>
<p>如果你懶得自己寫 plugin 來處理也不用擔心，</p>
<p>現在已經有兩百多個 plugins 在那裡等你愛智求真了。</p>
<p>我知道一定有人這時候在想：「那 SASS 呢？」</p>
<p>沒錯，這兩者看起來似乎有點像，不過可以先看一下這篇文章：</p>
<ul>
<li><a href="http://davidtheclark.com/excited-about-postcss/" target="_blank" rel="external">I’m Excited About PostCSS But I’m Scared to Leave Sass</a></li>
</ul>
<p>這裏則是值得一看的補充資料，其實官方的 readme 裏也都有寫：</p>
<ul>
<li><p><a href="http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889" target="_blank" rel="external">tut+的教學</a></p>
</li>
<li><p><a href="http://nicolasgallagher.com/custom-css-preprocessing/" target="_blank" rel="external">一個前端用 node.js 來寫 CSS 的 preprocessor 也是很正常的事</a></p>
</li>
</ul>
<p>簡言之，PostCSS 跟 SASS 或 LESS 最不一樣的點是：</p>
<p>「我們可以只採用我們想要的部分，並將其組裝起來。」</p>
<p>這不就是 Compoasable 和模組化嗎？</p>
<p>接著就來看看如何在 webpack 中設定 postcss，</p>
<p>和使用各種 plugins。</p>
<p>（坦白說這裏才是最頭痛的部分）</p>
<p>使用 webpack 雖然簡單，但 config 的寫法太雜亂了，</p>
<p>完成同樣一件事可以有好幾種方法，</p>
<p>目前連官方文件上也沒有一個一致的 best practice。</p>
<p>而<a href="https://github.com/ruanyf/webpack-demos" target="_blank" rel="external">阮義峰的這篇教學</a>是我目前看過寫的最清楚易懂的，</p>
<p>從 entry 到跟 react 一起使用都有說到。</p>
<hr>
<h2 id="CSS-modules"><a href="#CSS-modules" class="headerlink" title="CSS modules"></a>CSS modules</h2><p>假如你直接跳過前兩個工具，其實也是 ok 啦！</p>
<p>因為 webpack 的 css-loader 本身就內建 module 功能：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="built_in">module</span>: &#123;</div><div class="line">        loaders: [&#123;</div><div class="line">            test: <span class="regexp">/\.[s]?css$/</span>,</div><div class="line">            loader: <span class="string">'style!css?modules!sass'</span></div><div class="line">        &#125;]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>現在終於要來講一下 CSS modules 可以做到什麼事情。</p>
<ul>
<li>組合（Composition）</li>
</ul>
<p>我們能夠將 selector 組合在一起</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="selector-class">.className</span> &#123;</div><div class="line">  <span class="attribute">color</span>: green;</div><div class="line">  <span class="attribute">background</span>: red;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="selector-class">.otherClassName</span> &#123;</div><div class="line">  <span class="attribute">composes</span>: className;</div><div class="line">  <span class="attribute">color</span>: yellow;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裏要注意的是 composes 必須寫在其他 properties 的前面。</p>
<p>而我們也可以 compose 多個 className：</p>
<p><code>composes: classNameA classNameB;</code></p>
<p>乍看之下跟 SASS 的 extend 有點像，</p>
<p>但讓我們繼續看下去。</p>
<h2 id="Dependencies"><a href="#Dependencies" class="headerlink" title="Dependencies"></a>Dependencies</h2><p>假設我們現在有另一個檔案: style.css</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">.className &#123;</div><div class="line">    // some style</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="selector-class">.otherClassName</span> &#123;</div><div class="line">  <span class="attribute">composes</span>: className from <span class="string">"./style.css"</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這給了我們很大的彈性，但小心不要 override properties，</p>
<p>我覺得官方文件的這一句話寫得很棒：</p>
<blockquote>
<p>Best if classes do a single thing and dependencies are hierarchic.</p>
</blockquote>
<p>這的確是我們在設計 CSS module 時，要常存心中的一句話。</p>
<h2 id="Usage-with-preprocessors"><a href="#Usage-with-preprocessors" class="headerlink" title="Usage with preprocessors"></a>Usage with preprocessors</h2><p>這裏主要是說要如何運用 preprocessor ，</p>
<p>因為我們有時候還是需要 global 的 class。</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="selector-pseudo">:global</span> &#123;</div><div class="line">  <span class="selector-class">.global-class-name</span> &#123;</div><div class="line">    <span class="attribute">color</span>: green;</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<h2 id="Rewrite-with-CSS-Modules"><a href="#Rewrite-with-CSS-Modules" class="headerlink" title="Rewrite with CSS Modules"></a>Rewrite with CSS Modules</h2><p>如果你是打從專案一開始就使用 css module ，</p>
<p>那恭喜你！</p>
<p>但「通常」現有的專案上都是用 SASS 來解決，</p>
<p>這裡就以我工作上的專案來做例子。</p>
<p>這裏要提一下我們後端用的是 Rails，</p>
<p>Rails 有個邪惡的好東西叫做 <a href="https://ihower.tw/rails4/assets-pipeline.html" target="_blank" rel="external">Asset Pipeline</a>，</p>
<p>它會將靜態資源壓成一個檔案，減少 request 數。</p>
<p>自動幫你做這件事聽起來很美好，</p>
<p>但實際上因為 css 有 global scope 的問題，</p>
<p>所以要怎麼確保每一頁只 load 到自己要的 style 呢？</p>
<p>我的做法是每一頁會有一個專屬的 id，</p>
<p>而命名的方式就是以 controller 加上 action 的名稱來命名。</p>
<p>像是 posts_controller 的首頁，</p>
<p>我就會給它專屬的一支檔案<code>posts_index.scss</code></p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">#posts_index &#123;</div><div class="line">    // some style</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這樣做的第一個好處很明顯，</p>
<p>就是每個頁面裡的樣式就只會影響 id 裡的 scope。</p>
<p>那說好的 module 呢？</p>
<p>這裏就要用到 SASS 的 <code>extend</code>，</p>
<p>假設 posts 和 show 都有一模一樣的 header，</p>
<p>這時候我就會把 header 抽出來像下面這樣：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">%header &#123;</div><div class="line">    header &#123;</div><div class="line">        //  some style</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">import "./header.scss";</div><div class="line"></div><div class="line">#posts_index &#123;</div><div class="line">    @extend %header;</div><div class="line">    // some style</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">import "./header.scss";</div><div class="line"></div><div class="line">#posts_show &#123;</div><div class="line">    @extend %header;</div><div class="line">    // some style</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>看起來挺方便，</p>
<p>而且 Rails 的 routing 通常都是 restful 的，</p>
<p>所以理論上這樣 CSS 的名字也有一定的規則可循，</p>
<p>不會找不到檔案在哪裡。</p>
<p>（就算有自動搜尋，也要知道下哪些關鍵字吧！）</p>
<p>但，</p>
<p>如果今天根據 user 的身份不同，</p>
<p>會 render 不一樣的頁面呢？</p>
<p><code>#posts_index_super_user</code>？</p>
<p>沒錯，問題又變得開始複雜起來，</p>
<p>原因就出在它仍然是 global scope，</p>
<p>而我試圖想從命名來解決這件事情，</p>
<p>我常常在想：「啊！如果 CSS 是 local scope該有多好？」</p>
<blockquote>
<p>A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.</p>
</blockquote>
<p>天啊！這解決了根本上的問題！</p>
<p>假如能夠用 component-based 的方式來思考，</p>
<p>讓 react component 從 css module 之間有對應的 name 來讀取樣式，</p>
<p>那不就更棒了嗎？</p>
<p>以後的資料夾結構會長這樣子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">├── components</div><div class="line">│   ├── ui-App</div><div class="line">│   │   ├── index.css</div><div class="line">│   │   └── index.js</div><div class="line">│   ├── ui-Avatar</div><div class="line">│   │   ├── index.css</div><div class="line">│   │   └── index.js</div><div class="line">│   └── ui-Profile</div><div class="line">│       ├── fonts</div><div class="line">│       │   └── opensans-regular-webfont.woff</div><div class="line">│       ├── images</div><div class="line">│       │   └── icon-user.png</div><div class="line">│       ├── index.css</div><div class="line">│       └── index.js</div><div class="line">└── styles</div><div class="line">    ├── base.css</div><div class="line">    └── theme.css</div></pre></td></tr></table></figure>
<p>一個資料夾底下就放著 component.js, component.css，</p>
<p>本身就是一個 micro-service，</p>
<p>而我們要做的正是把這些 micro-service 給組裝起來變成一個頁面，</p>
<p>最後再把這些頁面組裝起來變成 Application，相當舒服。</p>
<p>不過要如何從現有的專案改寫呢？</p>
<p>這裏就拿這個小小的部落格來舉例，</p>
<p>因為我一開始是用<a href="https://github.com/abalone0204/generator-suku" target="_blank" rel="external">自己寫的 generator</a> 生成專案，</p>
<p>（小打一下廣告，</p>
<p>平常開發前端 component 就是在這個生成的專案上開發，</p>
<p>弄好 react 和 hmr 之後，其實蠻方便的。）</p>
<p>順帶一提，這是開始改寫前的樣子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">stylesheets/</div><div class="line">    ├── animations</div><div class="line">    │   ├── blink.scss</div><div class="line">    │   ├── loading.scss</div><div class="line">    │   └── spins.scss</div><div class="line">    ├── code_highlights</div><div class="line">    │   └── default.scss</div><div class="line">    ├── colors.scss</div><div class="line">    ├── components</div><div class="line">    │   ├── Nav</div><div class="line">    │   │   └── _icon_bar.css</div><div class="line">    │   └── common</div><div class="line">    │       └── loading.scss</div><div class="line">    ├── nav.scss</div><div class="line">    ├── pages</div><div class="line">    │   ├── about.scss</div><div class="line">    │   ├── home.scss</div><div class="line">    │   └── post.scss</div><div class="line">    └── style.scss</div></pre></td></tr></table></figure>
<p>到最後 stylesheets 裡面只會剩下 global 的 css 檔案，</p>
<p>像是 base.css 或是 theme.css 。</p>
<p>首先第一步當然就是處理 global 的 css，</p>
<p>思考的方向很簡單，就是哪些東西是每一個頁面都用得到的呢？</p>
<p>所以我們把 body, a, h1~h5之類的東西先拔出來：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">:global &#123;</div><div class="line">    a &#123;</div><div class="line">        color: inherit;</div><div class="line">        text-decoration: none;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    body &#123;</div><div class="line">        margin: 0;</div><div class="line">        letter-spacing: 1px;</div><div class="line">        color: #23263a;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    * &#123;</div><div class="line">        font-family: 'Noto Sans TC',Microsoft JhengHei,Microsoft YaHei, LiHei Pro, Heiti TC, sans-serif;</div><div class="line">        font-weight: 200;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    .wf-loading &#123;</div><div class="line">        * &#123;</div><div class="line">            font-family: Microsoft JhengHei, Microsoft YaHei, LiHei Pro, Heiti TC, sans-serif;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        font-family: Microsoft JhengHei, Microsoft YaHei, LiHei Pro, Heiti TC, sans-serif;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著來處理我們的 Nav bar，</p>
<p>從這裡開始，就要進入 module 化的思考方式，</p>
<p>一開始的時候你可能會覺得，欸？幹嘛這樣做？</p>
<p>但越到後面你會發現一旦你習慣這樣思考，</p>
<p>很多原本難解的問題都會迎刃而解，</p>
<p>尤其是用組裝的方式來思考畫面的元件，</p>
<p>能讓多狀態的呈現變得更簡單，</p>
<p>也更能明白哪個部分該抽象化出來變成 base。</p>
<p>先來看看這個 Nav 的例子。</p>
<hr>
<p>預計會在以下幾個步驟循序漸進地去思考如何去寫 CSS Modules：</p>
<ul>
<li><p>讀一下舊有的 js, css</p>
</li>
<li><p>最外層的 global selector</p>
</li>
<li><p>沒有狀態改變的 local selector</p>
</li>
<li><p>有狀態改變的 local selector</p>
</li>
</ul>
<h3 id="1-分析舊有的-js-css"><a href="#1-分析舊有的-js-css" class="headerlink" title="1. 分析舊有的 js, css"></a>1. 分析舊有的 js, css</h3><figure class="highlight jsx"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</div><div class="line">    <span class="keyword">constructor</span>(props) &#123;</div><div class="line">        <span class="keyword">super</span>(props);</div><div class="line">        <span class="keyword">this</span>.state = &#123;show: <span class="literal">false</span>&#125;;</div><div class="line">        <span class="keyword">this</span>.toggleIcon = <span class="keyword">this</span>.toggleIcon.bind(<span class="keyword">this</span>);</div><div class="line">    &#125;</div><div class="line">    toggleIcon() &#123;</div><div class="line">        <span class="keyword">this</span>.setState(&#123;show: !<span class="keyword">this</span>.state.show&#125;)</div><div class="line">    &#125;</div><div class="line">    render() &#123;</div><div class="line">        <span class="keyword">let</span> &#123;show&#125; = <span class="keyword">this</span>.state;</div><div class="line">        <span class="keyword">let</span> className = show ? <span class="string">"active"</span> : <span class="string">""</span>;</div><div class="line">        <span class="keyword">return</span> (</div><div class="line">            &lt;nav&gt;</div><div class="line">                &lt;div id="logo" className=&#123;className&#125;/&gt;</div><div class="line">                &lt;div id="toggle_icon" </div><div class="line">                     className=&#123;className&#125;</div><div class="line">                     onClick=&#123;this.toggleIcon&#125;</div><div class="line">                /&gt;</div><div class="line">                &#123;</div><div class="line">                    show ? </div><div class="line">                    (</div><div class="line">                        &lt;ul id="nav_list" className=&#123;className&#125;&gt;</div><div class="line">                            &lt;li&gt;&lt;Link to="/about"&gt;About&lt;/Link&gt;&lt;/li&gt;</div><div class="line">                            &lt;li&gt;&lt;i className="fa fa-github-alt"&gt;&lt;/i&gt;&lt;/li&gt;</div><div class="line">                            &lt;li&gt;&lt;i className="fa fa-facebook"&gt;&lt;/i&gt;&lt;/li&gt;</div><div class="line">                        &lt;/ul&gt;</div><div class="line">                    ) :</div><div class="line">                    null</div><div class="line">                &#125;</div><div class="line">            &lt;/nav&gt;</div><div class="line">            )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到我們的 toggle_icon 會隨著 show 的值而改變樣式，</p>
<p>至於怎樣改變？就來看看原先架構下的 CSS 怎麼寫。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div></pre></td><td class="code"><pre><div class="line">@import "./colors.scss";</div><div class="line">@import "./components/Nav/icon_bar";</div><div class="line"></div><div class="line">nav &#123;</div><div class="line">    position: fixed;</div><div class="line">    z-index: 5;</div><div class="line">    top: 0;</div><div class="line">    width: 100%;</div><div class="line">    color: white;</div><div class="line">    background: $deep_blue;</div><div class="line">    padding: 14px;</div><div class="line">    height: 28px;</div><div class="line"></div><div class="line">    a &#123;</div><div class="line">        color: inherit;</div><div class="line">        text-decoration: none;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #logo &#123;</div><div class="line">        height: 28px;</div><div class="line">        width: 28px;</div><div class="line">        display: inline-block;</div><div class="line">        background-image: url("../img/icon.png");</div><div class="line">        background-size: cover;</div><div class="line">        transition: transform 1s ease;</div><div class="line"></div><div class="line">        &amp;:hover &#123;</div><div class="line">            animation: shake;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #logo.active &#123;</div><div class="line">        color: $sudo_green;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #toggle_icon &#123;</div><div class="line">        position: absolute;</div><div class="line">        top: 50%;</div><div class="line">        transform: translateY(-50%);</div><div class="line">        right: 50px;</div><div class="line">        display: inline-block;</div><div class="line"></div><div class="line">        @extend %icon_bar;</div><div class="line"></div><div class="line">        cursor: pointer;</div><div class="line"></div><div class="line">        &amp;:before,</div><div class="line">        &amp;:after &#123;</div><div class="line">            @extend %icon_bar;</div><div class="line"></div><div class="line">            content: '';</div><div class="line">            display: block;</div><div class="line">            position: absolute;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        &amp;:before &#123;</div><div class="line">            margin-top: -10px;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        &amp;:after &#123;</div><div class="line">            margin-top: 10px;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #toggle_icon.active &#123;</div><div class="line">        background: transparent;</div><div class="line">        transition-property: background-color, transform;</div><div class="line">        transition-duration: .2s;</div><div class="line"></div><div class="line">        &amp;:before, &amp;:after &#123;</div><div class="line">            background: $sudo_green;</div><div class="line">            transition-property: background-color, transform;</div><div class="line">            transition-duration: .2s;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        &amp;:before &#123;</div><div class="line">            transform: rotate(45deg);</div><div class="line">            transform-origin: 0 0;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        &amp;:after &#123;</div><div class="line">            transform: rotate(-45deg);</div><div class="line">            transform-origin: 0 5px;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    #nav_list &#123;</div><div class="line">        position: fixed;</div><div class="line">        height: 100vh;</div><div class="line">        background: #23263a;</div><div class="line">        text-align: center;</div><div class="line">        top: 56px;</div><div class="line">        left: 0;</div><div class="line">        display: block;</div><div class="line">        padding: 5px 15px;</div><div class="line">        margin: 0;</div><div class="line"></div><div class="line">        li &#123;</div><div class="line">            display: block;</div><div class="line">            padding: 5px;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<h2 id="2-最外層的-global-selector"><a href="#2-最外層的-global-selector" class="headerlink" title="2. 最外層的 global selector"></a>2. 最外層的 global selector</h2><p>如果你有寫過 react native 的話，</p>
<p>就能體會到 style object 的好處，</p>
<p>假如沒有，那現在這是好好來玩玩看的時候。</p>
<p>我們從最外層開始拆解。</p>
<p>（其實由內而外、由外而內各有好壞，但這可能又要寫另外一篇了）</p>
<p>最外層的當然就是原生的 nav tag，</p>
<p>這裏其實大可直接給他 global</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">:global &#123;</div><div class="line">    nav &#123;</div><div class="line">        position: fixed;</div><div class="line">        z-index: 5;</div><div class="line">        top: 0;</div><div class="line">        width: 100%;</div><div class="line">        color: white;</div><div class="line">        background: #23263a;</div><div class="line">        padding: 14px;</div><div class="line">        height: 28px;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<h2 id="3-沒有狀態改變的-local-selector"><a href="#3-沒有狀態改變的-local-selector" class="headerlink" title="3. 沒有狀態改變的 local selector"></a>3. 沒有狀態改變的 local selector</h2><p>往下看到 logo ：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="selector-class">.logo</span> &#123;</div><div class="line">    <span class="attribute">height</span>: <span class="number">28px</span>;</div><div class="line">    <span class="attribute">width</span>: <span class="number">28px</span>;</div><div class="line">    <span class="attribute">display</span>: inline-block;</div><div class="line">    <span class="attribute">background-image</span>: <span class="built_in">url</span>(<span class="string">"../../../static/img/icon.png"</span>);</div><div class="line">    <span class="attribute">background-size</span>: cover;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>要怎麼 import 它呢？</p>
<p>首先別忘記在 webpack 的 config 裡開啟 css modules 的功能。</p>
<p>再來只要這樣：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> style <span class="keyword">from</span> <span class="string">"./Nav.scss"</span>;</div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Nav</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</div><div class="line">    render()&#123;</div><div class="line">       <span class="keyword">return</span> ( </div><div class="line">           ...</div><div class="line">           &lt;div className=&#123;style.logo&#125;/&gt;</div><div class="line">           ...</div><div class="line">       )</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>style.logo</code> 讀到的就會是 webpack 幫我們生成的唯一字串，</p>
<p>不用擔心會跟其他 class 重複，不相信的話 console.log 看一下，</p>
<p>而跟以往相同，webpack 也會自動去幫我們寫入 style 到 head 裡面，</p>
<p>對應到的 class name 就是剛剛生成的唯一字串。</p>
<p>原理大概是這樣子。</p>
<hr>
<h3 id="4-有狀態改變的-local-selector"><a href="#4-有狀態改變的-local-selector" class="headerlink" title="4. 有狀態改變的 local selector"></a>4. 有狀態改變的 local selector</h3><p>再來則是為什麼我仍然使用 SASS 的原因： extend</p>
<p>來看看 toggle_icon，他就是我們平常看到手機版的選單，</p>
<p>按了之後會變形。</p>
<p>先直接看它原本的 CSS 長怎樣：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">#toggle_icon &#123;</div><div class="line">    position: absolute;</div><div class="line">    top: 50%;</div><div class="line">    transform: translateY(-50%);</div><div class="line">    right: 50px;</div><div class="line">    display: inline-block;</div><div class="line">    @extend %icon_bar;</div><div class="line">    cursor: pointer;</div><div class="line">    &amp;:before,</div><div class="line">    &amp;:after &#123;</div><div class="line">        @extend %icon_bar;</div><div class="line">        content: '';</div><div class="line">        display: block;</div><div class="line">        position: absolute;</div><div class="line">    &#125;</div><div class="line">    &amp;:before &#123;</div><div class="line">        margin-top: -10px;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:after &#123;</div><div class="line">        margin-top: 10px;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>我知道有一些 PostCSS 的插件可以解決，<br>但這篇的重點在於模組化 CSS 的思考，所以就暫時先擱著啦！）</p>
</blockquote>
<p>因為那個 icon 有三個橫條，每個橫條的設定都差不多，</p>
<p>所以我寫了一個 icon_bar 來被 extend。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">%<span class="selector-tag">icon_bar</span> &#123;</div><div class="line">    <span class="attribute">width</span>: <span class="number">30px</span>;</div><div class="line">    <span class="attribute">height</span>: <span class="number">5px</span>;</div><div class="line">    <span class="attribute">transition-property</span>: background-color, transform;</div><div class="line">    <span class="attribute">transition-duration</span>: .<span class="number">2s</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接著則是重頭戲，</p>
<p>對於畫面來說，這個 toggle_icon 會有兩個狀態，</p>
<p>也就是說我們會有兩個 class 來處理它，</p>
<p>但這兩個狀態又有許多共同點，怎麼辦呢？</p>
<p>答案很簡單：</p>
<blockquote>
<p>抽出來當 base，讓兩個狀態的 class 去 composes 這個 base 就好啦！</p>
</blockquote>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line">.toggle_icon_base &#123;</div><div class="line">    @extend %icon_bar;</div><div class="line">    position: absolute;</div><div class="line">    top: 50%;</div><div class="line">    transform: translateY(-50%);</div><div class="line">    right: 50px;</div><div class="line">    display: inline-block;</div><div class="line">    cursor: pointer;</div><div class="line">    transition-property: background-color, transform;</div><div class="line">    transition-duration: .2s;</div><div class="line">    &amp;:before,</div><div class="line">    &amp;:after &#123;</div><div class="line">        // pseudo-selector 是不能使用 composes 的</div><div class="line">        // 這就是為什麼我仍需要 @extend</div><div class="line">        @extend %icon_bar; </div><div class="line">        content: '';</div><div class="line">        display: block;</div><div class="line">        position: absolute;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:before &#123;</div><div class="line">        margin-top: -10px;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:after &#123;</div><div class="line">        margin-top: 10px;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>這裏抽出來的就是兩方都不會變的 properties，</p>
<p>把 transition 放在 base 裏的好處就是能看到狀態之間的變化，</p>
<p>這樣能實現一些簡單的動畫。</p>
<p>接著就是把我們寫好的 base 組裝起來而已，</p>
<p>toggle_icon！附身合體！</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">.toggle_icon &#123;</div><div class="line">    composes: toggle_icon_base; // 記得要放在其他 properties 前面</div><div class="line">    background-color: white;</div><div class="line"></div><div class="line">    &amp;:before,</div><div class="line">    &amp;:after &#123;</div><div class="line">        background-color: white;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:hover &#123;</div><div class="line">        background-color: #50e2c2;</div><div class="line"></div><div class="line">        &amp;:before,</div><div class="line">        &amp;:after &#123;</div><div class="line">            background-color: #50e2c2;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>狀態的改變每個人都有自己喜好的方式，可以自行調整：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">.toggle_icon--active &#123;</div><div class="line">    composes: toggle_icon_base;</div><div class="line">    background: transparent;</div><div class="line">    </div><div class="line"></div><div class="line">    &amp;:before, &amp;:after &#123;</div><div class="line">        background: #50e2c2;</div><div class="line">        transition-property: background-color, transform;</div><div class="line">        transition-duration: .2s;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:before &#123;</div><div class="line">        transform: rotate(45deg);</div><div class="line">        transform-origin: 0 0;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    &amp;:after &#123;</div><div class="line">        transform: rotate(-45deg);</div><div class="line">        transform-origin: 0 5px;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>而 component 中該如何對應呢？</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Nav</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</div><div class="line">    render() &#123;</div><div class="line">        <span class="keyword">return</span> (</div><div class="line">        ...</div><div class="line">        &lt;div className=&#123;show ? style[<span class="string">"toggle_icon--active"</span>] : style.toggle_icon&#125;</div><div class="line">              onClick=&#123;<span class="keyword">this</span>.toggleIcon&#125;</div><div class="line">        /&gt;</div><div class="line">        ...</div><div class="line">        );</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>沒錯，就是這麼簡單而已。</p>
<h1 id="結論"><a href="#結論" class="headerlink" title="結論"></a>結論</h1><p>回頭看看重構後的 CSS，</p>
<p>你會發現我們已經不是昔日把所有東西都丟在越來越多層的 class 裡面，</p>
<p>而是變成扁平且一塊一塊的了，</p>
<p>如果要重構的話我們也能夠將重複的部分抽出來。</p>
<p>再來更棒的是除了 global 的地方，</p>
<p>我們不用再擔心全域命名污染的問題，</p>
<p>畢竟沒有 import 到的 class 就永遠不會發生作用啊！</p>
<p>如果有寫錯的地方或是建議，很歡迎留言告訴我。</p>
<p>我真的最討厭寫 CSS 了。</p>
<h2 id="參考連結："><a href="#參考連結：" class="headerlink" title="參考連結："></a>參考連結：</h2><ul>
<li><p><a href="https://github.com/css-modules/css-modules" target="_blank" rel="external">css module</a></p>
</li>
<li><p><a href="https://github.com/postcss/autoprefixer" target="_blank" rel="external">autoprefixer</a></p>
</li>
<li><p><a href="http://simonsmith.io/using-webpack-to-build-react-components-and-their-assets/" target="_blank" rel="external">Using webpack to build React components and their assets</a></p>
</li>
</ul>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;時至今日，我最討厭的東西就是亂七八糟的 CSS 還有 KMT，&lt;/p&gt;
&lt;p&gt;這兩個東西有一點很一致：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;不管我們再怎麼討厭它，&lt;br&gt;都還是得面對它、處理它。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&quot;先說結論：&quot;&gt;&lt;a h
    
    </summary>
    
    
      <category term="CSS Modules" scheme="http://abalone0204.github.com/tags/CSS-Modules/"/>
    
      <category term="PostCSS" scheme="http://abalone0204.github.com/tags/PostCSS/"/>
    
  </entry>
  
</feed>
