<?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 Andrew Chung on Medium]]></title>
        <description><![CDATA[Stories by Andrew Chung on Medium]]></description>
        <link>https://medium.com/@achung3071?source=rss-b86b7bda2a74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sWRkw-mcsPPhRhQ5jtMIVg.jpeg</url>
            <title>Stories by Andrew Chung on Medium</title>
            <link>https://medium.com/@achung3071?source=rss-b86b7bda2a74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:44:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@achung3071/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[How to trade Korean stocks as a foreign investor]]></title>
            <link>https://medium.com/bridge-markets/how-to-trade-korean-stocks-as-a-foreign-investor-8694669997ee?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/8694669997ee</guid>
            <category><![CDATA[korea]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 18:52:29 GMT</pubDate>
            <atom:updated>2021-03-28T19:58:37.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to trade South Korean stocks as a foreign investor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*e7shSDrhGQfkiYyeX9zbHg.jpeg" /></figure><p>Samsung. SK Hynix. LG Electronics. Hyundai. These are some of the major companies that are listed on the Korean stock exchange (KRX). Unfortunately, there’s a few barriers to investing in this awesome market that prevent many retail investors from being able to buy these companies’ stocks. Instead, most US investors end up settling for the small subset of companies that are listed on the US market as an ADR or ETFs that are managed by firms.</p><p>That said, it is still possible to invest in the Korean stock market! 9,327 foreign retail investors had been registered with South Korea’s Financial Supervisory Service (FSS) by the end of 2011 — given that this figure is quite outdated, it’s very likely that this number has jumped significantly since then. This article summarizes the key points about registering as a foreign investor, taken mainly from this <a href="https://www.stxons.com/manage/FileDownload.aspx?FilePath=/isolation/files/default/201702/121210_Guide%20to%20Investing%20in%20Korea_Final%20version__.pdf&amp;oidFile=2107">Guide to Investing in Korea</a> as well as a few other references.</p><h3>1. Designate a local custodian bank.</h3><p>The first thing you need investing in KRX is to decide on a source of funds. Therefore, you should designate a local custodian bank in your country which provides custody, money transfer, and security settlement services. Notable custodian banks in the United States include Bank of New York Mellon, JPMorgan Chase, State Street Bank and Trust Co., and Citigroup.</p><h3>2. Designate a local agent (standing proxy).</h3><p>Foreign investors should appoint a local agent (also known as a standing proxy) in Korea to conduct trading processes on their behalf. The local agent can be the Korea Securities Depository (KSD), a foreign exchange bank, a dealer/broker, or a collective investment business entity. The Guide to Investing in Korea linked above also mentions that a “foreign custodian” can act as the local agent; it is thus unclear whether the local custodian bank mentioned in Step 1 can act as the local agent as well (please leave a comment on this post if you happen to know!).</p><p>Note that technically, a standing proxy is not <em>needed</em> — however, the only other ways to get further down the road in investing in Korea is to either (1) visit the Korean FSS in person or (2) appoint a personal agent (law firm, etc.) to conduct the required jobs for you. Because this article is targeted at the common individual who is looking to conduct all processes electronically through a financial institution, we strongly recommend that you go ahead and appoint a local agent or standing proxy.</p><p>It should be noted that you’ll probably need to fill out Standing Proxy Agreement / Contract of some sort. <a href="https://english.samsungpop.com/eng/account/tab_open1.pop">Samsung Securities</a> has a list of documents you need to submit to get started in investing with them. Also, most English website interfaces for the local agents are outdated, meaning you should try calling them — most local brokers in Seoul can assist you with the entire process outlined in this article and help you open an account with them.</p><h3>3. Complete and submit a FIRA Form.</h3><p>In order to invest in Korea as a foreigner, you need to have an Investment Registration Certificate (IRC). To get this, you need to fill out a Foreign Investment Registration Application (FIRA) and also send in supporting identifying documents (usually a copy of your passport) to the FSS. The application itself can be found <a href="http://eng.kofia.or.kr/files/eng/application.docx">here</a>. All documents that are sent in electronically (such as your passport copy) should also be notarized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzlUz7oYdmV1U44NaJ4vkw.png" /><figcaption>Diagram showing ways to apply for an IRC in Korea.</figcaption></figure><p>It should be noted that in the Guide to Investing in Korea, it says the FIRA may be filed electronically to the FSS through the local agent. The IRC is then issued back electronically. Thus, it is likely that the local agent will guide you through this process — make sure to contact them and get their help in obtaining an IRC.</p><p>The IRC you receive has a unique identification number. With that, your records will now be registered in the foreign investment register, and you will be able to legally trade securities.</p><h3>4. Open a trading account</h3><p>Using the IRC, you will be able to to open a trading account through a securities company that has obtained KRX membership. It seems that the KRX member with which you open a brokerage account can also be the local agent, such as in the case of Samsung Securities (again, please comment and let me know if there is any incorrect information.</p><p>The licensed KRX member institutions can be found at the <a href="http://eng.kofia.or.kr/members/m_31/regularMembers01.do?srchCate=4">following link.</a> See the diagram below for a high-level overview of how one can go about participating in the KRX market:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qne-lAWdEEk-8gwg4OogMA.png" /><figcaption>How to participate in KRX markets as a foreigner.</figcaption></figure><p>And voilà! You’re now able to trade on the Korean stock exchange.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8694669997ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bridge-markets/how-to-trade-korean-stocks-as-a-foreign-investor-8694669997ee">How to trade Korean stocks as a foreign investor</a> was originally published in <a href="https://medium.com/bridge-markets">Bridge Markets</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating timestamped video annotations with React refs]]></title>
            <link>https://javascript.plainenglish.io/creating-timestamped-video-annotations-with-react-refs-db0ee3e9a53d?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/db0ee3e9a53d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 02:33:59 GMT</pubDate>
            <atom:updated>2019-12-20T08:05:45.423Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using the React-Player module to create a video player that can interact with the UI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_0k2OPXIvufSjNmiItLnA.png" /><figcaption>An image of <strong>Vidplus</strong>, a web-based video annotation tool. Video (left) and annotations (right) are shown.</figcaption></figure><p>Recently, I worked with some team members to create a web-based video annotation tool called Vidplus. The tool helps users get as much as possible out of educational videos on YouTube, DailyMotion, Facebook, etc. by allowing them to write <em>timestamped annotations</em>. I was responsible for creating the annotations page — shown above — using React.</p><p>Initially, videos are loaded via URL on the home page. Users can then create annotations associated with the video’s timestamps by clicking the “Add Note” button or hitting Enter. When users click on an existing annotation’s timestamp, the video immediately jumps to that timestamp so users can see what part of the video the annotation refers to.</p><p>Normally, in order to create this kind of UI/UX, one would have to reference and use the API provided by the video sharing service the video belongs to (e.g. <a href="https://developers.google.com/youtube/iframe_api_reference">Youtube Player API for iFrame embeds</a>). Luckily, CookPete has released a package called <a href="https://www.npmjs.com/package/react-player">React-Player</a> on NPM that serves as a React component wrapper for multiple external video player APIs (Youtube, Facebook, etc.). This article will examine how we can use this package along with React refs in order to implement the features described above.</p><h4>What are React refs?</h4><p>Before diving into the specifics of the front-end code, it is important to have a clear understanding of what React refs are. Essentially, refs are Javascript references to DOM elements or React components that are rendered in a component. Here is how refs are normally used:</p><pre>import ReactPlayer from &quot;react-player&quot;;</pre><pre>class VideoPlayer extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.player = React.createRef();<br>  }</pre><pre>  render() {<br>    // Detailed options (props) omitted for readability.    <br>    return &lt;ReactPlayer<br>      ref={this.player}<br>      url={this.props.url}<br>    /&gt;<br>  }<br>}</pre><p>As seen above, we first create a React ref inside the VideoPlayer class component using the React.createRef() method. Then, the ref is made to reference the ReactPlayer React component inside the render() method. The actual video player component instance can be now be accessed by calling this.player.current.</p><p>Note: <a href="https://reactjs.org/docs/refs-and-the-dom.html">Don’t overuse refs</a>. While refs are needed here because the react-player module has instance methods that can only be accessed through refs, they encourage imperative modification of child elements (which conflicts with the immutability preferred by React).</p><h4>Using the ReactPlayer ref to implement interactive features</h4><p>The two methods that should be used on the ReactPlayer ref are as follows:</p><ol><li>getCurrentTime(): Gets the current time of the video in seconds.</li><li>seekTo(amount): Makes the video player jump to amount seconds.</li></ol><p>Using these two methods, we can make the rest of the UI directly interact with the video. In order to make the timestamped annotations behave as expected, the general flow for the remaining code should be:</p><ol><li>Use this.player.current.getCurrentTime() to periodically update the current time of the video in a shared state (such as in Redux).</li><li>When an annotation is added (either by clicking “Add Note” or hitting Enter), retrieve the current timestamp from the shared state and display it along with the annotation on the browser page.</li><li>When the timestamp for an existing annotation is clicked, update another property in the shared state (i.e., targetTimestamp) as the clicked timestamp.</li><li>Retrieve targetTimestamp from the shared state and use it in the seekTo method. Using this.player.current.seekTo(targetTimestamp) will make the video jump to the target timestamp.</li></ol><p>And that’s how you make videos interact with the UI using React refs and the React Player module from NPM!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db0ee3e9a53d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/creating-timestamped-video-annotations-with-react-refs-db0ee3e9a53d">Creating timestamped video annotations with React refs</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I took a semester off to enroll in a software engineering bootcamp. Here’s why you should too.]]></title>
            <link>https://medium.com/quick-code/i-took-a-semester-off-to-enroll-in-a-software-engineering-bootcamp-heres-why-you-should-too-2c3f7310e008?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c3f7310e008</guid>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 00:14:53 GMT</pubDate>
            <atom:updated>2019-12-21T16:17:27.901Z</atom:updated>
            <content:encoded><![CDATA[<h4>About my experience at a web development bootcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-npQwFF8QrEm5ciYEEJHQ.jpeg" /><figcaption>Me (left) and my fellow 4-week project teammates: Kyungju Shim, Haekyoung Jung, Jongwoo Park</figcaption></figure><h4>My journey to a software engineering bootcamp</h4><p>In my first year of university, I took two computer science courses in Racket and C++. As I learned the basics of CS in these classes, I slowly fell in love with programming. I soon realized I wanted to explore the world of coding, beyond what I was simply doing in class. As a result, I ended up dabbling in several online courses and working as a research intern for a computational lab on campus, where I filtered large datasets in Python.</p><p>Then summer break came, and I was faced with a dilemma. Up until then, I had only coded to complete small tasks, whether it be class assignments or my duties as a research intern. I needed to have a bigger project under my belt — something similar to what actual industry developers work on. The question was, how would I learn the skills to create something like this?</p><p>After much contemplation and doing some research online, I decided to take my first semester of sophomore year off and enroll in a web development bootcamp near my house in Korea. The bootcamp was a six-month long program that taught all the skills necessary to become a successful entry-level developer. I was blown away by the quality of projects completed by past students, and figured the bootcamp would serve as an opportunity to learn practical industry skills not taught in school.</p><h4>The bootcamp experience</h4><p>During the summer, I participated in the “Pre Course” section of the bootcamp: a part-time, 10-week course in basic Javascript, HTML, CSS, and Git / Github. Learning how to manipulate the DOM with vanilla JS was a particularly empowering experience — I finally had the ability to make my ideas come to life in the browser. I applied these skills to my summer internship in machine learning, creating two client-side applications for training the company’s Sagemaker and Tensorflow ML models.</p><p>After successfully completing the Pre Course, I was prepared to take the next step: the Immersive Course. For 11 hours a day, I would learn countless topics in web development: classes, data structures, time and space complexity, algorithms, AJAX, React, Redux, Node.js, Express, authentication techniques, SQL and NoSQL database management systems. Students were also required to complete a small mini-project in pairs for each topic learned, all over the course of five weeks. It was a mentally and physically draining experience, but well worth the struggle — by the end of five weeks, I had all the knowledge needed to begin the team project stage.</p><p>For the first two-week project, I proposed an idea for a web-based video annotation tool called Vidplus. By working on the front-end for this project, I learned more about prototyping user interfaces, making the most out of React lifecycle methods, and patterns for state management with API requests using Redux and Redux-Saga.</p><p>Then came the final four-week project. For this project, our team decided to create a publishing platform for book curations and reviews called Booktogether. I was the only back-end developer on our team, which allowed me to explore a wider range of options and technologies such as database servers in the cloud (MongoDB Atlas) and open-source search engines (Elasticsearch).</p><p>Working as the only back-end team member, of course, did not mean I was exempt from collaboration. Our team followed the Agile Scrum methodology, which tasked us with daily stand-up meetings and code reviews. During these meetings, I communicated the details of the REST API documentation that I had written and made suggestions to improve the quality of back- and front-end code so that we would end up with a more robust application.</p><h4>My growth as a developer</h4><p>When I first signed up for the bootcamp, I thought it would just be a way for me to take my coding skills to the next level. It was simply a method through which I would be able to gain industry-level experience in programming and excel in my studies as a result.</p><p>However, the actual benefits that I got out of the bootcamp exceeded my expectations by a mile. Surely, the bootcamp enhanced my coding skills and even made me eligible to take a CS project course a year early, but that was only part of what I gained from the experience.</p><p>The true benefits of the bootcamp came in the intangibles—by the end of the bootcamp, I was not just a <em>coder</em>, but an actual <em>developer</em>. Using the knowledge I had gained from the first five weeks, I was able to quickly find and integrate unfamiliar modules into the team projects that I was a part of. This experience gave me the confidence that I could learn any programming skill I wanted, whether it be a new framework or even a new language.</p><p>Additionally, participating in various pair programming activities and Agile Scrum sprints taught me how to effectively communicate the ideas in my code to other people. Now, I think it’s safe to say that my soft skills as a developer are much better than what they were when I first enrolled in the coding bootcamp. I am also confident that these skills will come in handy when I am faced with a collaborative task in my future workplace.</p><h4>Making the decision to enroll</h4><p>The decision to enroll in any software engineering bootcamp — whether it be web development, machine learning, data science — is a huge commitment. While bootcamps may cost less than a semester at university, they are not a small financial investment by any means. You must also be prepared to give up a comfortable everyday life, as you’ll be spending almost all of your time (apart from meals) in front of a computer screen.</p><p>Speaking from experience, however, I will say this: if you’re willing to put in the time and effort to transform yourself into a better software engineer, don’t hesitate and just go for it! No matter how tough the bootcamp is, as long as you keep up your determination and diligence, you <em>will </em>succeed. Don’t hesitate to ask your fellow peers and program engineers/coordinators for help. Ultimately, when it’s all said and done, you’ll realize just how much of a better developer you’ve become.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c3f7310e008" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quick-code/i-took-a-semester-off-to-enroll-in-a-software-engineering-bootcamp-heres-why-you-should-too-2c3f7310e008">I took a semester off to enroll in a software engineering bootcamp. Here’s why you should too.</a> was originally published in <a href="https://medium.com/quick-code">Quick Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I automatically deployed Typescript to Elastic Beanstalk to speed up server-side development]]></title>
            <link>https://medium.com/quick-code/how-i-automatically-deployed-typescript-to-elastic-beanstalk-to-speed-up-server-development-22b89870e159?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b89870e159</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[elastic-beanstalk]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 22:15:23 GMT</pubDate>
            <atom:updated>2019-12-21T16:17:11.979Z</atom:updated>
            <content:encoded><![CDATA[<h4>Speed up your development process by auto-deploying Typescript code to EB!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZXqbGLfJtKixd4TRMA1Gg.gif" /><figcaption>A demo of <strong>Booktogether</strong>, an online publishing platform that I created the back-end for.</figcaption></figure><p>For my most recent team project <a href="https://booktogether.org/">Booktogether </a>— an online publishing platform in Korean for book curations and reviews — I was responsible for server-side development using Typescript and Express, as well as deployment using AWS Elastic Beanstalk.</p><p>As I soon found out, manual deployment to EB was a tedious process. I was constantly compiling Typescript code to Javascript, compressing all the files into a .zip file, and uploading the compressed file to AWS.</p><p>That’s when I thought to myself, “is there any way I can speed up deployment, so I can just focus on writing working code?” After doing some digging online, I found this <a href="https://www.youtube.com/watch?v=VO3tGUFQRKw">walkthrough</a> by Aaron White that helped me set up AWS CodePipeline to send my code straight from Github to EB.</p><h4>Side Note: A Common Error</h4><p>Although I won’t go through configuration details of CodePipeline too deeply in this article, I would like to specify a problem that I encountered while setting up this auto-deployment system. When I originally pushed the server-side code (along with a <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/sample-elastic-beanstalk.html#sample-elastic-beanstalk-codepipeline">build spec file</a>) from Github to AWS, the EB console responded with the following error:</p><blockquote>[Instance: i-12345] Command failed on instance. Return code: 1 Output: (TRUNCATED)…/opt/elasticbeanstalk/containerfiles/ebnode.py”, line 180, in npm_install raise e subprocess.CalledProcessError (TRUNCATED)</blockquote><p>As I later realized, this error happened because of the npm install command that EB runs when code is deployed to the EC2 instance. Specifically, the installation of some packages trigger the node-gyp process, which is run by the default EC2 user.</p><p>The default user does not have permission to access some of the packages in the node_modules directory that npm install creates, which is why one needs to create a file called .npmrc in the project root and add the following:</p><pre># Forces node-gyp process to be run as root user, not ec2 default<br>unsafe-perm=true</pre><h4>Auto-deploying Typescript code to EB</h4><p>Now back to the heart of the matter. When code is deployed to a Node.js environment in Elastic Beanstalk, node app is automatically called in order to initialize the server. However, because Node.js is a Javascript runtime environment, the Typescript code that I had written for my server would not run by default. I needed to compile my Typescript code first.</p><p>In order to accomplish this without having to manually upload my code as a .zip file, I had two options. The first was to simply compile Typescript code on my local machine using a command like npm run build, and then upload both Javascript and Typescript to my Github repository. This option, however, had two main drawbacks:</p><ol><li>An extra step (executing npm run build) would be added to the deployment process</li><li>I would have to manage changes in both .js and .ts files in Github</li></ol><p>Given these issues, I resorted to another option — specifically, the use of the .ebextensions directory. Files in this directory are used for advanced custom configuration of an Elastic Beanstalk environment. .ebextensions files are written in YAML or JSON format, with a .config file extension.</p><p>The config file I used in this case configured EB in such a way that the instance would compile all Typescript code to Javascript right after running npm install. Referencing the following <a href="https://medium.com/@lhviet88/deploy-a-typescript-expressjs-into-elasticbeanstalk-nodejs-server-8381e00e7e52">article</a> on Typescript compilation using .ebextensions, I created a file called source_compile.config in the .ebextensions directory and included the following script:</p><pre># source_compile.config<br>container_commands:<br>  compile:<br>    command: &quot;./node_modules/.bin/tsc -p tsconfig.json&quot;<br>    env:<br>      PATH: /opt/elasticbeanstalk/node-install/node-v10.15.3-linuxT-x64/bin/</pre><p>The command tsc -p tsconfig.json tells EB to compile the Typescript project to Javascript given the configuration file tsconfig.json. If there is no outdir key specified in tsconfig.json, the compiled .js files will be located in the same locations as the corresponding .ts files.</p><p>Additionally, I needed to ensure the version of node specified in the PATH key was compatible with the node version used by my EB environment. If needed, one should change the node version (currently written as v10.15.3) and OS name used in the PATH key of the source_compile.config script above.</p><p>Having gone through all these steps, I once again merged changes into my main Github branch — and voilà! The server was up and running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jCi63xDMRfJOupPLLxY1Q.png" /><figcaption>Health shown as “Ok” after deploying a project with configuration files (buildspec.yml, .npmrc, .ebextensions)</figcaption></figure><p>Thus, by making use of an auto-deployment pipeline and .ebextensions, I let deployment take care of itself and was able to focus more on writing server-side code in Typescript. For a product or application that is widely in use, it would be smart to set up an a separate development server connected to this pipeline and additional CI/CD tools for rigorous testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b89870e159" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quick-code/how-i-automatically-deployed-typescript-to-elastic-beanstalk-to-speed-up-server-development-22b89870e159">How I automatically deployed Typescript to Elastic Beanstalk to speed up server-side development</a> was originally published in <a href="https://medium.com/quick-code">Quick Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2019 Fall Dev Blog: TIL]]></title>
            <link>https://medium.com/@achung3071/2019-fall-dev-blog-til-f42865d1416b?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42865d1416b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[bootcamp]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 17:30:34 GMT</pubDate>
            <atom:updated>2020-03-31T23:57:16.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>A collection of the concepts I learned over the course of participating in the Code States Immersive Bootcamp.</h4><blockquote>21 September 2019: Prototype</blockquote><ul><li>Learned about how a red-black binary tree corrects itself. (Partially) created a working red-black tree object in JavaScript using functional instantiation.</li><li>Came up with a more intuitive way of thinking about Object.create(proto). It is essentially the same as:</li></ul><pre>let obj = {};<br>obj.__proto__ = proto;</pre><ul><li>Investigated how inheritance and prototype chaining works outside of ES6 syntax with Object.create().</li><li>Learned about the two methods of resolving index conflicts in hash tables (separate chaining vs. open addressing) and created a hash table object with separate chaining using pseudoclassical instantiation.</li></ul><blockquote>23 September 2019: Subclassing</blockquote><ul><li>Learned about prototype chaining using both Object.create with pseudoclassical instantiation and the ES6 class/extends keywords.</li><li>Learned about calling the constructor from parent classes through the following syntax: <em>ParentClassName</em>.apply(this, arguments)</li><li>Realized that one has to reset the constructor when using the Object.create() method for inheritance, as shown below:</li></ul><pre>InheritedClass.prototype = Object.create(ParentClass);<br>InheritedClass.prototype.constructor = InheritedClass;</pre><blockquote>24 September 2019: CSS with Subclassing and OOP</blockquote><ul><li>Learned tricks for mimicking animation with CSS and setInterval or recursive setTimeout calls, such as:</li></ul><pre>// NOTE: &quot;this&quot; is a class instance whose property $node is rendered // on the HTML page.</pre><pre>// moving towards right side of page (contained in a setInterval)<br>this.$node.style.left = parseInt(this.$node.style.left) + 20 + &quot;px&quot;;</pre><pre>// blinking (also contained in a setInterval)<br>let style = this.$node.style;<br>style.display = style.display === &quot;none&quot; ? &quot;inline-block&quot; : &quot;none&quot;;</pre><ul><li>Learned about the background-image, background-size, and background-repeat style properties and how to manipulate them with DOM.</li><li>Was reminded to beware of the fact that “this” (and the overall execution context) does not change when using arrow functions.</li></ul><blockquote>25 September 2019: N-Rooks Problem</blockquote><ul><li>Learned about the basics of the N-Queens and N-Rooks problems, and worked on solving the latter. (N queens or rooks must be placed on an NxN chessboard so that none of them can directly attack each other.)</li><li>Learned that the Array.slice() method for copying an array does not work for deep copies. Thus, when copying a two-dimensional array, the one-dimensional arrays inside will still point to the same memory address.</li><li>Realized a workaround for deep copying an array using JSON methods (used to create a new “chessboard” represented by a 2D array).</li></ul><pre>// board.rows() is a 2d array representing a chessboard<br>let boardCopy = JSON.parse(JSON.stringify(board.rows()));</pre><blockquote>26 September 2019: N-Queens Problem</blockquote><ul><li>Learned about the concept of minor and major diagonals and how elements on them can be represented by a “diagonal index.”</li></ul><pre>_getFirstRowColumnIndexForMajorDiagonalOn: function(rowIndex, colIndex) {<br>  return colIndex - rowIndex; // index for major diagonal<br>},</pre><pre>_getFirstRowColumnIndexForMinorDiagonalOn: function(rowIndex, colIndex) {<br>  return colIndex + rowIndex; // index for minor diagonal<br>},</pre><ul><li>Learned the JSON.parse(JSON.stringify(<em>array</em>)) method for deep copying a multi-dimensional array is not super time-efficient, and that a 2D array can be copied more efficiently through the following:</li></ul><pre>// board.rows() is a 2d array representing a chessboard<br>let boardCopy = board.rows().map(function(value) {<br>  return value.slice();<br>});</pre><blockquote>27 September 2019: Basic Web Architecture</blockquote><ul><li>Familiarized myself with the syntax for making requests (GET and POST) via the fetch API in JavaScript.</li></ul><pre>// Example:<br>fetch(URL, {<br>  method: &#39;POST&#39;,<br>  body: JSON.stringify(message),<br>  headers: {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  }<br>}).then(...) // handle response here</pre><ul><li>Learned about the stateless and connectionless nature of HTTP requests, which are independent and thus do not remember previous requests made in a similar context.</li><li>Investigated the Blink Engine for rendering HTML/CSS/JavaScript as browser pixels in Google Chrome and its utilization of the browser’s V8 engine for compiling JavaScript.</li><li>Learned about the advantages of using dynamic AJAX requests over loading a new page every time the client receives data from the server, which many websites did back in the day.</li></ul><blockquote>28 September 2019: Browser Security</blockquote><ul><li>Learned the basics of cross-origin resource sharing (CORS) and how simple requests are sent in order to retrieve data from another server. Requests are allowed or rejected based on the other server’s CORS configuration (specified in Access-Control-Allow-Origin).</li><li>In addition, preflighted cross-site requests are sent before the real request if certain HTTP methods or headers are used. CORS uses this to ensure the receiving server is CORS-aware and knows how to handle the incoming request (so that its security is not breached when the real request is sent).</li><li>Also learned about XSS attacks and how &lt;script&gt; or other DOM-altering tags sent to a database can breach the security of a browser application. Gathered ideas about how to establish preventative measures, such as using regular expressions and .replace() for characters like &lt; and &gt;.</li></ul><blockquote>30 September 2019: Intro to React</blockquote><ul><li>Learned about the basics of the React library for front-end development. Familiarized myself with props and state, the lifecycle of a component, and the general top-down flow of data. (Here is the blog I wrote on props and state: <a href="https://medium.com/@andrewchung2022/using-a-grocery-list-to-understand-props-and-state-in-react-f86eefbcc132">https://medium.com/@andrewchung2022/using-a-grocery-list-to-understand-props-and-state-in-react-f86eefbcc132</a>)</li><li>Realized that you have to bind component methods to the specific component instance in the constructor if you want to use these methods as event handlers. Otherwise, the value of <em>this</em> becomes the specific HTML element that uses the handler function.</li></ul><pre>// Example from reactjs.org</pre><pre>class Toggle extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    // This binding is necessary<br>    this.handleClick = this.handleClick.bind(this);<br>  }</pre><pre>  // other methods (like handleClick) ...</pre><pre>  render() {<br>    return &lt;button onClick={this.handleClick}&gt;&lt;/button&gt;;<br>  }<br>}</pre><blockquote>01 October 2019: Lifting State Up</blockquote><ul><li>Learned how to work around the top-down data flow in React and bring about state changes in ancestor components. This can be done by sending down methods through props, as follows:</li></ul><pre>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = (<br>      x: null<br>    }<br>  }</pre><pre>  setX(value) { // state-changing method that will be sent down<br>    this.setState({<br>      x: value<br>    });<br>  }</pre><pre>  render() {<br>    return &lt;ChildItem change={this.setX.bind(this)}/&gt;<br>  }<br>}</pre><pre>// Now, this.props.change can be executed within ChildItem to<br>// change the state of App, which is its ancestor.</pre><ul><li>Got a refresher on my knowledge of throttle, which I used to ensure that clicking the search button multiple times in a row would only lead to one API call towards the Youtube V3 Data API.</li><li>Familiarized myself with the general way to modularize HTTP requests. The strategy is to send the HTTP request within a reusable function. That function should receive a callback that adequately deals with the response data, such as in the .then() block of a fetch() API call.</li></ul><blockquote>02 October 2019: Useful Methods in Stateful Components</blockquote><ul><li>Learned that API calls to receive initial data should generally be included in the componentDidMount() method. API calls are asynchronous, so calling it in componentWillMount() does not mean that the response data will be rendered on the first try. It makes more logical sense to render the DOM first before receiving the response data and adjusting it.</li><li>Learned that setState() generally works in an asynchronous manner and updates states without mutating its properties. This is necessary for reconciliation between the old and new virtual DOM.</li><li>The reason we use setState() and don’t modify state directly: for example, if we mutate an array in state, the only way React can tell if the new array is different (and if the DOM should be re-rendered) is by comparing individual elements. But with setState, we create an immutable array copy and can instantly tell if they differ through reference equality.</li></ul><blockquote>04 October 2019: React Router and getDerivedStateFromProps</blockquote><ul><li>Learned how to give different URLs to videos on my Youtube clone app using React Router. The basic syntax is as follows:</li></ul><pre>import { BrowserRouter as Router, Route } from &quot;react-router-dom&quot;;</pre><pre>class App extends React.Component {<br>  // Constructor and other methods...<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;Route path=&quot;/&quot; exact component={Home} /&gt;<br>        &lt;Route path=&quot;/:id&quot; component={VideoPlayer} /&gt;<br>        // Other stuff you want to render regardless of URL...<br>      &lt;/Router&gt;<br>    );<br>  }<br>}</pre><ul><li>In the example above, when the main server address is exactly provided, the Home component is rendered. If there is a video ID that follows, the corresponding video is rendered on the webpage instead of Home.</li><li>Learned that you can access dynamic parameters (such as “id” in the second &lt;Route&gt; tag above) through props.match.params — so in the VideoPlayer component, the id corresponding to the current video can be accessed through props.match.params.id.</li><li>Other tags such as &lt;Link&gt; from React Router is useful for SPAs because it does not lead to a new page (unlike &lt;a&gt;).</li><li>The lifecycle method <em>static</em> getDerivedStateFromProps(props, state) allows comparison between the most recent props and the state. It is called before every render(). The returned object is merged with this.state.</li></ul><blockquote>05 October 2019: To-do List React Solo Project</blockquote><ul><li>Learned how to use basic components from the <a href="https://ant.design/docs/react/introduce">Ant Design</a> React UI Library. Implemented components like Layout, Sider, Button, Search, Col, Input into the to-do list project that I am working on.</li><li>Worked through the process of building a project from scratch, from thinking about the layout as a whole to considering the relationship between different UI components.</li><li>With regards to JavaScript itself, learned that it is possible to replace all occurrences of a certain substring using .replace() and a RegExp with the g modifier (global match). The following code removes all whitespace characters, hyphens, and colons from a string:</li></ul><pre>&quot;hello-my-name-is: andrew&quot;.replace(/[\s-:]/g, &quot;&quot;);<br>// &quot;hellomynameisandrew&quot;</pre><blockquote>07 October 2019: Using the JSON-server module</blockquote><ul><li>Learned how to make use of a node module called json-server to create a very simple back-end for my todo-list app.</li><li>You can start a server that holds a json file by installing json-server and entering “json-server -p {PORT no.} {json file path}” in the terminal.</li><li>json-server provides an API that allows you to send different types of HTTP requests to the server and fetch/update data in the json file.</li></ul><pre>// example JSON file structure<br>{<br>  &quot;tasks&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Breakfast&quot;,<br>      &quot;status&quot;: &quot;incomplete&quot;,<br>      &quot;tags&quot;: [<br>        &quot;Food&quot;<br>      ],<br>      &quot;id&quot;: 1<br>    },<br>    {<br>      &quot;name&quot;: &quot;Morning Sprint&quot;,<br>      &quot;status&quot;: &quot;incomplete&quot;,<br>      &quot;tags&quot;: [<br>        &quot;Sprint&quot;<br>      ],<br>      &quot;id&quot;: 2<br>    }<br>  ]<br>}</pre><ul><li>To add a task to the “tasks” array in the JSON file, send a POST request to “http://localhost:{PORT no.}/tasks” with a task object in the body.</li><li>To update the “Breakfast” task, send a PUT request to “http://localhost:{PORT no.}/tasks/1”. The last part specifies the id of the task.</li></ul><blockquote>08 October 2019: Intro to Node.js</blockquote><ul><li>Learned how to create a simple server without Express using the built-in http module in Node.js.</li><li>Realized that the (request, response) objects that are used in http.createServer are instances of streams, which are instances of EventEmitters (and can thus listen to certain events with .on()).</li><li>The following shows how you would handle a string coming in from the request stream and send it back out:</li></ul><pre>// Assume request and response have been defined by createServer()<br>let body = [];<br>request<br>  .on(&quot;data&quot;, chunk =&gt; body.push(chunk))<br>  .on(&quot;end&quot;, () =&gt; {<br>   // Buffer.concat() joins all data buffer objects into one buffer<br>   body = Buffer.concat(body).toString(); // the incoming string<br>   response.writeHead(200, headers);<br>   response.end(INSERT RESPONSE DATA HERE);<br>  });</pre><ul><li>Learned about handling OPTIONS requests (likely preflight CORS requests) before another HTTP request (e.g., POST, PUT) occurs.</li></ul><pre>let headers = {<br>  &quot;access-control-allow-origin&quot;: &quot;*&quot;,<br>  &quot;access-control-allow-methods&quot;: &quot;GET, POST, PUT, DELETE, OPTIONS&quot;,<br>  &quot;access-control-allow-headers&quot;: &quot;content-type, accept&quot;,<br>  &quot;access-control-max-age&quot;: 10<br>};</pre><pre>// code inside http.createServer()<br>if (request.method === &quot;OPTIONS&quot;) {<br>  response.writeHead(204, headers); // Allow CORS<br>  response.end();<br>}</pre><blockquote>10 October 2019: Serving with local files</blockquote><ul><li>Learned how to serve static HTML files using the fs module. Note that the process below is similar for CSS and JS files (only the url and path to read from would be different, such as “/styles/styles.css).</li></ul><pre>// Example with index.html<br>if (request.url === &quot;/&quot; &amp;&amp; request.method === &quot;GET&quot;) {<br>  headers[&quot;Content-Type&quot;] = &quot;text/html&quot;;<br>  response.writeHead(200, headers);<br>  let stream = fs.createReadStream(<br>    path.resolve(__dirname, &quot;../client/index.html&quot;)<br>  );<br>  stream.pipe(response);<br>}</pre><ul><li>Note that .pipe() sends all information from the ReadableStream (pointing to index.html) to the response, which is a WritableStream.</li><li>Also was able to use the fs module to store client data in a JSON file. A simplified version of the code is as follows:</li></ul><pre>let storage = { results: [] }; // for storing data locally</pre><pre>// When receiving a GET request to the base URL<br>fs.readFile(__dirname + &quot;/posts.json&quot;, &quot;utf8&quot;, function(err, data) {<br>  storage.results = JSON.parse(data).results;<br>});</pre><pre>// When the API endpoint receives a GET request<br>response.writeHead(200, headers);<br>response.end(JSON.stringify(storage))</pre><pre>// When endpoint receives a POST request (assume body is defined)<br>storage.results.push(JSON.parse(body));<br>fs.writeFile(<br>  __dirname + &quot;/posts.json&quot;, // Write updated object to JSON file<br>  JSON.stringify(storage),<br>  function (err) {<br>    if (err) {<br>      console.error(err);<br>      response.writeHead(500, headers);<br>      response.end(&quot;Server error.&quot;);<br>    } else {<br>      response.writeHead(201, headers);<br>      response.end(body);<br>    }<br>  }<br>);</pre><blockquote>11 October 2019: Intro to Express</blockquote><ul><li>Learned the general syntax for Express and how it simplifies the conditional logic used in http.createServer.</li><li>Express middleware is essentially a “layer of software” that parses data from the request (and sends responses for invalid data) so that it is easier for the server to handle the request and send appropriate responses.</li><li>App-wide middleware is usually created through app.use(), although middleware can also be added to individual request types and URLs.</li></ul><pre>// Examples: Static File Serving and Body Parsing<br>app.use(express.static(path.resolve(__dirname, &quot;../client&quot;)));<br>app.use(express.json());</pre><ul><li>Express.static(<em>folder</em>) automatically sends an HTML file in <em>folder</em> to the browser if a GET request is sent to the url “/”. If the HTML refers to CSS and JS files in the folder, those are sent to the client too.</li><li>Express.json() allows for body parsing and gives the request object a property called body, which can be used when handling requests later.</li><li>Express routing takes care of all conditional logic, as the various methods on app correspond to the type of request that is being sent.</li></ul><pre>app.route(&quot;/classes/messages&quot;) // Requests to /classes/messsages<br>  // Handle GET requests by sending JSON-formatted storage object<br>  .get((req, res) =&gt; res.status(200).json(storage))<br>  // Handle POST requests by sending <br>  .post((req, res) =&gt; {<br>    req.body.id = uuid.v1(); // Give the message a unique id<br>    storage.results.push(req.body);<br>    fs.writeFile(<br>      __dirname + &quot;/posts.json&quot;,<br>      JSON.stringify(storage),<br>      err =&gt; err ? console.error(err) : null)<br>    res.status(201).json(req.body);<br>  });</pre><blockquote>12 October 2019: Promises</blockquote><ul><li>Got a refresher on how to return promises as a way of handling async operations. The following is an example using fs.readFile, in which the value of the resolved promise is the content in “filePath”.</li></ul><pre>const getDataFromFilePromise = filePath =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    fs.readFile(filePath, &quot;utf-8&quot;, (err, data) =&gt; {<br>      err ? reject(err) : resolve(data);<br>    });<br>  });<br>};</pre><ul><li>Learned that an asynchronous function that takes a callback with the parameters (err, data) can be changed into a promise-returning function with util.promisify in Node.</li><li>Learned of promise chaining: if a promise is returned in a .then() block, another .then() block can be added in order to handle the value of this promise upon resolution (i.e., multiple .then() blocks can be used).</li><li>Promise chaining can also be done with Promise.all(), which takes an array of promises and returns a single promise which resolves when all individual promises in the array have resolved. The return value upon resolution is an array holding the return values of the individual promises.</li></ul><blockquote>14 October 2019: async/await and other tools</blockquote><ul><li>Learned that preceding a promise with the await keyword allows for (a) the code within an async function to execute in a synchronous manner and (b) allows the resolved value of the promise to be stored in a variable.</li><li>The following is an example of an async function that is executed as a callback on a POST request in Express:</li></ul><pre>app.post(&#39;/&#39;, async (req, res) =&gt; {<br>  try {<br>    // writeSourceFile returns a promise<br>    await writeSourceFile(body);<br>    res.status(200).send(&#39;ok&#39;); // executes after promise resolves<br>  } catch (err) {<br>    res.status(500).json({<br>      status: &quot;error&quot;,<br>      err: err.toString()<br>    });<br>  }<br>});</pre><ul><li>Learned that the JSDOM module allows for the parsing of HTML inside a server (Node) environment.</li></ul><pre>const jsdom = require(&quot;jsdom&quot;);<br>const { JSDOM } = jsdom;<br>// After receiving an HTML string with an &quot;article&quot; tag<br>const dom = new JSDOM(html); // html is the html string<br>const content = dom.window.document.querySelector(&quot;article&quot;)<br>  .textContent; // manipulating the DOM<br>fs.writeFile(filename, content, err =&gt; console.error(err));</pre><blockquote>15 October 2019: SQL and mySQL Database</blockquote><ul><li>Learned the basic syntax for SQL (select, where, insert into, aliases, joins, etc.) and how these keywords can be used to query databases.</li><li>Learned the basics of schema and query design within relational databases, as well as general “rules of thumb” for how to structure one-to-many, many-to-one and many-to-many relationships between tables.</li><li>In general, figured out that it is good practice to reference primary keys from the “one” table inside a column in the “many” table. It is also good to create a new table connecting two tables in a many-to-many relationship.</li><li>Learned about the differences between inner, left, right and full joins and how they can each be used to combine tables in a schema together.</li><li>Interacted with mySQL server using clients like the mySQL monitor (both in the CLI and in batch mode with .sql files) and the TablePlus GUI.</li><li>Realized that the default database server upon creation is 127.0.0.1 (localhost), but it is also possible to interact with a remote database server.</li></ul><blockquote>16 October 2019: Node.js mySQL module and MVC</blockquote><ul><li>Encountered a “client does not support authentication protocol” error while trying to create a connection in Node. This is because the new authentication method in MySQL 8 (caching_sha2_password) is not supported by the node module. To solve this, I <a href="https://stackoverflow.com/questions/50093144/mysql-8-0-client-does-not-support-authentication-protocol-requested-by-server">downgraded mySQL</a> in the default CLI client to the regular native_password method.</li><li>Learned about SQL Injections, which is essentially XSS using SQL. This is possible because raw queries in Node are made using regular strings. ORM reduces the use of raw SQL, so can help prevent this. The following syntax also stops injections by safely escaping strings in the array</li></ul><pre>db.query(&quot;UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?&quot;,<br>[fooVal, barVal, bazVal, userId], // values passed to question marks<br>function (error, results, fields) { ... });</pre><ul><li>Learned about the <a href="https://medium.com/of-all-things-tech-progress/understanding-mvc-architecture-with-react-6cd38e91fefd">MVC design pattern</a>, where the controllers handle HTTP requests from the client and make corresponding calls to the models (which access the database) or views (e.g., React).</li></ul><blockquote>17 October 2019: Sequelize ORM</blockquote><ul><li>Learned the basic syntax for the Sequelize ORM, which allows us to edit a database schema and query it without having to use SQL strings. Using ORM tends to result in more intuitive and reusable code.</li><li>Sample code can be found <a href="https://gist.github.com/yun-sangho/ba7ab9b88211d1cea4ee199d69b58f6d">here</a>. As shown, Sequelize uses promises to handle asynchronous operations on the database.</li><li>Note that the .sync() operation creates tables in the DB corresponding to how they were defined in Sequelize. If an existing table should be overwritten, use {force: true} inside .sync().</li><li>.findAll() corresponds to SELECT, while .create() corresponds to INSERT INTO. Raw queries can also be made by calling .query() on the instance:</li></ul><pre>const sequelize = new Sequelize ({ ... });<br>sequelize.query(&quot;SELECT username, text, roomname FROM messages INNER JOIN users ON messages.user_id=users.id&quot;,<br>{ type: db.QueryTypes.SELECT });</pre><ul><li>Using ORM can be more difficult and slower when making complicated queries, such as multiple joins. After all, the ORM itself requires a database driver (such as mysql2) and translates to raw SQL.</li></ul><blockquote>18 October 2019: Authentication in Node</blockquote><ul><li>Learned about the basic session authorization process and how to create a back-end for this process using the express-session middleware.</li><li>When sending a cookie back to the client, the express-session middleware assigns the browser a unique session id in the cookie. This session id is used to later access a server-side session object corresponding to the user.</li><li>The session object can be used to save information unique to the client, such as whether they are logged in, their id, etc. This object can be edited by accessing the .session property of a request object in Express.</li><li>Also learned about hashing using the Crypto module in Node.js. Hashing is generally done so that even if the database is hijacked, it is possible to hide the true content within the database. Here is a general example:</li></ul><pre>const hashedPassword = crypto<br>  .createHmac(&quot;sha256&quot;, &quot;secret&quot;) // salt added via specific alg.<br>  .update(password)<br>  .digest(&quot;hex&quot;);</pre><ul><li>Learned about the concept of “salt”, which is an arbitrary value that is added during the hashing operation so that exposure of the hashing algorithm does not automatically lead to compromised data.</li></ul><blockquote>19 October 2019: Additional Authentication Techniques</blockquote><ul><li>Learned about <a href="https://www.npmjs.com/package/morgan">morgan</a>, which is a general logger for HTTP requests. Logger modules help with development on the server, and can even be used to debug <a href="https://www.npmjs.com/package/universal-react-logger">client-side errors</a> on the server.</li></ul><pre>// Simple example of setting up server logger:<br>var morgan = require(&quot;morgan&quot;);<br>var app = express();<br>app.set(&quot;port&quot;, 3000);<br>app.use(morgan(&quot;dev&quot;));<br>app.listen(app.get(&quot;port&quot;));</pre><ul><li>Learned how to use <a href="https://sequelize.org/master/manual/hooks.html">hooks</a> in Sequelize, which are essentially lifecycle methods that are called to handle data coming in and out of the database. This is useful when you want to store hashed values without having to call a hash function every time a row is stored or queried:</li></ul><pre>const users = sequelize.define(&quot;users&quot;, {<br>   email: DataTypes.STRING,<br>   password: DataTypes.STRING<br> },<br> {<br>   hooks: {<br>     beforeCreate: user =&gt; { // Hashing stored passwords<br>       user.password = hash(user.password);<br>     },<br>     beforeFind: query =&gt; {<br>       if (query.where.password) { // Hashing password query<br>         query.where.password = hash(query.where.password);<br>       }<br>     }<br>   }<br> });</pre><ul><li>Learned the basics of Joi, a module for input validation. This is especially useful for storing into databases when you want data inputs to follow constraints that cannot necessarily be specified in the table definition (e.g., password length before hashing).</li><li>Refactored my authentication code from using express-session to using the jsonwebtoken module. Using a JSON web token reduces server-side stress and increases scalability because session information is encrypted and stored client-side. If not well managed, this can also lead to less security.</li></ul><pre>// SIGN-IN: assume &quot;user&quot; is the corresponding user from the db<br>const token = jwt.sign({ _id: user.id }, &quot;secret&quot;);<br>// Sets token header, but is better to store w/in httpOnly cookie<br>res.set(&quot;auth-token&quot;, token)<br>  .status(200)<br>  .send({ id: user.id });</pre><pre>// GET INFO: get user information with token (from the request)<br>const userId = jwt.verify(token, &quot;secret&quot;)._id;<br>users.find({ // Sequelize ORM<br>  where: { id: userId }<br>}).then(user =&gt; {<br>  res.status(200).send(user);<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42865d1416b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Your First Web App Using AWS S3, EC2, and RDS]]></title>
            <link>https://medium.datadriveninvestor.com/deploy-your-first-web-app-using-aws-s3-ec2-and-rds-4dd165d77b4f?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dd165d77b4f</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[rds]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 16:51:17 GMT</pubDate>
            <atom:updated>2019-10-27T02:23:47.133Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to deployment via Amazon Web Services</h4><p>You’ve been developing this application for months, and now you finally want to deploy it. But how? It’s not like you can keep your computer up and running 24/7. We need a remote environment to host our service for us so that it can be accessed by anyone at any time.</p><p>Here’s where Amazon Web Services comes into play. With AWS, you get a place to store and serve your client-side files (S3), a virtual server that stays on as long as you need it to (EC2), and a full database management system in the cloud (RDS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9faxG9GLY5UrYZaDNcNMgg.png" /><figcaption>Basic deployment architecture using S3 (Client), EC2 (Server), RDS (Database).</figcaption></figure><p>Of course, there are a plethora of other services that AWS provides. In this post, however, I will focus on explaining the three services mentioned above. By the end, hopefully, you’ll have a better sense of how AWS can help you make your application available to the rest of the world.</p><p><a href="https://www.datadriveninvestor.com/2019/01/15/the-path-of-mobile-app-development-in-2019/">The Path of Mobile App Development in 2019 | Data Driven Investor</a></p><h4>1. Amazon S3 (Simple Storage Service)</h4><p>At its core, S3 is a service for storing any kind of data — literally anything. S3 buckets, which are containers for such data, provide automatic scaling (i.e., no fixed storage sizes). The files within these buckets can be delivered to clients at low latency levels, making S3 ideal for online services that require storage outside of a database environment.</p><p>All files in S3 are HTTP(s) enabled, which means that they can be accessed via URL. The public access configuration of these files can be set directly through an S3 bucket policy, allowing the bucket owner to control the identities that have access to the bucket.</p><p>S3 also allows static web hosting, which means client-side files (HTML, CSS, JS) can be served directly to a browser from an S3 bucket. If needed, such applications can easily be modified to make API calls to a virtual server, such as an EC2 instance.</p><h4>2. Amazon EC2 (Elastic Compute Cloud)</h4><p>Let’s say we set up a SPA using a static file hosting on S3. In order to make this application dynamic, it is also necessary to construct a back-end that can handle API requests from S3. This can be done through Amazon EC2, which allows for running virtual servers in the cloud.</p><p>EC2 provides users with computing environments — known as instances — based on operating systems like Linux, Ubuntu, Windows, etc. You can literally think of it as Amazon giving you one of the millions of computers it owns so that you can store and run your files on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*WhyPT3P1ZpI7s7kfwBAM0g.jpeg" /><figcaption>Imagine that you’re getting one of these computers to run your EC2 server on. Source: <a href="https://hipertextual.com/imagen-del-dia/data-center-facebook">Hipertextual</a></figcaption></figure><p>These instances can be accessed remotely via protocols like SSH and HTTP, allowing users to <a href="https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171">run server-side programs</a> in these virtual environments for extended periods of time. It is also possible to create and manage databases (e.g., MySQL, PostgreSQL) within an EC2 instance’s local environment.</p><h4>3. Amazon RDS (Relational Database Services)</h4><p>Amazon RDS allocates users EC2 instances developed specifically for database management. These database instances can be based on any of the following six relational database engines: MySQL, MariaDB, PostgreSQL, Oracle, SQL Server, and Aurora. You can create and manage databases on these instances, just as you would on your local machine.</p><p>Naturally, many first-time users will ask: why use RDS and pay extra money when you can manually create databases on an EC2 instance? The answer is that RDS automates difficult database management tasks, potentially saving users a lot of time and money.</p><p>For example, you can easily change the CPU, storage, and IOPS of a database instance, thus enhancing scalability. The service also automates backups and recovery. Placing a database instance in a Virtual Private Cloud (VPC) — a virtual data center — also provides added security, as no entity other than a designated EC2 server(s) can access the database.</p><p>To conclude, here are the steps you should follow to deploy using AWS:</p><p>1. Upload your client-side files to an S3 bucket and enable static file hosting. Make sure your bucket permissions are set correctly — otherwise, your files will remain private.</p><p>2. Move your server-side programs to an EC2 instance and make sure that your client-side code makes API calls to this instance’s IP address.</p><p>3. Create a database instance in RDS and ensure that your server-side code references a database within this database instance.</p><p>Now start your server, and voilà! You now have a working web application.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dd165d77b4f" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/deploy-your-first-web-app-using-aws-s3-ec2-and-rds-4dd165d77b4f">Deploy Your First Web App Using AWS S3, EC2, and RDS</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a Grocery List to Understand props and state in React]]></title>
            <link>https://javascript.plainenglish.io/using-a-grocery-list-to-understand-props-and-state-in-react-f86eefbcc132?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86eefbcc132</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 21:22:50 GMT</pubDate>
            <atom:updated>2019-10-01T20:00:33.224Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explaining the difference between mutable and immutable properties of dynamic React Components</h4><p>React is a front-end JavaScript library built on components. These components represent independent “units” of the user interface that can be reused with great ease. Unlike static HTML elements, React components can be defined so that they come with dynamic behavior already built in. The question is, how is this accomplished?</p><p>As an example, let’s try making a simple grocery list in React. We want to render a list of two grocery items — a cucumber and a kale — on an HTML web page. When you click on the item, a strikethrough line is drawn through it, telling you the item has been bought. The line can be removed by clicking on the item another time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*V_Bhl5iZdthdIcyzTCPdWA.png" /><figcaption>An example of the simple grocery list we wish to create using React.</figcaption></figure><p>This is the entire structure of the grocery list UI in JSX:</p><pre>&lt;GroceryList <em>items</em>={[&quot;Cucumber&quot;, &quot;Kale&quot;]} /&gt;</pre><p>Simple, right? This is the power of React — we can modularize a complex user interface written in HTML until the entire app is distilled down to a few (or in this case, one) general components.</p><p>The attribute <em>items</em> in the GroceryList component above is part of an object called <em>props</em>, which holds all the attributes of a component in JSX. In this case, props would look something like { items: [“Cucumber”, “Kale”] }.</p><p>Props is accessible in the definition for the GroceryList component as <em>this.props</em> (as props is an attribute of a GroceryList instance):</p><pre>import React <em>from</em> &quot;react&quot;;<br>import ReactDOM <em>from</em> &quot;react-dom&quot;;</pre><pre>class GroceryList extends React.Component {<br>  render() {<br>    return (<br>      &lt;ul&gt;<br>        {this.props.items.map((item, index) =&gt; (<br>          &lt;GroceryListItem item={item} key={index} /&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    );<br>  }<br>}</pre><p>GroceryList is rendered as an unordered list in HTML, with a GroceryListItem serving as each list element. Note that the JSX elements in the array returned from .map() are simply rendered in order.</p><p>Each GroceryListItem represents an item in this.props.items, which is the array [“Cucumber”, “Kale”]. The props object for each GroceryListItem has two properties (“item” and “key”).</p><p>Now, we just need to define the GroceryListItem component and give it the dynamic strikethrough behavior:</p><pre>class GroceryListItem extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      bought: false<br>    };<br>  }</pre><pre>  handleClick() {<br>    this.setState({<br>      bought: !this.state.bought<br>    });<br>  }</pre><pre>  render() {<br>    let style = {<br>      textDecoration: this.state.bought ? &quot;line-through&quot; : &quot;none&quot;,<br>    };<br>    return (<br>      &lt;li style={style} onClick={this.handleClick.bind(this)}&gt;<br>        {this.props.item}<br>      &lt;/li&gt;<br>    );<br>  }<br>}</pre><p>Whoa, hold up! What’s the meaning of <em>this.state</em> in the constructor?</p><p>State is another object that is an internal property of a React component. In the code above, this.state contains the property <em>bought</em>, which indicates whether or not we have bought that specific GroceryListItem. As seen in the render() method, if the item has been bought, we adjust the styling so that the textDecoration property is set to line-through.</p><p>The way we buy/un-buy items is through the onclick event handler. When we click the HTML li element corresponding to the GroceryListItem, state.bought changes to the opposite of its current value. Afterwards, the render() method re-renders the page because this.setState() has been called.</p><p>But then there’s the question: can’t we just add the bought property to props directly? In other words, couldn’t we have just written the following and edited this.props.bought instead?</p><pre>&lt;GroceryListItem item={item} key={index} bought=false /&gt;</pre><p>The answer is no, because of a general rule in the React library: <strong>props are read-only</strong>. The philosophy of React is that props, or the data passed from a parent component to a child component, should be immutable. Changing a prop could have detrimental side-effects, as it could be relied upon and altered by a component higher up in the UI hierarchy.</p><p>Using this example, let’s say that bought was indeed a property of this.props and we modified it using the onclick event handler. But then, if we added a method to GroceryList that caused the entire GroceryList to be re-rendered, the bought property of every GroceryListItem would change back to false — even if we did not explicitly un-buy them by re-clicking each one.</p><p>A state, on the other hand, is fully encapsulated. It is not accessible to components other than the one it is defined within, making it safe to dynamically edit. Thus, a stateful GroceryListItem prevents the strikethroughs from being removed by the GroceryList, which would not be able to access the state of a GroceryListItem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86eefbcc132" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-a-grocery-list-to-understand-props-and-state-in-react-f86eefbcc132">Using a Grocery List to Understand props and state in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Many Solutions Does the N-Queens Problem Have?]]></title>
            <link>https://medium.com/swlh/how-many-solutions-does-the-n-queens-problem-have-e8da5d45a34c?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8da5d45a34c</guid>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[n-queens]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 11:11:09 GMT</pubDate>
            <atom:updated>2019-10-22T00:16:37.669Z</atom:updated>
            <content:encoded><![CDATA[<h4>A walkthrough of a backtracking algorithm for solving the n-queens problem using JavaScript.</h4><h4>What is the n-queens problem?</h4><p>The n-queens problem was first presented as the “eight queens problem” by Max Bezzel in 1848. The puzzle asks that eight queens be placed on an 8×8 chessboard such that they are unable to attack each other. Over time, this problem developed into the more general n-queens problem, which asks for the placement of <em>n</em> non-attacking queens on an <em>n</em>×<em>n</em> chessboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*SVCP2lIp1jfzJuQn_QUeVg.png" /><figcaption>A solution to the eight queens problem. Source: <a href="http://yue-guo.com/wp-content/uploads/2019/02/N_queen.png">Yue Guo</a></figcaption></figure><p>As seen in the above image, a solution to the n-queens problem requires that each queen’s position is not horizontally, vertically, or diagonally away from that of another queen. A corollary of this fact is that no two queens can be placed in the same row, column, or diagonal — a characteristic which we will take advantage of while constructing our solution algorithm.</p><h4>Finding the number of solutions for a specific n</h4><p>The goal of this section is to create a function (countNQueensSolutions) that counts the number of possible solutions to the n-queens problem for a specific integer n. The beginning of the code is shown below:</p><pre>function countNQueensSolutions(n) {<br>  if (n === 0) {<br>    return 1;<br>  }<br>  let solutionCount = 0;<br>  let emptyBoard = new Board({ n });</pre><p>First off, we check whether the argument is 0. If it is, we return 1, which is the number of solutions to the 0-queens problem. The reason we do so is because we want to search for solutions on a two-dimensional, n×n “chessboard.” However, it doesn’t make much sense to deal with a 0×0 board (and indeed, the function yields an error for n=0 if we do not handle this case).</p><p>Afterwards, we create a variable called solutionCount that will increment as new solutions are found. We then create a new Board object, which holds a two-dimensional array (.rows()) that mimics a chessboard as well as various useful methods. For instance, if n=3, emptyBoard.rows() will have the following structure:</p><p>[[0, 0, 0]<br> [0, 0, 0]<br> [0, 0, 0]]</p><p>The zeroes indicate that the chessboard is empty. When a queen is placed at a specific spot on the board, the corresponding number will change to 1.</p><p>The next thing that needs to be done is the creation of a recursive function that will find all the possible solutions for a given n. This is shown below:</p><pre>  function recursive(board, rowIndex) {<br>    for (let i = 0; i &lt; n; i++) {<br>      let boardCopy = board.rows().map(function(value) {<br>        return value.slice();<br>      });<br>      let newBoard = new Board(boardCopy);<br>      newBoard.rows()[rowIndex][i] = 1;<br>      if (!newBoard.hasAnyQueenConflictsOn(rowIndex, i)) {<br>        if (rowIndex === n - 1) {<br>          solutionCount++;<br>        } else {<br>          recursive(newBoard, rowIndex + 1);<br>        }<br>      }<br>    }<br>  }<br>  recursive(emptyBoard, 0);<br>  return solutionCount;<br>}</pre><p>The following is a step-by-step explanation of the recursive algorithm shown above. Note that “hasAnyQueenConflictsOn” is a pre-defined method for boards. The method returns true if a queen at (rowIndex, colIndex) can be attacked by another queen.</p><ol><li>First, create a copy of the empty chessboard given as an argument (newBoard). This is done so that the same chessboard will not be continually modified as different queen placements are considered.</li><li>Add a queen at a certain index on the first row of the chessboard.</li><li>If there are no conflicts, check if the first row is the last row (i.e., if rowIndex equals n-1). If it is, queens exist on all rows without a conflict, so we have found a solution. Increase solutionCount by 1.</li><li>If the index of the last row is not equal to (n-1), there are more rows that we must add queens to (as a valid solution consists of one queen in each row and column). Run the recursive function again by passing the copied chessboard and the next rowIndex as arguments.</li><li>Within the recursive function call, create a copy of the newly modified chessboard and add a queen on the second row (which now corresponds to the new value of rowIndex).</li><li>If there is a conflict between the first queen and the second queen, the code automatically moves to the next iteration of the for loop and puts the queen at a different position on the second row. This is a process known as <em>backtracking</em> — if there is a conflict, don’t waste time going deeper with recursion. Simply go back and move onto the next possible case.</li><li>If there is no conflict, check if the second row is the last row. If it is, increase solutionCount by 1 (as all n queens have been placed without conflicts) and move to the next loop iteration. If not, run the recursive function again (this time moving on to the third row of the board).</li><li>Continue executing the recursive/iterative steps outlined in 5–7 until solutionCount is fully updated. Return solutionCount at the end.</li></ol><h4>Challenges and Room for Improvement</h4><p>The biggest challenge that I had while writing this algorithm (and still have) is the issue of optimization. For instance, it did not occur to me at first that I should place the next queen on the next row — instead, I thought that I should try placing the next queen on every single open space. As I later realized, this was a naive approach, as (a) I would still <em>have</em> to place a queen on the next row at some point, and (b) open spaces on the current row would never work because a queen already exists on it.</p><p>The issue of having to deep copy the 2D chessboard array on every iteration was also something that I did not see at first. Once I realized that I shouldn’t be modifying the same array on every iteration, I tried copying the 2D array using Array.slice(). This method failed, as I could only achieve a shallow copy. I then tried using JSON.parse(JSON.stringify(<em>array</em>)), which took way too long. The method of copying with .map() and .slice() above was the most efficient solution I could come up with.</p><p>If I were to classify my algorithm on <a href="https://sites.google.com/site/nqueensolver/home/algorithm-results">this chart</a>, I would (optimistically) place it somewhere between <em>Novice Backtracking</em> and <em>Optimized Backtracking</em>. Of course, using only a one-dimensional array could speed this process up faster, and other techniques like <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.7113&amp;rep=rep1&amp;type=pdf">bitwise operators</a> and <a href="https://sites.google.com/site/nqueensolver/home/algorithms/3systematic-greedy-algorithm">systematic &amp; greedy search</a> also exist. I hope you can take this algorithm even further and improve its complexity to be on par with some of these other algorithm types!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8da5d45a34c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-many-solutions-does-the-n-queens-problem-have-e8da5d45a34c">How Many Solutions Does the N-Queens Problem Have?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between prototype and __proto__ in JavaScript?]]></title>
            <link>https://javascript.plainenglish.io/proto-vs-prototype-in-js-140b9b9c8cd5?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/140b9b9c8cd5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Mon, 23 Sep 2019 07:07:28 GMT</pubDate>
            <atom:updated>2019-10-01T20:01:49.997Z</atom:updated>
            <content:encoded><![CDATA[<h4>An explanation of the relationship between the two concepts.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOaDO4sAhvLKmCgAqq-43A.jpeg" /></figure><h3>So you’re wondering, what’s with all that __proto__ and prototype nonsense in JavaScript?</h3><p>Aren’t they exactly the same thing? Let’s find out.</p><h4>An explanation of prototype</h4><p>Apple recently released its new iPhone, the iPhone 11. That phone has certain qualities — for example, Face ID and 4K video. Every iPhone 11 that is produced must have those exact same features.</p><p>Now, let’s assume that there’s a constructor function that produces a new iPhone 11 every time it’s called. In order to properly build an iPhone 11, a <em>prototype </em>— a model of an iPhone 11 to refer to — is needed. This prototype or model ensures that <em>every</em> iPhone has Face ID, that every iPhone can take 4K video. Thus, the iPhone constructor must know and have access to the prototype that it must build. This is the constructor’s <em>prototype</em> property.</p><pre>function iPhone() {}; // constructor</pre><pre>// a method for recognizing faces<br>iPhone.prototype.faceID = function() { ... };</pre><pre>// a method for taking 4k video<br>iPhone.prototype.video = function() { ... };</pre><pre>let newPhone = new iPhone(); // an iPhone 11</pre><p>So far so good, right? Let’s get into __proto__ next.</p><h4>The relationship between __proto__ and prototype</h4><p>I’ve now made a new iPhone 11, and saved it in a variable called newPhone. The contents of newPhone will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*MMJM8j47xmveEkSaeO_Blg.png" /><figcaption>The contents of a new iPhone instance.</figcaption></figure><p>So it seems like this new iPhone 11 comes with FaceID and video! In fact, you can execute newPhone.faceID() or newPhone.video() and see that these methods work fine. However, why are these features stored in an object called __proto__, and not stored directly as properties of newPhone?</p><p>__proto__ is an object in every class <em>instance</em> that points to the prototype it was created from. Here, newPhone.__proto__ is a reference to iPhone.prototype, and thus holds the exact same contents as well. By having a __proto__ property identical to iPhone.prototype, newPhone is essentially saying, “Look, since I’m an iPhone 11, I have the exact same features as any other iPhone 11! I’ve got Face ID, 4K video, you name it.”</p><p>In reality, the only <em>true</em> difference between prototype and __proto__ is that the former is a property of a class constructor, while the latter is a property of a class instance. In other words, while iPhone.prototype provides a blueprint for building an iPhone, newPhone.__proto__ affirms that the iPhone has indeed been built according to that specific blueprint. But with regards to the properties and methods present in those two objects… well, they’re exactly the same.</p><p>Lastly, you might be wondering about the meaning of __proto__: Object in the last line. That’s there because newPhone.__proto__ is actually a JavaScript object, and JavaScript objects are also built according to a specific “blueprint”. In this example, newPhone.__proto__.__proto__ refers to Object.prototype, which is the prototype or blueprint that all JavaScript objects are based on. And that’s about it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140b9b9c8cd5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/proto-vs-prototype-in-js-140b9b9c8cd5">What is the difference between prototype and __proto__ in JavaScript?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Data Structures: Part 2]]></title>
            <link>https://medium.com/@achung3071/common-data-structures-part-2-49ec5e4583be?source=rss-b86b7bda2a74------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ec5e4583be</guid>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Chung]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 19:32:15 GMT</pubDate>
            <atom:updated>2019-09-19T03:31:52.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>A pseudocode-based explanation of trees, binary search trees, graphs, and hash tables.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J01wPqOV2KqFtNcfo581kg.jpeg" /><figcaption>Diagram: Trees and Binary Search Trees</figcaption></figure><p><strong>Tree</strong>: A tree can be defined recursively as a data structure having a root node with 0 or more child nodes. Each child node has 0 or more child nodes, and so on. This structure is used in HTML/DOM, as all elements on a webpage stem from a root &lt;html&gt; element which branches out into a tree. Trees are not linear, but hierarchical in structure. To search for nodes in a tree (which is required when adding or removing nodes), one must traverse or visit all the nodes in it.</p><ul><li><em>Constructor</em>: The constructor for a tree should take in root data as an argument. This root data is assigned to a new Node, which is then set as the <strong>root</strong> node of the tree. Additionally, the constructor for a node should set the node’s <strong>children</strong> as an empty array and <strong>data </strong>as the argument to the constructor.</li><li><em>TraverseDF</em>: This is an algorithm that can serve as the foundation for most other tree methods (adding, removing, etc.). It takes a callback as an argument and executes the callback after visiting each node. The node that is visited is passed as the argument to the callback.<br>1. Create a new function that takes a node as an argument.<br>2. Recursively call the new function that was just created on each of the given node’s children with a for loop. This order of traversal is called depth-first.<br>3. Execute the provided callback with the original node that was passed as an argument.<br>4. Immediately execute this new function by passing the root node of the tree (this.root) as an argument.</li></ul><p><strong>Binary Search Tree: </strong>Binary (Search) Trees are considered a subset of the tree data structure. While nodes in regular trees can have any number of children, nodes in binary trees have at most two children. The children of a binary tree are usually denoted as left and right. Binary trees are used a lot with searching or sorting algorithms, mainly because they can reduce the time complexity of such algorithms to O(log(n)). A method for sorting when adding a new node is shown in pseudo-code below.</p><ul><li><em>Constructor</em>: The constructor for a binary tree should take in root data as an argument. This root data is assigned to a new Node, which is then set as the <strong>root</strong> node of the tree. Additionally, the constructor for a node should set the node’s two children (<strong>left </strong>and <strong>right</strong>) as null and <strong>data </strong>as the argument to the constructor.</li><li><em>Insert</em>: Note that this pseudo-code is written specifically for inserting a node with numerical data. Nodes with smaller numbers as data go on the left side of the tree, while nodes with bigger numbers go on the right. insert should take in one argument, which is the node that should be added to the tree.<br>1. Create a new function insertNode that takes in two arguments: rootNode and newNode.<br>2. If newNode.data &lt; rootNode.data, check if rootNode.left is null. If it is, set rootNode.left as newNode.<br>3. If rootNode.left is not null, then run insertNode recursively by setting the first argument (originally rootNode) as rootNode.left and keeping newNode as the second argument.<br>4. If newNode.data &gt; rootNode.data, check if rootNode.right is null. If it is, set rootNode.right as newNode.<br>5. If rootNode.right is not null, then run insertNode recursively by setting the first argument (originally rootNode) as rootNode.right and keeping newNode as the second argument.<br>6. Immediately run insertNode by passing this.root (the root node of the entire tree) as the first argument and the argument to the insert method as the second argument.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTV7nZgDtvK242rzPkUfnA.jpeg" /><figcaption>Diagram: Graphs and Hash Tables</figcaption></figure><p><strong>Graph</strong>: A graph consists of one or more nodes that are connected to each other by edges. In this sense, trees could be considered a subset of graphs. As with trees, nodes also hold information or data. However, in a graph, any node can be connected to any other node, which is why concepts like “parent” and “child” do not exist when considering a graph. Graphs can represent social networks, transportation routes, trade agreements, etc. Edges in a graph can be either directed or undirected.</p><p>Please note that for the sake of simplicity, I have not mentioned the creation of another node class (although is perfectly fine to do so).</p><ul><li><em>Constructor</em>: Create a graph class that takes a specified number of nodes as a parameter. Set <strong>numNodes</strong> as the given number of nodes and <strong>adjacencyList</strong> as a map object (using map instead of a regular object allows nodes to be stored as keys). This object will show which nodes are connected to which in the graph. Note that if the graph is dense, an adjacency matrix may be more adequate for viewing edges.</li><li><em>addNode</em>: Adds a node to the graph. Simply add the given node as a key to the adjacencyList and an empty array as the value. This empty array will show which other nodes it is connected to.</li><li><em>addEdge</em>: This method takes two nodes that are already on the graph as arguments and adds an “edge” between them. To do this, take the adjacencyList and use the nodes as keys to access their lists of connected nodes. Use the array push method to push each node into the other node’s list of connected nodes.</li></ul><p><strong>Hash Table</strong>: A hash table, similar to a binary tree, is often used with searching algorithms because it requires much less time to complete searches in a hash table as opposed to other associative arrays. The way it reduces the complexity of such algorithms is by implementing a hashing function. A hashing function converts a key to a numerical index, so that one can instantaneously figure out the location of the data that the key points towards. While overlapping index values between two keys can make the searching process slower, it is still much faster than checking each and every value in an array.</p><ul><li><em>Constructor</em>: Create a hash table class that has a size <strong>limit</strong> and an empty array called <strong>storage</strong> as its two data members. The size limit should be determined from the argument to the constructor.</li><li><em>Hash Function</em>: A simple hash function for alphanumeric keys uses ASCII codes. Specifically, the index at which the data is stored is determined through the following — (sum of ASCII codes for the key) mod (hash table size limit).</li><li><em>Lookup</em>: After data is added to the hash table via the given hash function, there will come a time when the data needs to be retrieved again. The lookup function, which is used for this purpose, takes a single key as an argument.<br>1. The index corresponding to the given key is found through the hash function.<br>2. If data corresponding does not exist at that specific index (i.e., if storage[index] is not defined), return false.<br>3. Otherwise, iterate through the key-value pairs present at that specific index via a loop. If the key for one of these pairs matches the key given as an argument, return the corresponding value in the pair. (This assumes the hash table uses separate chaining, not open addressing.)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ec5e4583be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>