<?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 Jerry Mao on Medium]]></title>
        <description><![CDATA[Stories by Jerry Mao on Medium]]></description>
        <link>https://medium.com/@jerrymao?source=rss-cda72c7e8586------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mI-Opl1Lq0coVecj3Mhu7A.jpeg</url>
            <title>Stories by Jerry Mao on Medium</title>
            <link>https://medium.com/@jerrymao?source=rss-cda72c7e8586------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:49:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jerrymao/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[What is an Abstract Syntax Tree and why do I care?]]></title>
            <link>https://medium.com/@jerrymao/what-is-an-abstract-syntax-tree-and-why-do-i-care-c7882db8edc8?source=rss-cda72c7e8586------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7882db8edc8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[abstract-syntax-tree]]></category>
            <category><![CDATA[acorn]]></category>
            <dc:creator><![CDATA[Jerry Mao]]></dc:creator>
            <pubDate>Fri, 29 Jul 2016 01:18:17 GMT</pubDate>
            <atom:updated>2016-07-29T01:18:17.640Z</atom:updated>
            <content:encoded><![CDATA[<p>As a JavaScript developer, your typical dev environment probably includes a compiler such as <a href="https://babeljs.io/">Babel</a> if you’re using transpiled JavaScript/ES2015, a linter (<a href="http://eslint.org/">ESLint</a> is a pretty solid choice), and some way to <a href="https://github.com/mishoo/UglifyJS2/">minify your production-ready code</a> (because you obviously want to be as efficient as possible). These are all tools that parse through your code, and in most cases, generate new code. Although there are differences in what they do and how they do it, most of these tools have at least one thing in common: abstract syntax trees.</p><p>In programming, abstract syntax trees are data structures (trees to be exact) that represents the syntactical structure of your source code. They differ from concrete syntax trees as the resulting data structure is relatively abstracted (ie punctuation and parentheses are excluded). By parsing source code into an AST, it is much easier to perform static analysis. All the programs I mentioned above rely on ASTs for their static analysis, whether it be compiling code to more browser-friendly format, or finding out what variables are safe to replace with one letter words.</p><p>In JavaScript, ASTs are usually built through parsers such as <a href="https://github.com/ternjs/acorn">acorn</a> and <a href="http://esprima.org/">esprima</a>. The resulting AST is an object that contains a multitude of nodes, each representing a specific part of the source code. To easily see examples (and to follow along the next section) use <a href="http://astexplorer.net/">ASTExplorer</a>, where you can enter in code walk through the resulting AST. For example, if I put in a simple</p><pre>var x = 2 + 3</pre><p>I get back a “VariableDeclaration” node. This node is has one declaration, which is separated into its ID (x) and init (2 + 3). The init, which is a “BinaryExpression,” is further separated into three parts: a left literal (2), a binary operator (+), and a right literal (3). All in all, this simple one line declaration results in an AST that spans 47 lines. Imagine having to manually parse through a large source file! Fortunately, there are tools available out there that help you traverse an AST to get only what you’re interested in, such as <a href="https://github.com/estools/esrecurse">esrecurse</a> and <a href="https://github.com/estools/estraverse">estraverse</a>. Most of these tools come from the EStools repository, which is aimed for use with esprima. However, since most parsers follow the <a href="https://github.com/estree/estree">ESTree spec</a>, this shouldn’t be too much of a problem.</p><p>Armed with the knowledge, you’re now one step closer to building your own linter/transpiler/minifier/whatever!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7882db8edc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make a Tree in D3 4.0]]></title>
            <link>https://medium.com/@jerrymao/make-a-tree-in-d3-4-0-98a379313297?source=rss-cda72c7e8586------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a379313297</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[Jerry Mao]]></dc:creator>
            <pubDate>Fri, 15 Jul 2016 00:55:46 GMT</pubDate>
            <atom:updated>2016-07-16T18:26:28.360Z</atom:updated>
            <content:encoded><![CDATA[<p>A couple of weeks ago (as of writing this blog). the popular data documentation library <a href="https://d3js.org/">D3</a> (which, surprisingly, stands for Data-Driven Documents) released a <a href="https://github.com/d3/d3/releases/tag/v4.0.0">major 4.0 update</a>. The biggest change that stands out is the modularization of the library, as well as changes to existing methods.</p><p>While working on a <a href="https://github.com/team-gryff/react-monocle">project</a>, I found that the update broke the existing code we were using to render a tree. Rather than falling back to a previous version, I instead took it upon myself to update the code to be compatible with the new version. In doing so,however, I found documentation to be sparse, which is why I thought it would be cool to share the steps I took.</p><p>Just a heads up, I will be using ES2015 imports to import modules into my code, so you will need a module bundler such as <a href="http://browserify.org/">browserify</a> or <a href="https://webpack.github.io/">webpack</a> if you haven’t included one in your dev environment yet.</p><p>If you used d3 before, you probably found yourself importing the whole d3 object. With the 4.o update, D3 now takes advantage of ES2015 modules, which means now we’re only importing what we need! We will be using the tree, hierarchy, select, and path modules to build our tree. Start by importing them at the top of your file.</p><pre>import { tree, hierarchy, select, path } from ‘d3’;</pre><p>Next, we’re going to instantiate our constants.</p><pre>const m = [20, 120, 20, 120],<br>w = 1480 — m[1] — m[3],<br>h = 800 — m[0] — m[2],<br>i = 0,<br>rectW = 200,<br>rectH = 100;</pre><p>This defines the width/height of the graph and nodes. Now we can make the function that will create the tree. It will take in the html element the graph will be rendered on as well as the data that will be visualized by the tree.</p><pre>function create(element, treeData) {<br> //make tree<br>}</pre><p>Inside the function we’re first going to instantiate our tree using d3’s tree module. We’re also going to append a svg element with the given width and height and a g element inside the svg.</p><pre>function create(element, treeData) {<br> const tree = tree().size([w, h]);</pre><pre>const svg = select(element)<br> .append(‘svg”)<br> .attr(“width”, w)<br> .attr(“height”, h)<br> .append(“svg:g”)<br> .attr(“transform”, “translate(0,40)”);<br>}</pre><p>Next, we’re going to format the data we pass in with d3’s hierarchy module, and pass in the result into our tree variable.</p><pre>const nodes = tree(hierarchy(treeData));</pre><p>We’re also going to iterate through this newly created data with d3 4.0’s new “each” method (that replaced forEach) to set the y coordinates of each node. We’re also going to select all the g elements with the class “node” (which will be declared in a bit) and assign them IDs.</p><pre>nodes.each(d =&gt; {<br> d.y = d.depth * h / 3;<br> })</pre><pre>const node = svg.selectAll(‘g.node’)<br> .data(nodes, d =&gt; {<br> return d.id || (d.id = ++i);<br> });</pre><p>Finally, we can start appending our nodes to the DOM!</p><pre>const nodeEnter = node.enter().append(‘g’)<br> .attr(‘class’, ‘node’);</pre><pre>nodeEnter.append(‘rect’)<br> .attr(‘width’, rectW)<br> .attr(‘height’, rectH)<br> .attr(‘y’, -10)<br> .attr(‘rx’, 2)<br> .attr(‘ry’, 2)<br> .attr(‘stroke’, ‘black’)<br> .attr(‘stroke-width’, 0.9)<br> .attr(‘transform’, d =&gt; `translate(${d.x},${d.y})`)<br> .style(‘fill’,‘lightsteelblue’);</pre><pre>nodeEnter.append(‘text’)<br> .attr(‘x’, 4)<br> .attr(‘y’, 10)<br> .attr(‘dy’, ‘.5em’)<br> .text(d =&gt; d.name)</pre><p>Our nodes are built by the “rect” svg element, with attributes assigned using d3’s attr method. The important thing to note is the transform attribute, which is calculated by d3 and used to properly position the nodes. The text displayed will be the name property of each node.</p><p>Now that we have our nodes, it’s time to create the paths to each node. This is done through <a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves">cubic bézier curves</a>. Personally, this part was the most challenging in importing my previous code to be compatible with the new release. A cubic bézier curve takes four points: a start, a end, and two points to determine how it will curve. In prior releases, this more abstracted using d3.svg.diagonal(), but in this release, I found myself having to ditact the specific coordinates of the paths. The resulting code looks like this:</p><pre>svg.selectAll(‘path.link’)<br> .data(links, d =&gt; { return d.target.id; })<br> .enter().insert(‘svg:path’, ‘g’)<br> .attr(‘class’, ‘link’)<br> .attr(‘d’, nodez =&gt; {<br> const oldX = nodez.source.x;<br> const oldY = nodez.source.y;<br> const newX = nodez.target.x;<br> const newY = nodez.target.y;<br> const pathing = path();<br> pathing.moveTo(oldX + rectW / 2, oldY);<br> pathing.bezierCurveTo(oldX + rectW / 2, (oldY + newY) / 2, newX + rectW / 2, (oldY + newY) / 2, newX + rectW / 2, newY);<br> return pathing;<br> });</pre><p>Similar to the nodes, we insert svg paths before the g on the DOM. The d property dictates how the path will curve and look based on the information given. In this case we instantiate d3’s path module. After moving to the starting point, a bézier curve is created with the remaining three coordinates.</p><p>That’s it! A simple tree graph, written in brand new D3 code. The resulting code should look like this:</p><pre>function create(element, treeData) {<br> const tree = tree().size([w, h]);</pre><pre>const svg = select(element)<br> .append(‘svg”)<br> .attr(“width”, w)<br> .attr(“height”, h)<br> .append(“svg:g”)<br> .attr(“transform”, “translate(0,40)”);<br> <br> const nodes = tree(hierarchy(treeData));<br> nodes.each(d =&gt; {<br> d.y = d.depth * h / 3;<br> })</pre><pre>const node = svg.selectAll(‘g.node’)<br> .data(nodes, d =&gt; {<br> return d.id || (d.id = ++i);<br> });</pre><pre>const nodeEnter = node.enter().append(‘g’)<br> .attr(‘class’, ‘node’);</pre><pre>nodeEnter.append(‘rect’)<br> .attr(‘width’, rectW)<br> .attr(‘height’, rectH)<br> .attr(‘y’, -10)<br> .attr(‘rx’, 2)<br> .attr(‘ry’, 2)<br> .attr(‘stroke’, ‘black’)<br> .attr(‘stroke-width’, 0.9)<br> .attr(‘transform’, d =&gt; `translate(${d.x},${d.y})`)<br> .style(‘fill’, function (d) {<br> return d.children ? ‘white’ : ‘lightsteelblue’;<br> });</pre><pre>nodeEnter.append(‘text’)<br> .attr(‘x’, 4)<br> .attr(‘y’, 10)<br> .attr(‘dy’, ‘.5em’)<br> .text(d =&gt; d.name)</pre><pre>svg.selectAll(‘path.link’)<br> .data(links, d =&gt; { return d.target.id; })<br> .enter().insert(‘svg:path’, ‘g’)<br> .attr(‘class’, ‘link’)<br> .attr(‘d’, nodez =&gt; {<br> const oldX = nodez.source.x;<br> const oldY = nodez.source.y;<br> const newX = nodez.target.x;<br> const newY = nodez.target.y;<br> const pathing = path();<br> pathing.moveTo(oldX + rectW / 2, oldY);<br> pathing.bezierCurveTo(oldX + rectW / 2, (oldY + newY) / 2, newX + rectW / 2, (oldY + newY) / 2, newX + rectW / 2, newY);<br> return pathing;<br> });<br>}</pre><p>Just run the function, passing in data and the DOM element of your choice, and you should see a tree display on your page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a379313297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React.js Components with Enzyme, Mocha, and Chai]]></title>
            <link>https://medium.com/@jerrymao/testing-react-js-components-with-enzyme-mocha-and-chai-534c7f000976?source=rss-cda72c7e8586------2</link>
            <guid isPermaLink="false">https://medium.com/p/534c7f000976</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jerry Mao]]></dc:creator>
            <pubDate>Fri, 10 Jun 2016 00:57:33 GMT</pubDate>
            <atom:updated>2016-07-31T01:25:52.317Z</atom:updated>
            <content:encoded><![CDATA[<p>One way to ensure a productive and efficient workflow is to set up tests. However, if a developer is working in React.js, tests may seem harder to implement, as React’s main interactions are with it’s own virtual DOM. There have been a multitude of ways people have developed in order to get around this. However, the best way I have found is through <a href="https://github.com/airbnb/enzyme">Enzyme</a>, a testing utility from the Airbnb team. Along with Enyzme, my test stack includes:</p><p>Mocha: JavaScript test framework</p><p>Chai: BDD / TDD assertion library</p><p>JSDOM: JavaScript implementation of the DOM.</p><p>Assuming you have your React environment set up already, go ahead and install everything using npm.</p><pre>npm i enzyme mocha chai jsdom react-addons-test-utils cheerio babel-register babel-preset-airbnb babel-preset-react babel-preset-es2015 -D</pre><p>“react-addons-test-utils” are required for any test environment using React components, and Cheerio is need for Enzyme to work properly. We are also installing babel with a couple of presets in order for your tests to be properly read by node.</p><p>If you’re already using babel in your project and have it configured already, skip this section. If not, you’ll have to make a .babelrc file in your root directory. This file will be used by babel for configuration information. Inside the file, include the presets you just downloaded. It should look something like the following.</p><pre>{<br> presets: [“react”,”airbnb”, “es2015”]<br>}</pre><p>Once your modules are installed, in your root directory, go ahead and make a test folder. This is the folder where we are going to populate your tests.</p><p>Before we make any tests, however, we are going to make a file called .setup.js that will configure JSDOM.</p><pre>//in test/.setup.js<br>require(‘babel-register’)();</pre><pre>var jsdom = require(‘jsdom’).jsdom;</pre><pre>var exposedProperties = [‘window’, ‘navigator’, ‘document’];</pre><pre>global.document = jsdom(‘’);<br>global.window = document.defaultView;<br>Object.keys(document.defaultView).forEach((property) =&gt; {<br> if (typeof global[property] === ‘undefined’) {<br> exposedProperties.push(property);<br> global[property] = document.defaultView[property];<br> }<br>});</pre><pre>global.navigator = {<br> userAgent: ‘node.js’<br>};</pre><pre>documentRef = document;</pre><p>Now, we can start making tests! Assuming we’re following a test driven development workflow, we make our tests before we even write a line of code for our component. For now, let’s assume we want to make a component called Foo. Make a new file in your test folder called “Foo-Test.js” where we can start writing our code.</p><pre>‘use strict’;<br>import React from ‘react’;<br>import { expect } from ‘chai’;<br>import { shallow, mount, render } from ‘enzyme’;<br>import Foo from ‘PUT WHERE FOO WILL BE HERE’;</pre><p>All the code should be in the top of your test file, importing all the components that we need. Notice I have a placeholder for Foo’s filepath, as we did not create the component yet. Next, we’re going to describe how want the component to look like. For our Foo component, I want the main div to have a class called “foo”, with two child divs called “bar.” The resulting code will look like this:</p><pre>describe(&#39;Component Foo&#39;, function() {<br> it (&#39;should have a class named foo&#39;, function() {<br> const wrapper = shallow(&lt;Foo /&gt;);<br> expect(wrapper.is(‘.foo&#39;)).to.equal(true);<br> })</pre><pre>it(‘should have two children’, function() {<br> const wrapper = shallow(&lt;Foo /&gt;);<br> expect(wrapper.children().length).to.equal(2)<br> })</pre><pre>it(‘should have children with a class named bar’, function() {<br> const wrapper = shallow(&lt;Foo /&gt;);<br> expect(wrapper.children(‘.bar’).length).to.equal(2);<br> })<br>})</pre><p>Because my component does not have state or lifecycle methods, I’m using Enyzme to just shallowly render the component. This allows a component to be tested in isolation as well. If you want to test something that depends on state, props, or certain lifecycle methods, use the “mount” method instead of “shallow.”</p><p>After creating your component, you should be able to test them using mocha through the command line. It should look something like this:</p><pre>mocha test/.setup.js &#39;YOUR TEST FILE PATH HERE&#39;</pre><p>In the start, ideally every test should be failing. If you have passing tests, go back and check your test!</p><p>By making the test before you make your component, you ensure you have a clear and succinct idea of what your want your component to look like, and what it should contain. Although the test may take up some time to set up, many times you will find that you actually saved yourself some time. This is the core concept behind test driven development, which many companies currently impliment in their own product development lifecycle.</p><p>This is just the tip of the iceberg when it comes to testing React components. For more information, look at the <a href="https://github.com/airbnb/enzyme/tree/master/docs/api">API documentation</a> for Enzyme. Good luck, and happy testing. Go get them green check marks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=534c7f000976" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>