<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jallen Liao on Medium]]></title>
        <description><![CDATA[Stories by Jallen Liao on Medium]]></description>
        <link>https://medium.com/@lancelyao?source=rss-14665e59a01d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FqYpipwRxGt36CSy.jpg</url>
            <title>Stories by Jallen Liao on Medium</title>
            <link>https://medium.com/@lancelyao?source=rss-14665e59a01d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:56:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lancelyao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OAuth2]]></title>
            <link>https://medium.com/@lancelyao/oauth2-283c8436bbf1?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/283c8436bbf1</guid>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 21:40:10 GMT</pubDate>
            <atom:updated>2020-08-13T21:40:10.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>OAuth2 definition</h3><p><strong>OAuth</strong> is an <a href="https://en.wikipedia.org/wiki/Open_standard">open standard</a> for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.This mechanism is used by companies such as <a href="https://en.wikipedia.org/wiki/Amazon_(company)">Amazon</a>, <a href="https://en.wikipedia.org/wiki/Google">Google</a>, <a href="https://en.wikipedia.org/wiki/Facebook">Facebook</a>, <a href="https://en.wikipedia.org/wiki/Microsoft">Microsoft</a> and <a href="https://en.wikipedia.org/wiki/Twitter">Twitter</a> to permit the users to share information about their accounts with third party applications or websites.</p><p>Generally, OAuth provides clients a “secure delegated access” to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with HTTP, OAuth essentially allows <a href="https://en.wikipedia.org/wiki/Access_token">access tokens</a> to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server. (Wikipidia)</p><h3>Terminology:</h3><p><strong>Resource Owner</strong>: The owner of the source on the resouce server</p><p><strong>Client</strong>: The application that needs to access the source on the resource server</p><p><strong>Authorization Server</strong>: The server that does the authorization for the resource server before accessing resource on the resource server</p><p><strong>Resource Server</strong>: The server that holds the resource.</p><h3>Flows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*vSo9E799ZkFodrkNkn9qcg.png" /></figure><h4>Step 1</h4><p>Resource Owner wants the Client to access his resources on the Resource Server. (For example, Resource Owner wants the Client to use his email contacts on Gmail Server to send out words.)</p><h4>Step 2</h4><p>The Client redirects the broweser to the Authrization Server with Client_ID, Redirect_URI, Response Type and Scope.</p><p><strong>Client_ID</strong>: The Client needs to register on the Authorization Server before doing this flow, and there will be a Client_ID and Client_Secret assigned to the Client.</p><p><strong>Redirect_URI: </strong>URI used to redirect back after authenticating the Resource Owner (Step 5)<strong>.</strong></p><p><strong>Repsonse Type</strong>: Used to define the type of response from Authorization Server. It should be Code for this flow, the Client expects to receive an Authorization Code.</p><p><strong>Scope</strong>: The granual permissons (Actions that the Client wants to perfrom such as Read, Write, Delelte).</p><h4>Step3</h4><p>The Authorization Server verifies who you are and prompts a login.</p><h4>Step 4</h4><p>Then the Authorization Server presents a consent form based on the scopes requested by the Client after successful login. And the Resource Owner has the right to allow ro deny permission requested by the Client.</p><p><strong>Consent: </strong>The authorization server takes the Scopes that the Client is requesting and verify with the Resource Owner whether or not they want to give the Client the permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*0VfyrhapQxQ4EbeX6PIYjg.png" /><figcaption>Consent</figcaption></figure><h4>Step 5</h4><p>After granting the Resource Owner the permission, the Authorization Server redirects the browser back to the Client using the Redirect_URI along with a temporary Authorization Code.</p><h4>Step 6</h4><p>The Client then contact the Authorization Server directly. It does not use the Resource Owner’s browser. It securely sends its Client_ID, Client_Secret and Authorization Code</p><h4>Step 7</h4><p>The Authorization Server verifies the data and responds with an Access Token</p><h4>Step 8</h4><p>The Client can use the Access Token to access the contacts on the Resource Server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=283c8436bbf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object.create vs. New in javascript]]></title>
            <link>https://medium.com/@lancelyao/object-create-vs-new-in-javascript-8315327bdc5a?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8315327bdc5a</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 17:42:48 GMT</pubDate>
            <atom:updated>2020-07-08T17:42:48.326Z</atom:updated>
            <content:encoded><![CDATA[<p>Object.create() creates a new object, using an existing object as the prototype of the newly created object. This method is mainly used for implementing inheritance.</p><pre>Object.create(prototype[, propertiesObject])</pre><blockquote><strong>Parameters Used:</strong></blockquote><ul><li><strong>prototype :</strong> It is the prototype object from which a new object has to be created.</li><li><strong>propertiesObject :</strong> It is optional parameter. It specifies the enumerable properties to be added to the newly created object.</li></ul><blockquote><strong>Return Value:</strong><br>Object.create() returns a new object with the specified prototype object and properties.</blockquote><pre>// creating a function which will be the <br>//prototype for the object to be created later <br>function fruits() { <br> this.name = &#39;fruit 1&#39;; <br>}</pre><pre>// creating a function to whose object will <br>// inherit properties from the prototype <br>// using object.create() method <br>function<br>apple() { <br> fruits.call(this); <br>}</pre><pre>// creating an object of the apple function which <br>// will have properties of the prototype <br>// object i.e. fruits <br>apple.prototype = Object.create(fruits.prototype); <br>const app = new apple();</pre><pre>// Displaying the created object <br>console.log(app.name); // fruit 1</pre><pre>var fruit = Object.create(fruits);</pre><pre>console.log(fruit.name1); // undefined</pre><pre>var fruit1 = new fruits();<br>console.log(fruit1.name1); // fruit 1</pre><p>Object.create and constructor function new both create a new object and both set the __proto__ but in a different way. Object.create sets the __proto__ to be the one passed as the first parameter. The constructor function set the __proto__ to the type specified prototype. The major difference is that Object.Create returns the new object while the constructor function return the constructor of the object or the object.</p><p>This is due to the important difference that new actually runs constructor code, whereas Object.create will <strong>not</strong> execute the constructor code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8315327bdc5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array vs. ArrayList vs. List<> in C#]]></title>
            <link>https://medium.com/@lancelyao/array-vs-arraylist-vs-list-in-c-53a20234e7b3?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a20234e7b3</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 14:00:05 GMT</pubDate>
            <atom:updated>2020-07-07T14:00:05.547Z</atom:updated>
            <content:encoded><![CDATA[<p>An Array (System.Array) is fixed in size once it is allocated. You can&#39;t add items to it or remove items from it. Also, all the elements must be the same type. As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance. Also, System.Array supports multiple dimensions (i.e. it has a <a href="https://msdn.microsoft.com/en-us/library/system.array.rank(v=vs.110).aspx">Rank</a> property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).</p><pre>class TestArraysClass<br>{<br>    static void Main()<br>    {<br>        // Declare a single-dimensional array of 5 integers.<br>        int[] array1 = new int[5];</pre><pre>// Declare and set array element values.<br>        int[] array2 = new int[] { 1, 3, 5, 7, 9 };</pre><pre>// Alternative syntax.<br>        int[] array3 = { 1, 2, 3, 4, 5, 6 };</pre><pre>// Declare a two dimensional array.<br>        int[,] multiDimensionalArray1 = new int[2, 3];</pre><pre>// Declare and set array element values.<br>        int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };</pre><pre>// Declare a jagged array.<br>        int[][] jaggedArray = new int[6][];</pre><pre>// Set the values of the first array in the jagged array structure.<br>        jaggedArray[0] = new int[4] { 1, 2, 3, 4 };<br>    }<br>}</pre><p>An ArrayList is a flexible array which contains a list of objects. You can add and remove items from it and it automatically deals with allocating space. If you store value types in it, they are boxed and unboxed, which can be a bit inefficient. Also, it is not type-safe.</p><pre>using System;<br>using System.Collections;</pre><pre>namespace Test<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Creating an empty ArrayList <br>            ArrayList list = new ArrayList();</pre><pre>// Use Add() method <br>            // to Add elements  <br>            // in the list <br>            list.Add(&quot;Geeks&quot;);<br>            list.Add(&quot;for&quot;);<br>            list.Add(&quot;Geeks&quot;);<br>            list.Add(&quot;10&quot;);<br>            list.Add(&quot;20&quot;);</pre><pre>// Displaying the list <br>            Console.WriteLine(&quot;Elements of Original ArrayList: \n&quot;);</pre><pre>// Displaying the elements in ArrayList <br>            foreach (string str in list)<br>            {<br>                Console.WriteLine(str);<br>            }</pre><pre>// Creating another ArrayList <br>            ArrayList sec_list = new ArrayList();</pre><pre>// using Clone() Method: shalolow copy<br>            sec_list = (ArrayList)list.Clone();</pre><pre>// Displaying the Cloned ArrayList <br>            Console.WriteLine(&quot;\nElements of Cloned ArrayList: \n&quot;);</pre><pre>// Displaying the elements in ArrayList <br>            foreach (string str1 in sec_list)<br>            {<br>                Console.WriteLine(str1);<br>            }</pre><pre>string[] sec_list1 = new string[5];</pre><pre>list.CopyTo(sec_list1);</pre><pre>// Displaying the Copyed ArrayList <br>            Console.WriteLine(&quot;\nElements of Copyed ArrayList: \n&quot;);</pre><pre>// Displaying the elements in ArrayList <br>            foreach (string str1 in sec_list1)<br>            {<br>                Console.WriteLine(str1);<br>            }<br>        }<br>    }<br>}</pre><p>A List&lt;&gt; leverages generics; it is essentially a type-safe version of ArrayList. This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it&#39;ll generate a compile-time error.</p><pre>List&lt;string&gt; dinosaurs = new List&lt;string&gt;();</pre><pre>Console.WriteLine(&quot;\nCapacity: {0}&quot;, dinosaurs.Capacity);</pre><pre>dinosaurs.Add(&quot;Tyrannosaurus&quot;);<br>dinosaurs.Add(&quot;Amargasaurus&quot;);<br>dinosaurs.Add(&quot;Mamenchisaurus&quot;);<br>dinosaurs.Add(&quot;Deinonychus&quot;);<br>dinosaurs.Add(&quot;Compsognathus&quot;);<br>Console.WriteLine();<br>foreach(string dinosaur in dinosaurs)<br>{<br>    Console.WriteLine(dinosaur);<br>}</pre><pre>Console.WriteLine(&quot;\nCapacity: {0}&quot;, dinosaurs.Capacity);<br>Console.WriteLine(&quot;Count: {0}&quot;, dinosaurs.Count);</pre><pre>Console.WriteLine(&quot;\nContains(\&quot;Deinonychus\&quot;): {0}&quot;,<br>    dinosaurs.Contains(&quot;Deinonychus&quot;));</pre><pre>Console.WriteLine(&quot;\nInsert(2, \&quot;Compsognathus\&quot;)&quot;);<br>dinosaurs.Insert(2, &quot;Compsognathus&quot;);</pre><pre>Console.WriteLine();<br>foreach(string dinosaur in dinosaurs)<br>{<br>    Console.WriteLine(dinosaur);<br>}</pre><pre>// Shows accessing the list using the Item property.<br>Console.WriteLine(&quot;\ndinosaurs[3]: {0}&quot;, dinosaurs[3]);</pre><pre>Console.WriteLine(&quot;\nRemove(\&quot;Compsognathus\&quot;)&quot;);<br>dinosaurs.Remove(&quot;Compsognathus&quot;);</pre><pre>Console.WriteLine();<br>foreach(string dinosaur in dinosaurs)<br>{<br>    Console.WriteLine(dinosaur);<br>}</pre><pre>dinosaurs.TrimExcess();<br>Console.WriteLine(&quot;\nTrimExcess()&quot;);<br>Console.WriteLine(&quot;Capacity: {0}&quot;, dinosaurs.Capacity);<br>Console.WriteLine(&quot;Count: {0}&quot;, dinosaurs.Count);</pre><pre>dinosaurs.Clear();<br>Console.WriteLine(&quot;\nClear()&quot;);<br>Console.WriteLine(&quot;Capacity: {0}&quot;, dinosaurs.Capacity);<br>Console.WriteLine(&quot;Count: {0}&quot;, dinosaurs.Count);</pre><pre>/* This code example produces the following output:</pre><pre>Capacity: 0</pre><pre>Tyrannosaurus<br>Amargasaurus<br>Mamenchisaurus<br>Deinonychus<br>Compsognathus</pre><pre>Capacity: 8<br>Count: 5</pre><pre>Contains(&quot;Deinonychus&quot;): True</pre><pre>Insert(2, &quot;Compsognathus&quot;)</pre><pre>Tyrannosaurus<br>Amargasaurus<br>Compsognathus<br>Mamenchisaurus<br>Deinonychus<br>Compsognathus</pre><pre>dinosaurs[3]: Mamenchisaurus</pre><pre>Remove(&quot;Compsognathus&quot;)</pre><pre>Tyrannosaurus<br>Amargasaurus<br>Mamenchisaurus<br>Deinonychus<br>Compsognathus</pre><pre>TrimExcess()<br>Capacity: 5<br>Count: 5</pre><pre>Clear()<br>Capacity: 5<br>Count: 0<br> */</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a20234e7b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generator in ES6]]></title>
            <link>https://medium.com/@lancelyao/generator-in-es6-da8783f8a38c?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/da8783f8a38c</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 01:39:23 GMT</pubDate>
            <atom:updated>2020-07-08T19:12:26.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Regular functions return only one single value (or nothing), but generators can return (“yield”) multiple values, one after another, on-demand. They work great with iterables, allowing to create data streams with ease.</p><p>There are two atrributes that is different from regular function expression, one is the * sign and the other is yield expression.</p><pre>function* generateSequence() {<br>  yield 1;<br>  yield 2;<br>  return 3;<br>}</pre><pre>var seq = generateSequence();</pre><p>Above generator function generateSequence , it has two yield expressions, so this function has three states: hello, world and return statement.</p><p>Generator functions behave differently from regular ones. When such function is called, it does not run its code. Instead it returns iterator object. We need to use next function to move to the next state.</p><pre>hw.next()<br>// { value: 1, done: false }<br><br>hw.next()<br>// { value: 2, done: false }<br><br>hw.next()<br>// { value: 3, done: true }<br><br>hw.next()<br>// { value: undefined, done: true }</pre><p>In a word, calling generator function, it returns an iterator object, representing the pointer within the function. For each next call, it returns an object withvalue and done attributes. value stands for the value behind yield , done stands for whether the iteration ends.</p><h3>yield</h3><pre>function *gen() {<br>  yield 123 + 456;<br>}</pre><p>the expression 123 + 456 after yield will not be calculated immediately, only when the pointer ofnext method moves to this expression it executes.</p><p>return vs. yield</p><p>there only can be one return in generator function, but there can be several yield . And return is the end of any function, expressions after return will not be executed.</p><h3>next</h3><p>yield itself has no return value, or the return value is always undefined . next method can accept an argument that can be considered as the return value of last yield expression.</p><pre>function* f() {<br>  for(var i = 0; true; i++) {<br>    var reset = yield i;<br>    if(reset) { i = -1; }<br>  }<br>}<br><br>var g = f();<br><br>g.next() // { value: 0, done: false }<br>g.next() // { value: 1, done: false }<br>g.next(true) // { value: 0, done: false }</pre><p>For the first next call, i = 0 , so it return {value : 0, done: false} . For the second next call, there is no input for next call, so reset = undefined and returns {value : 1, done: false} . For the third next call, there is an input true , so reset = yield i =&gt; reset = true and i = -1 , at this time it returns {value: 0, done: false} .</p><pre>function* foo(x) {<br>  var y = 2 * (yield (x + 1));<br>  var z = yield (y / 3);<br>  return (x + y + z);<br>}<br><br>var a = foo(5);<br>a.next() // Object{value:6, done:false}<br>a.next() // Object{value:NaN, done:false}<br>a.next() // Object{value:NaN, done:true}<br><br>var b = foo(5);<br>b.next() // { value:6, done:false }<br>b.next(12) // { value:8, done:false }<br>b.next(13) // { value:42, done:true }</pre><p>Since the argument of next method is the return value of previous yield expression, the param for the first next call is invalid. V8 engine neglects the param input for the first next call. It is considered valid only starting from the second next call.</p><h3>try..catch</h3><p>async statements can be put in the try..catch block to catch potential error.</p><pre>async function main() {<br>  try {<br>    const val1 = await firstStep();<br>    const val2 = await secondStep(val1);<br>    const val3 = await thirdStep(val1, val2);<br><br>    console.log(&#39;Final: &#39;, val3);<br>  }<br>  catch (err) {<br>    console.error(err);<br>  }<br>}</pre><pre>const superagent = require(&#39;superagent&#39;);<br>const NUM_RETRIES = 3;<br><br>async function test() {<br>  let i;<br>  for (i = 0; i &lt; NUM_RETRIES; ++i) {<br>    try {<br>      await superagent.get(&#39;<a href="http://google.com/this-throws-an-error">http://google.com/this-throws-an-error</a>&#39;);<br>      break;<br>    } catch(err) {}<br>  }<br>  console.log(i); // 3<br>}<br><br>test();</pre><h3>for…of in generator</h3><pre>function* foo() {<br>  yield 1;<br>  yield 2;<br>  yield 3;<br>  yield 4;<br>  yield 5;<br>  return 6;<br>}<br><br>for (let v of foo()) {<br>  console.log(v);<br>}<br>// 1 2 3 4 5</pre><p>When next method returns an object with atrribute done: true , for...of will stop and the value of the object(done: true) will not be included.</p><pre>function* numbers () {<br>  yield 1<br>  yield 2<br>  return 3<br>  yield 4<br>}<br><br>// spread operator<br>[...numbers()] // [1, 2]<br><br>// Array.from method<br>Array.from(numbers()) // [1, 2]<br><br>// destructuring assignment<br>let [x, y] = numbers();<br>x // 1<br>y // 2<br><br>// for...of loop<br>for (let n of numbers()) {<br>  console.log(n)<br>}<br>// 1<br>// 2</pre><p>For destructing assignment, the value with return statement is also not assgined.</p><h3>Generator and State Machine</h3><p>Generator is the best data structure to implement state machine. Below clock function is a state machine</p><pre>var ticking = true;<br>var clock = function() {<br>  if (ticking)<br>    console.log(&#39;Tick!&#39;);<br>  else<br>    console.log(&#39;Tock!&#39;);<br>  ticking = !ticking<br>}</pre><p>There are two states in the clock function (Tick and Tock), every time it runs, it changes its state.</p><p>We can use generator to implement this.</p><pre>var clock = function* () {<br>  while (true) {<br>    console.log(&#39;Tick!&#39;);<br>    yield;<br>    console.log(&#39;Tock!&#39;);<br>    yield;<br>  }<br>};</pre><pre>for (let state of clock()) {<br>}</pre><p>In above code, we remove the global variable ticking , and the code is more concise and more secure(the state can not be changed illegally), conforms more to function programming. The reason why Generator does not need global varibale is that it contains the state information which is whether it is in the state of pause.</p><h3>How generator maintain the state ?</h3><p>Unlike the javascript runtime environment where there will be a gobal context. This context contains all the variables and objects. When the function executes, another function context will be created on top of this global context, which becomes the active context. There is a context stack (FILO) that store these function contexts. The last created function context will be executed first, then it will be removed from the context stack. Then the function context stored before it will be executed. This continues until all function contexts execute. Then the context stack becomes empty.</p><p>But for generator, the function context just temporarily exits the context stack when it reaches yield command. And all the variables and objects are frozen at the current state. When next executes, the function context will be joined to the context stack again, the frozen variables and objects resume their executions.</p><pre>function* gen() {<br>  yield 1;<br>  return 2;<br>}<br><br>let g = gen();<br><br>console.log(<br>  g.next().value,<br>  g.next().value,<br>);</pre><p>In above code, when g.next() executed the first time, the context of Generator function gen will exit the context stack, and the state of variables and objects will be frozen. When g.next() is executed the second time, the context of gen will join the context stack again and become the active context and resume execution.</p><h3>Use cases</h3><h4>Syncrhonization of asynchronous operation</h4><pre>function* loadUI() {<br>  showLoadingScreen();<br>  yield loadUIDataAsynchronously();<br>  hideLoadingScreen();<br>}<br>var loader = loadUI();<br>// Load UI<br>loader.next()<br><br>// Unload UI<br>loader.next()</pre><h4>Implement Iterator Interface</h4><pre>function* iterEntries(obj) {<br>  let keys = Object.keys(obj);<br>  for (let i=0; i &lt; keys.length; i++) {<br>    let key = keys[i];<br>    yield [key, obj[key]];<br>  }<br>}<br><br>let myObj = { foo: 3, bar: 7 };<br><br>for (let [key, value] of iterEntries(myObj)) {<br>  console.log(key, value);<br>}<br><br>// foo 3<br>// bar 7</pre><h4>Use as data structure</h4><pre>function* doStuff() {<br>  yield fs.readFile.bind(null, &#39;hello.txt&#39;);<br>  yield fs.readFile.bind(null, &#39;world.txt&#39;);<br>  yield fs.readFile.bind(null, &#39;and-such.txt&#39;);<br>}</pre><pre>for (task of doStuff()) {<br>  // task is a function, use it like a callback function<br>}</pre><p>Above implementation is equal to belove ES5 expression</p><pre>function doStuff() {<br>  return [<br>    fs.readFile.bind(null, &#39;hello.txt&#39;),<br>    fs.readFile.bind(null, &#39;world.txt&#39;),<br>    fs.readFile.bind(null, &#39;and-such.txt&#39;)<br>  ];<br>}</pre><p>Reference: <a href="https://es6.ruanyifeng.com/#docs/generator">https://es6.ruanyifeng.com/#docs/generator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da8783f8a38c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy in javascript]]></title>
            <link>https://medium.com/@lancelyao/proxy-in-javascript-d57a724b5ee6?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d57a724b5ee6</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 01:02:49 GMT</pubDate>
            <atom:updated>2020-07-06T01:04:33.403Z</atom:updated>
            <content:encoded><![CDATA[<p>The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for the object.</p><h3>get()</h3><p>get method can redefine the access of an atrribute, it accepts three params(target object, atrribute name and proxy instantiation).</p><pre>var person = {<br>  name: &quot;Sam&quot;<br>};<br><br>var proxy = new Proxy(person, {<br>  get: function(target, propKey) {<br>    if (propKey in target) {<br>      return target[propKey];<br>    } else {<br>      throw new ReferenceError(&quot;Prop name \&quot;&quot; + propKey + &quot;\&quot; does not exist.&quot;);<br>    }<br>  }<br>});<br><br>proxy.name // &quot;Sam&quot;<br>proxy.age // throw an error</pre><p>get method can be inherited.</p><pre>let proto = new Proxy({}, {<br>  get(target, propertyKey, receiver) {<br>    console.log(&#39;GET &#39; + propertyKey);<br>    return target[propertyKey];<br>  }<br>});<br><br>let obj = Object.create(proto); //The <strong>Object.create()</strong> method creates a new object, using an existing object as the prototype of the newly created object.<br>obj.foo // &quot;GET foo&quot;</pre><p>In above code, interception operation is defined on Prototype object, so this interception will be triggered when accessing the inherited attribute ofobj .</p><h3>set()</h3><p>set method can intercept an attribute’s assignment operation. It can accepts four arguments (target object, property name, property value, Proxy instantiation).</p><pre>let validator = {<br>  set: function(obj, prop, value) {<br>    if (prop === &#39;age&#39;) {<br>      if (!Number.isInteger(value)) {<br>        throw new TypeError(&#39;The age is not an integer&#39;);<br>      }<br>      if (value &gt; 200) {<br>        throw new RangeError(&#39;The age seems invalid&#39;);<br>      }<br>    }<br><br>    // for value meeting the requirment will be stored<br>    obj[prop] = value;<br>  }<br>};<br><br>let person = new Proxy({}, validator);<br><br>person.age = 100;<br><br>person.age // 100<br>person.age = &#39;young&#39; // error<br>person.age = 300 // error</pre><p>In above code, any value that does not meet the requirements will trigger an error.</p><p>Sometimes, we want to add inner properties with a underscore in an object, which means we don’t want these properties to be used outside. We can take advantage of get and set to achieve this.</p><pre>const handler = {<br>  get (target, key) {<br>    invariant(key, &#39;get&#39;);<br>    return target[key];<br>  ),<br>  set (target, key, value) {<br>    invariant(key, &#39;set&#39;);<br>    target[key] = value;<br>    return true;<br>  }<br>};</pre><pre>function invariant(key, action) {<br>  if (key[0] === &#39;_&#39;) {<br>    throw new Error(`Invalid attempt to $(action) private &quot;${key}&quot; property`);<br>  }<br>}</pre><pre>const target = {};<br>const proxy = new Proxy(target, handler);<br>proxy._prop<br>// Error: Invalid attempt to get private &quot;_prop&quot; property<br>proxy._prop = &#39;c&#39;<br>// Error: Invalid attempt to set private &quot;_prop&quot; property</pre><p>In above code, get and set operation of a property with “_” prefix will trigger error.</p><p>In strict mode, set must return turn , or it will cause error.</p><pre>&#39;use strict&#39;;<br>const handler = {<br>  set: function(obj, prop, value, receiver) {<br>    obj[prop] = receiver;<br>    // error since true must be returned<br>    return false;<br>  }<br>};<br>const proxy = new Proxy({}, handler);<br>proxy.foo = &#39;bar&#39;;<br>// TypeError: &#39;set&#39; on proxy: trap returned falsish for property &#39;foo&#39;</pre><h3>apply()</h3><p>apply method can intercept invocation, call and apply operation.</p><p>apply accepts three arguments (target object, context of the target object(this), argument array of target object).</p><pre>var handler = {<br>  apply (target, ctx, args) {<br>    return Reflect.apply(...arguments);<br>  }<br>};</pre><p>Example</p><pre>var target = function () { <br>  return &#39;I am the target&#39;; <br>};<br>var handler = {<br>  apply: function () {<br>    return &#39;I am the proxy&#39;;<br>  }<br>};<br><br>var p = new Proxy(target, handler);<br><br>p()<br>// &quot;I am the proxy&quot;</pre><p>In above code, p is the instantiation of Proxy. When p is called p() , it will be intercepted by apply method and returns a string.</p><p>Another example</p><pre>var twice = {<br>  apply (target, ctx, args) {<br>    return Reflect.apply(...arguments) * 2;<br>  }<br>};<br>function sum (left, right) {<br>  return left + right;<br>};<br>var proxy = new Proxy(sum, twice);<br>proxy(1, 2) // 6<br>proxy.call(null, 5, 6) // 22<br>proxy.apply(null, [7, 8]) // 30</pre><p>There are another 10 different interceptions. You can refer to <a href="https://es6.ruanyifeng.com/#docs/proxy">https://es6.ruanyifeng.com/#docs/proxy</a> .</p><h3>Use case</h3><p>Proxy object can intercept any property, so it can be used to implement web server.</p><pre>const service = createWebService(&#39;<a href="http://example.com/data">http://example.com/data</a>&#39;);<br><br>service.employees().then(json =&gt; {<br>  const employees = JSON.parse(json);<br>  // ···<br>});</pre><p>Above code creates a web server interface returning different kinds of data. Proxy can intercept any property, so we don’t need to write matching method for every data, just one Proxy is enough.</p><pre>function createWebService(baseUrl) {<br>  return new Proxy({}, {<br>    get(target, propKey, receiver) {<br>      return () =&gt; httpGet(baseUrl + &#39;/&#39; + propKey);<br>    }<br>  });<br>}</pre><p>And Proxy can be used to implement ORM layer for database.</p><p>Reference:<a href="https://es6.ruanyifeng.com/#docs/proxy">https://es6.ruanyifeng.com/#docs/proxy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57a724b5ee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterator in ES6]]></title>
            <link>https://medium.com/@lancelyao/iterator-in-es6-68a45f5f8fc6?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a45f5f8fc6</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 19:18:55 GMT</pubDate>
            <atom:updated>2020-07-05T19:19:12.334Z</atom:updated>
            <content:encoded><![CDATA[<h3>Iterator and for…of in ES6</h3><p>Iterator is an interface that offers uniform access mechanism for all collection data stuctures such as Array , Map and Set . Any data structure that has this Iterator interface can perform iteration action.</p><p>The three main function for Iterator :</p><ul><li>Provide uniform and easy-to-use interface</li><li>Put the member in the data structure in order</li><li>Creates new statement for...of iteration</li></ul><h4>The process of iteration:</h4><ul><li>Create a pointer object and points to the starting point of the current data structure</li><li>When first invoke the next method, it will points to the first member of the data structure</li><li>When invoke the next method second time, it will points to the second member</li><li>Continue to invoke the next method until it reaches the end of the data structure</li></ul><h4>Implement an iterator function</h4><pre>function makeIteration(array) {<br>  var nextIndex = 0;<br>  return {<br>    next: function() {<br>      return nextIndex &lt; array.length ?<br>        {value: array[nextIndex++], done : false}<br>        :<br>        {value: undefined, done: true};<br>    }<br>  };<br>}</pre><pre>var it = makeIterator([&#39;a&#39;, &#39;b&#39;]);<br>it.next(); // { value: &quot;a&quot;, done: false}<br>it.next(); // { value: &quot;b&quot;, done: false}<br>it.next(); // { value: undefined, done: true}</pre><p>In above code snippet, use next to access the next member until it reaches the end and returns {done: true}</p><h3>Default iterator interface</h3><p>When a data structure is deployed with Iterator interface, we can say this data structure is iterable. Specifically when a data structure has the attribute of Symbol.iterator , it is considered iterable. Symbol.iterator itself is a iterator function, it returns the iterator attribute of Symbol object.</p><pre>const obj = {<br>  [Symbol.iterator]: function() {<br>    return {<br>      next: function() {<br>        return {<br>          value: 1,<br>          done: true<br>        };<br>      }<br>    };<br>  }<br>}</pre><p>In above code, obj is iterable due to its Symbol.iterator attribute. When invoke this atrribute, it will returns a iterator object. This object has next method and can return the current member of the data structure and has value and done attributes.</p><p>Some data structures orginally have the Iterator interface, and can use for...of to iterate. For example:</p><ul><li>Array</li><li>Map</li><li>Set</li><li>String</li></ul><p>…</p><p>If an object wants to be iterated by for...of , it must deploy iterator function on the attribute of Symbol.iterator .</p><h4>Deploy iterator function on Symbol.iterator of a class</h4><pre>class RangeIterator {<br>  constructor(start, stop) {<br>    this.value = start;<br>    this.stop = stop;<br>  }</pre><pre>  [Symbol.iterator]() {return this;}</pre><pre>  next() {<br>    var value = this.value;<br>    if (value &lt; this.stop) {<br>      this.value++;<br>      return {value: value, done: false};<br>    } else {<br>      return {value: undefined, done: true};<br>    }<br>  }<br>}</pre><pre>function range(start, stop) {<br>  return new RangeIterator(start, stop);<br>}</pre><pre>for (var value of range(0, 3)) {<br>  console.log(value);   // 0,1,2<br>}</pre><p>Above is how to deploy Iterator interface on a class, Symbol.iterator corresponds to a function which returns current member of the iteration.</p><h4>Deploy iterator function on prototype chain of a class</h4><pre>function Obj(value) {<br>  this.value = value;<br>  this.next = null;<br>}</pre><pre>Obj.prototype[Symbol.iterator] = function() {<br>  var iterator = { next: next };</pre><pre>  var current = this;</pre><pre>  function next() {<br>    if (current) {<br>      var value = current.value;<br>      current = current.next;<br>      return { done: false, value: value};<br>    } else {<br>      return { done: true };<br>    }<br>  }<br>  return iterator;  // why need to return iterator<br>}</pre><pre>var one = new Obj(1);<br>var two = new Obj(2);<br>var three = new Obj(3);</pre><pre>one.next = two;<br>two.next = three;</pre><pre>for (var i of one) {<br>  console.log(i); // 1, 2, 3<br>}</pre><p>Above code first deploy Symbol.iterator method on the prototype chain of construction function, this function returns the iterator object.</p><h4>Add Iterator interaface to a object</h4><pre>let obc = {<br>  data: [&quot;hello&quot;, &quot;world&quot;],<br>  [Symbol.iterator]() {<br>    const self = this;<br>    let index = 0;<br>    return {<br>      next() {<br>        if (index &lt; self.data.length) {<br>          return {<br>            value: self.data[index++],<br>            done: false<br>          };<br>        } else {<br>          return {value: undefined, done: true};<br>        }<br>      }<br>    };<br>  }<br>}</pre><p>For objects similar to the array object(has index and length attribute) , you can just use the Symbol.iterator method of Array interface.</p><pre>let iterable = {<br>  0: &#39;a&#39;,<br>  1: &#39;b&#39;,<br>  2: &#39;c&#39;,<br>  length: 3,<br>  [Symbol.iterator]: Array.prototype[Symbol.iterator]<br>};</pre><pre>for (let item of iterable) {<br>  console.log(item);<br>}</pre><h3>Circumstance When invoking Iterator interface</h3><h4>Destructuring assignment</h4><p>When destructuring assignment with Array or Set, it calls the Symbol.iterator method by default.</p><pre>let set = new Set().add(&#39;a&#39;).add(&#39;b&#39;).add(&#39;c&#39;);</pre><pre>let [x,y] = set;<br>// x=&#39;a&#39;; y=&#39;b&#39;;</pre><pre>let [first, ...rest] = set;<br>// first=&#39;a&#39;; rest=[&#39;b&#39;,&#39;c&#39;];</pre><h4>Spread operator</h4><p>Spread operator(…) calls the default Iterator interface.</p><pre>let str = &#39;hello&#39;;<br>[...str] // [&#39;h&#39;,&#39;e&#39;,&#39;l&#39;,&#39;l&#39;,&#39;o&#39;]</pre><pre>let arr = [&#39;b&#39;, &#39;c&#39;];<br>[&#39;a&#39;, ...arr, &#39;d&#39;]<br>// [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]</pre><p>You can convert any data structure that has the Iterator interface to an array.</p><pre>let arr = [...iterable]</pre><h4>yield*</h4><p>yield* is followed by an iterable structure, it calls the Iterator interface of this structure.</p><pre>let generator = function* () {<br>  yield 1;<br>  yeild* [2,3,4];<br>  yeild 5;<br>};</pre><pre>var iterator = generator();</pre><pre>iterator.next() // { value: 1, done: false}<br>iterator.next() // { value: 2, done: false}<br>iterator.next() // { value: 3, done: false}<br>iterator.next() // { value: 4, done: false}<br>iterator.next() // { value: 5, done: false}<br>iterator.next() // { value: undefined, done: true}</pre><h4>other circumstances</h4><pre>for…of<br>Array.from()<br>Map(), Set(), WeakMap(), WeakSet()<br>Promise.all()<br>Promise.race()</pre><h3>Iterator intreface of String</h3><pre>var someString = &quot;hi&quot;;<br>typeof someString[Symbol.iterator] //function</pre><pre>var iterator = someString[Symbol.iterator]();</pre><pre>iterator.next() // { value: &quot;h&quot;, done: false }<br>iterator.next() // { value: &quot;i&quot;, done: false }<br>iterator.next() // { value: undefined, done: true }</pre><p>In above code, Symbol.iterator method returns an iterator object which can be used to call next method.</p><p>We can override the original Symbol.iterator method.</p><pre>var str = new String(&quot;hi&quot;);<br>[...str] // [&quot;h&quot;, &quot;i&quot;]</pre><pre>str[Symbol.iterator] = function() {<br>  return {<br>    next: function() {<br>      if (this._first) {<br>        this._first = false;<br>        return { value: &quot;bye&quot;, done: false};<br>      } else {<br>        return { done: true };<br>      }<br>    },<br>    _first: true<br>  };<em><br>}</em>;</pre><pre>[...str] // [&quot;bye&quot;]<br>str // &quot;hi&quot;</pre><h3>Generator function to implement Iterator Iterface</h3><p>The simplest way to implement Iterator interface is to use Generator function.</p><pre>let myIterable = {<br>  [Symbol.iterator]: function* () {<br>    yield 1;<br>    yield 2;<br>    yield 3;<br>  }<br>}<br>[...myIterable] // [1, 2, 3]</pre><pre>let obj = {<br>  * [Symbol.iterator]() {<br>    yield &#39;hello&#39;;<br>    yield &#39;world&#39;;<br>  }<br>};</pre><pre>for (let x of obj) {<br>  console.log(x);<br>}</pre><pre>// &quot;hello&quot;<br>// &quot;world&quot;</pre><h3>return(), throw() function of Iterator</h3><pre>function readLineSync(file) {<br>  return {<br>    [Symbol.iterator]() {<br>      return {<br>        next() {<br>          return { done: false };<br>        },<br>        return() {<br>          file.close();<br>          return { done: true };<br>        }<br>      };<br>    }<br>  };<br>}</pre><pre>// situation 1<br>for (let line of readLinesSync(fileName)) {<br>  console.log(line);<br>  break;<br>}<br><br>// situation 2<br>for (let line of readLinesSync(fileName)) {<br>  console.log(line);<br>  throw new Error();<br>}</pre><p>In situation 1, after the output of the first line, it calls return function, and close the file.</p><p>In situation 2, error throw will be after the return function invocation.</p><h3>for..in vs for…of</h3><pre>let arr = [3, 5, 7];<br>arr.foo = &#39;hello&#39;;<br><br>for (let i in arr) {<br>  console.log(i); // &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;foo&quot;<br>}<br><br>for (let i of arr) {<br>  console.log(i); //  &quot;3&quot;, &quot;5&quot;, &quot;7&quot;<br>}</pre><p>for...in only returns the key name of object, not the value of the key.</p><h3>forEach vs. for…of</h3><p>break can not be used in forEach, but can be used in for...of</p><pre>for (var n of fibonacci) {<br>  if (n &gt; 1000)<br>    break;<br>  console.log(n);<br>}</pre><p>Reference: <a href="https://es6.ruanyifeng.com/#docs/iterator">https://es6.ruanyifeng.com/#docs/iterator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a45f5f8fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce() vs ReduceRight() in Javascript]]></title>
            <link>https://medium.com/@lancelyao/reduce-vs-reduceright-in-javascript-e91ed23ef214?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91ed23ef214</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 14:06:31 GMT</pubDate>
            <atom:updated>2020-06-26T14:06:31.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reduce</h3><p>The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.</p><pre>Array.reduce(reducer, [, initialValue])</pre><p>The reduce method takes two arguments: a reducer callback function and an optional inital value.</p><p>The reduce method calls the reducer() function for every element in the array.</p><p>The reducer() function return a reuslt that is an accumulated value, and this value is provided as angurment for the next call of the reduce() function.</p><ul><li>The reducer function</li></ul><p>function reducer(accumulator, currentValue, index, array){}</p><p>accumulator</p><p>The accumulator accumulates callback’s return values. It is the accumulated value previously returned in the last invocation of the callback — or initialValue , if it was supplied</p><p>currentValue</p><p>The current element being processed in the array.</p><p>index | Optional</p><p>the index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, it starts from index 1.</p><p>array | Optional</p><p>The array reduce() was called upon.</p><ul><li>initialValue | Optional</li></ul><p>A value to use as the first argunment to the first call of the reducer() function.</p><p>Below is the example of reduce method.</p><pre>[2, 4, 6, 8, 10].reduce(function(accumulator, currentValue, index, array) {<br>  console.log(accumulator, currentValue, index);<br>  return accumulator + currentValue<br>}, 10)</pre><pre>10 2  0<br>12 4  1<br>16 6  2<br>22 8  3<br>30 10 4</pre><p>Since the initialValue is 10, so the index begins with 0, and the initial value of accumulator is 10. Below table illustrates the reduce process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*zSIIWUts3Rznu254U5PW9A.png" /></figure><h3>reduceRight()</h3><p>reduceRight() method works in the same way as reduce method, but in the opposite diretion.</p><pre>[2, 4, 6, 8, 10].reduceRight(function(accumulator, currentValue, index, array) {<br>  console.log(accumulator, currentValue, index);<br>  return accumulator + currentValue<br>}, 10)</pre><pre>10 10 4<br>20 8  3<br>28 6  2<br>34 4  1<br>38 2  0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*5yCjoIy6IxQssDchlX0trw.png" /></figure><p>In conclusion, reduce and reduceRight method work in the same way exception the reduce direction is opposite.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91ed23ef214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton pattern in C#]]></title>
            <link>https://medium.com/@lancelyao/singleton-pattern-in-c-b2bc4b1e0532?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2bc4b1e0532</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 13:56:31 GMT</pubDate>
            <atom:updated>2020-06-20T14:00:06.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Singleton Pattern in C#</h3><p>The purpose of Singleton Pattern is to create only one common access to an object, which means the class can only have on instantiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*546cgD2MFxHPKib3FFAZGw.png" /><figcaption>Singleton Pattern Diagram</figcaption></figure><pre>namespace SingletonDemo<br>{<br>    public sealed class Singleton<br>    {<br>        private static int counter = 0;<br>        private static Singleton instance = null;<br>        public static Singleton GetInstance<br>        {<br>            get<br>            {<br>                if (instance == null)<br>                    instance = new Singleton();<br>                return instance;<br>            }<br>        }<br>        <br>        private Singleton()<br>        {<br>            counter++;<br>            Console.WriteLine(&quot;Counter Value &quot; + counter.ToString());<br>        }<br><br>        public void PrintDetails(string message)<br>        {<br>            Console.WriteLine(message);<br>        }<br>    }<br>}</pre><pre>namespace SingletonDemo<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            Singleton fromTeachaer = Singleton.GetInstance;<br>            fromTeachaer.PrintDetails(&quot;From Teacher&quot;);<br>            Singleton fromStudent = Singleton.GetInstance;<br>            fromStudent.PrintDetails(&quot;From Student&quot;);<br><br>            Console.ReadLine();<br>        }<br>    }<br>}</pre><pre>Counter Value 1<br>From Teacher<br>Counter Value 1<br>From Student</pre><ul><li><strong>Sealed </strong>ensures the class can not be inherited and object instantiation is restricted in the derived class.</li><li><strong>Private</strong> ensures the property and method can only be used within the class.</li><li><strong>Static</strong> ensures the static member belongs to the class itself rather than to a specific object.</li></ul><p>As now almost all machines have multicore-processors. This brings about the parallel programming where the execution of processes are carried out simultaneously, which means the code or function executed by each thread is independent. So above singleton pattern will break in below parallel tasks.</p><pre>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            Parallel.Invoke(<br>                () =&gt; PrintTeacherDetails(),<br>                () =&gt; PrintStudentdetails()<br>                );<br>            Console.ReadLine();<br>        }<br><br>        private static void PrintTeacherDetails()<br>        {<br>            Singleton fromTeacher = Singleton.GetInstance;<br>            fromTeacher.PrintDetails(&quot;From Teacher&quot;);<br>        }<br><br>        private static void PrintStudentdetails()<br>        {<br>            Singleton fromStudent = Singleton.GetInstance;<br>            fromStudent.PrintDetails(&quot;From Student&quot;);<br>        }<br>    }<br>}</pre><pre>Counter Value 2<br>From Student<br>Counter Value 1<br>From Teacher</pre><h3>Thread-safe Singleton Pattern</h3><p>So we need thread-safe singleton pattern for parallel tasks.We can use locks to control the threat race condition in a multithreaded environment. Locks can be used to synchronize the method, so only one thread can access it at any given point of time.</p><pre>Single checked lock</pre><pre>namespace SingletonDemo<br>{<br>    public sealed class Singleton<br>    {<br>        private static int counter = 0;<br>        private static readonly object Instancelock = new object();<br>        private Singleton()<br>        {<br>            counter++;<br>            Console.WriteLine(&quot;Counter Value &quot; + counter.ToString());<br>        }<br>        private static Singleton instance = null;<br>       <br>        public static Singleton GetInstance<br>        {<br>            get<br>            {<br>                lock (Instancelock)<br>                {<br>                    if (instance == null)<br>                    {<br>                        instance = new Singleton();<br>                    }<br>                    return instance;<br>                }<br>            }<br>        }<br>        <br>        public void PrintDetails(string message)<br>        {<br>            Console.WriteLine(message);<br>        }<br>    }<br>}</pre><p>But for every thread access of the code block, it needs to wait for the thread arrving before to end even when it just checks if the instance is exited. To solve this problem, we can use double checked locks , which only synchronize the process when instance is null.</p><h4>Double checked locks</h4><pre>namespace SingletonDemo<br>{<br>    public sealed class Singleton<br>    {<br>        private static int counter = 0;<br>        private static readonly object Instancelock = new object();<br>        private Singleton()<br>        {<br>            counter++;<br>            Console.WriteLine(&quot;Counter Value &quot; + counter.ToString());<br>        }<br>        private static Singleton instance = null;<br>       <br>        public static Singleton GetInstance<br>        {<br>            get<br>            {<br>                if (instance == null)<br>                {<br>                    lock (Instancelock)<br>                    {<br>                        if (instance == null)<br>                        {<br>                            instance = new Singleton();<br>                        }<br><br>                    }<br>                }<br>                return instance;<br>            }<br>        }<br><br>        public void PrintDetails(string message)<br>        {<br>            Console.WriteLine(message);<br>        }<br>    }<br>}</pre><p>And this will save time for Singleton Pattern in multithreaded environment.</p><pre>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            Parallel.Invoke(<br>                () =&gt; PrintTeacherDetails(),<br>                () =&gt; PrintStudentdetails()<br>                );<br>            Console.ReadLine();<br>        }<br><br>        private static void PrintTeacherDetails()<br>        {<br>            Singleton fromTeacher = Singleton.GetInstance;<br>            fromTeacher.PrintDetails(&quot;From Teacher&quot;);<br>        }<br><br>        private static void PrintStudentdetails()<br>        {<br>            Singleton fromStudent = Singleton.GetInstance;<br>            fromStudent.PrintDetails(&quot;From Student&quot;);<br>        }<br>    }<br>}</pre><pre>Counter Value 2<br>From Student<br>Counter Value 1<br>From Teacher</pre><h3>Senarios</h3><ul><li><strong>Service Proxies</strong>: invoking a Service API is an extensive operation in an application. The process that taking most of the time is creating the Service client in order to invoke the service API. If you create the Service proxy as Singleton then it will improve the performance of your application.</li><li><strong>Facades: </strong>applying<strong> </strong>Singleton to the Database connections can improve the performance of the application</li></ul><p>Reference: <a href="https://dotnettutorials.net/lesson/singleton-design-pattern/">https://dotnettutorials.net/lesson/singleton-design-pattern/</a></p><p>Reference:<a href="https://dotnettutorials.net/lesson/thread-safe-singleton-design-pattern/">https://dotnettutorials.net/lesson/thread-safe-singleton-design-pattern/</a></p><p>Reference:<a href="https://dotnettutorials.net/lesson/task-parallel-library-overview/">https://dotnettutorials.net/lesson/task-parallel-library-overview/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2bc4b1e0532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event delegation based on Bubbling]]></title>
            <link>https://medium.com/@lancelyao/event-delegation-based-on-bubbling-407cc2595403?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/407cc2595403</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 19:46:11 GMT</pubDate>
            <atom:updated>2020-06-20T12:50:17.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Event delegation — based on Bubbling</h3><p>If we have many similiar elements, we can assign a handler to the their common ancestor instead of assigning a handle to each of them. Then in the handler we can get event.target to see which element the event comes from.</p><p>To continue explanation of Eevent Delegation, we should first understand the underling principle behind it, which is the mechanism of capturing and bubbling.</p><h3>Bubbling</h3><blockquote>When an event happens on an element, it first runs the hanlders on it, then on its parent, then all the way up to other ancestors.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fembed%2Fpreview%2FQWyNGLE%3Fheight%3D600%26slug-hash%3DQWyNGLE%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fpen%2FQWyNGLE&amp;image=https%3A%2F%2Fassets.codepen.io%2F4627291%2Finternal%2Fscreenshots%2Fpens%2FQWyNGLE.default.png%3Fformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D400%26amp%3Bquality%3D75%26amp%3Bv%3D1%26amp%3Bversion%3D1591895423%26amp%3Bwidth%3D700&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d4a5df5383049a7d5727bf688e2040c/href">https://medium.com/media/5d4a5df5383049a7d5727bf688e2040c/href</a></iframe><ul><li>As shown above, “click” on the most inner &lt;p&gt;(Tier 3) element will trigger the event sequencially from Tier3 -&gt; Tier2 -&gt; Tier1.</li><li>And we can see that the target element is P from the Tier3 caught by using event.target in Tier1’s handler.</li></ul><p>Almost all events bubbles, focus event is an exception and there are unmentioned others.</p><h4>Stop bubbling</h4><p>We can use event.stopPropgagation() to stop the event bubbling. Otherwise, a bubbling event will go from the target element traight up to &lt;html&gt;, then document and some events even reach window .</p><p>If there are multiple event handlers on a single element, you need to use event.stopImmediatePropagation() to stop them all.event.stopPropgagation() can only stop one.</p><p><strong>Caveat</strong>: no need to stop bubbling if there is no explicit demand. It can cause problems later on. For example, if you later decide to catch clicks on the whole window to track users’ behavior, we might loose the data of the element that is prevented from bubbling.</p><h3>Capturing</h3><p>As oppsed to bubbling which goes straight up till the &lt;html&gt; or window, capturing goes down from top down. In below example, the capturing process is added along with bubbling process. When an element is clicked, there are capturing events triggered beginning from &lt;html&gt;, then reaching the target element, then bubbling up from the target element back to the &lt;html&gt;.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fembed%2Fpreview%2FXWXdpzv%3Fheight%3D600%26slug-hash%3DXWXdpzv%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fpen%2FXWXdpzv&amp;image=https%3A%2F%2Fassets.codepen.io%2F4627291%2Finternal%2Fscreenshots%2Fpens%2FXWXdpzv.default.png%3Fformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D400%26amp%3Bquality%3D75%26amp%3Bv%3D1%26amp%3Bversion%3D1591902311%26amp%3Bwidth%3D700&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/339f97c06e6c2ea2e1a5f37e99ab057e/href">https://medium.com/media/339f97c06e6c2ea2e1a5f37e99ab057e/href</a></iframe><ul><li>We add ele.addEventListener(&quot;click&quot;, e =&gt; alert(`Capturing ${ele.tagName}`), true) (is equal to `elem.addEventListener(..., {capture: true}))to tract capturing process.</li><li>When we click on the P element (Tire 3), we can see it goes from top &lt;html&gt; straight to the target element P (HTML -&gt; BODY -&gt; DIV -&gt; DIV -&gt; P). (<strong>Capturing</strong>)</li><li>When it reaches the target element (P), then it goes straight up from the target element to &lt;html&gt;(P -&gt; DIV -&gt; DIV -&gt; HTML). (<strong>Bubbling</strong>)</li></ul><p>When we use addEventListener(..., {capture: true}) to add event listener, we should also use removeEventListener(...,{capture: true}) to remove event listener.</p><h3>Bubble-based Event Delegation</h3><p>Based on capturing and bubbling principle, event delegation utilizes the bubbling to add the same handling for many similiar elements.</p><p>Below example shows how to use the event delegation to trigger specific control action based on the target element. It uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset">dataset</a> to identify the target element.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fembed%2Fpreview%2FJjGXWbJ%3Fheight%3D600%26slug-hash%3DJjGXWbJ%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Flancelyao%2Fpen%2FJjGXWbJ&amp;image=https%3A%2F%2Fassets.codepen.io%2F4627291%2Finternal%2Fscreenshots%2Fpens%2FJjGXWbJ.default.png%3Fformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D400%26amp%3Bquality%3D75%26amp%3Bv%3D1%26amp%3Bversion%3D1591904519%26amp%3Bwidth%3D700&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ecad7eabdeb8d950e35bcf202570c5/href">https://medium.com/media/59ecad7eabdeb8d950e35bcf202570c5/href</a></iframe><pre>&lt;div id=&quot;control&quot;&gt;<br>  &lt;button data-action=&quot;start&quot;&gt;Start&lt;/button&gt;<br>  &lt;button data-action=&quot;stop&quot;&gt;Stop&lt;/button&gt;<br>  &lt;button data-action=&quot;pause&quot;&gt;Pause&lt;/button&gt;<br>&lt;/div&gt;</pre><p>We only attach onclick event on the div element which is the common ancestor of three buttons. When click action is applied on any one button, the click event will bubble up to the div element, then below event hanlder of div element will handle the click event based on the source of the clicked element.</p><pre>class Control {<br>    constructor(control) {<br>      this._control = control;<br>      control.onclick = this.onClick.bind(this); // (*)<br>    }<br><br>    start() {<br>      alert(&#39;start!&#39;);<br>    }<br><br>    stop() {<br>      alert(&#39;stop!&#39;);<br>    }<br><br>    pause() {<br>      alert(&#39;pause!&#39;);<br>    }<br><br>    onClick(event) {<br>      let action = event.target.dataset.action;<br>      if (action) {<br>        this[action]();<br>      }<br>    };<br>  }<br><br>  new Control(control);</pre><p>Normally the usage of Event Delegation follows below steps:</p><ul><li>Put a single handler on the container</li><li>In the handler, check the source element event.target</li><li>If the event happened inside an element that interests us, then handle the event.</li></ul><h4>Benefits</h4><ul><li>Better code management and save memory: no need to add handlers for each element, and can add and remove mass elements at the same time</li><li>Easy DOM modification: we can mass add/remove elements with innerHTML</li></ul><h4>Limitations</h4><ul><li>Some events may not bubble, such as focus .And stopPropagation() may be used.</li><li>More CPU load: as the hanlder on the ancestor runs with every event that its children element triggers. But usually this is negligible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407cc2595403" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“this” keyword deep dive in Javascript]]></title>
            <link>https://medium.com/@lancelyao/this-keyword-deep-dive-in-javascript-7580b9ad012a?source=rss-14665e59a01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7580b9ad012a</guid>
            <dc:creator><![CDATA[Jallen Liao]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 14:06:15 GMT</pubDate>
            <atom:updated>2020-06-13T14:22:35.417Z</atom:updated>
            <content:encoded><![CDATA[<p>Firstly, let’s look at the definition for “this” keyword.</p><blockquote><em>“</em><strong><em>this</em></strong><em>” keyword refers to the object it belongs to.</em></blockquote><h3>Different secanrios for this keyword usage</h3><p>Here are the representation of <strong>this</strong> keyword in different scenarios:</p><ul><li>In a method, <strong><em>this</em></strong> refers to <strong><em>the owner object.</em></strong></li></ul><pre>var person = {<br>  firstName: &quot;John&quot;,<br>  lastName : &quot;Doe&quot;,<br>  id     : 5566,<br>  fullName : function() {<br>    return this.firstName + &quot; &quot; + this.lastName;<br>  }<br>};</pre><pre>person.fullName(); // John Doe</pre><ul><li>Used alone, <strong><em>this refers to the global object.</em></strong></li></ul><pre>var x = this;<br>console.log(this); // [object Window]</pre><ul><li>In a function, <strong><em>this</em></strong> refers to the <strong><em>global object</em></strong>.</li></ul><pre>function myFunction() {<br>  cnosole.log(this);<br>}</pre><pre>myFunction(); //[object Window]</pre><ul><li>In a function, but in <strong><em>strict mode</em></strong>, <strong>this</strong> is <strong><em>undefined</em></strong>.</li></ul><pre>&quot;use strict&quot;;<br>function myFunction() {<br>  cnosole.log(this);<br>}</pre><pre>myFunction(); // undefined</pre><ul><li>In an event, <strong><em>this</em></strong> refers to the <strong><em>element</em></strong> that received the event.</li></ul><pre>&lt;button onclick=&quot;this.style.display=&#39;none&#39;&quot;&gt;<br>  Click to Remove Me!<br>&lt;/button&gt;</pre><pre>// When click on the button, the button will disappear since its display property is set to &quot;none&quot;;</pre><ul><li>Methods like <strong><em>call()</em></strong>, and <strong><em>apply() </em></strong>can refer <strong><em>this</em></strong> to <strong><em>any object</em></strong>.</li></ul><p>In the example below of <strong><em>call()</em></strong>, when calling person1.fullName with person2 as argument, <strong><em>this </em></strong>will refer to person2, even if it is a method of person1:</p><pre>var person1 = {<br>  fullName: function() {<br>    return this.firstName + &quot; &quot; + this.lastName;<br>  }<br>}<br>var person2 = {<br>  firstName:&quot;John&quot;,<br>  lastName: &quot;Doe&quot;,<br>}<br>person1.fullName.call(person2);  // Will return &quot;John Doe&quot;</pre><p>In the example below of <strong><em>apply(), </em></strong>the effect is the same.</p><pre>var person1 = {</pre><pre>  fullName: function() {</pre><pre>    return this.firstName + &quot; &quot; + this.lastName;</pre><pre>  }<br>}</pre><pre>var person2 = {</pre><pre>  firstName:&quot;John&quot;,</pre><pre>  lastName: &quot;Doe&quot;,</pre><pre>}</pre><pre>console.log(person1.fullName.apply(person2));  // John Doe</pre><h3>Discrepancy of this keyword for Regular function and Arrow function</h3><ul><li>With arrow functions there are no binding of <strong><em>this</em>.</strong> <strong><em>this</em></strong> keyword only represents the object that defined the arrow function.</li></ul><pre>var person = {<br>  firstName: &quot;John&quot;,<br>  lastName: &quot;Doe&quot;,<br>  myName: () =&gt; {<br>    return this.firstName + this.lastName; // undefined + undefined<br>  }<br>}</pre><pre>person.myName();</pre><ul><li>In regular functions<strong> </strong>the<strong> this </strong>keyword represents the object that called the function, which could be the window, the document, a button etc.</li></ul><pre>var person = {<br>  firstName: &quot;John&quot;,<br>  lastName: &quot;Doe&quot;,<br>  myName: function() {<br>    return this.firstName + this.lastName; // &quot;John&quot; + &quot;Doe&quot;<br>  }<br>}</pre><pre>person.myName();</pre><p>In a word, in regular function the context of this keyword will change according to the context where it is called, while in arrow function the context is bound to the origial context of definition.</p><h3>Binding in javascript with this keyword</h3><h4>Inexplicit binding</h4><pre>class Person {</pre><pre>  constructor() {</pre><pre>    this.firstName = &quot;John&quot;;</pre><pre>    this.lastName = &quot;Doe&quot;;</pre><pre>  }</pre><pre>  display() {</pre><pre>    return this.firstName + this.lastName;</pre><pre>  }</pre><pre>}</pre><pre>const person = new Person();<br>person.display(); // &quot;JoneDoe&quot;</pre><pre>const display = person.display;<br>display(); // Error: this is undefined</pre><p>When directly invoking the person.display method, this keyword is inexplicted bind to the person object.</p><p>But changing the context to the global environment by using const display = person.display , this keyword becomes undefined (<strong>Since the bodies of <em>class declarations</em> and <em>class expressions</em> are executed in </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode"><strong>strict mode</strong></a><strong>, which makes <em>this</em> keyword in global regular function becomes undefined.</strong>)</p><h4>Explicit binding</h4><p>Let’s explictly bind the display function to the object.</p><pre>class Person {</pre><pre>  constructor() {</pre><pre>    this.firstName = &quot;John&quot;;</pre><pre>    this.lastName = &quot;Doe&quot;;</pre><pre>  }</pre><pre>  display() {</pre><pre>    return this.firstName + this.lastName;</pre><pre>  }</pre><pre>}</pre><pre>const person = new Person();<br>const display = person.display.bind(person);<br>display(); // &quot;JohnDoe&quot;</pre><p>Now even though we assign the person.display to globally defined variable, this keyword is still binded to the person object.</p><p>In the last part, we discuss the difference between arrow function and regular function. Let’s see what’s the difference between them in terms of binding.</p><h4>Execption with arrow function</h4><p>With arrow function, this keyword is binded to the context of class where it is defined, so there is no need to explictly bind this keyword.</p><pre>class Person {</pre><pre>  constructor() {</pre><pre>    this.firstName = &quot;John&quot;;</pre><pre>    this.lastName = &quot;Doe&quot;;</pre><pre>  }</pre><pre>  display = () {</pre><pre>    return this.firstName + this.lastName;</pre><pre>  }</pre><pre>}</pre><pre>const person = new Person();</pre><pre>const display = person.display<br>display(); // &quot;JohnDoe&quot;</pre><p>Even though person.display is assigned to a variable defined in global context, its context stays the same as in person object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7580b9ad012a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>