<?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 Amanda DaSilva on Medium]]></title>
        <description><![CDATA[Stories by Amanda DaSilva on Medium]]></description>
        <link>https://medium.com/@adasilva?source=rss-c9675007d974------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qy_xVb-L8d1zxQCOaH1YZQ.jpeg</url>
            <title>Stories by Amanda DaSilva on Medium</title>
            <link>https://medium.com/@adasilva?source=rss-c9675007d974------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:53:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adasilva/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[The Angular Conversion Part 4: What we couldn’t Automate]]></title>
            <link>https://medium.com/grubhub-bytes/the-angular-conversion-part-4-what-we-couldnt-automate-aa37061cb328?source=rss-c9675007d974------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa37061cb328</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Amanda DaSilva]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 18:01:00 GMT</pubDate>
            <atom:updated>2019-07-11T19:37:15.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Angular conversion part 4: What we couldn’t automate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjcmK3XjHJP3LLqWnoqRtg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/0E0j6aC5BUw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fancycrave</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>(<em>This is the fourth and final part of our series on our conversion from AngularJS to Angular. </em><a href="https://bytes.grubhub.com/how-i-learned-to-stop-angularjs-and-love-the-angular-e84b0aabb49d"><em>Part one</em></a><em> discussed our history with frameworks and why we decided to make the change. </em><a href="https://bytes.grubhub.com/angular-is-coming-preparing-the-upgrade-be9ec8954ea2"><em>Part two </em></a><em>covered some of the preliminary steps we took before running our conversion script. And </em><a href="https://medium.com/p/automating-the-angular-conversion-31e73f6c6f70"><em>part three</em></a><em> gave you the script and detailed our process.</em>)</p><p>With the JavaScript landscape constantly changing, a framework conversion is a challenge that most web teams will eventually tackle. On a high level, this kind of conversion is a matter of changing your application dependencies and updating the codebase to function with those dependencies. In reality, there is a lot more to a framework conversion than just making the application “work.” You also need the application to work well, and that requires adopting the best practices and ideologies of the new framework.</p><p>As the previous post in this series discusses, we were able to automate the conversion from AngularJS to Angular quickly in terms of boilerplate. However, completing this project was a largely handcrafted process. This fourth and final blog post in the series on our conversion from AngularJS to Angular will cover some lessons we’ve learned while converting our app from something that “works” to a performant Angular app.</p><p>Automating a big chunk of our Angular conversion allowed us to start running our code within the new framework relatively quickly. But this first version of our converted app was a disappointment. Scrolling was janky, our bundles were huge, and the tooling was slow. It turns out that the Angular core team was right — migrating from AngularJS to Angular is not fully automatable. Our team spent the next few months learning Angular and its tooling to get our application in a state we could be proud of.</p><h3>Zones</h3><p>Angular made significant updates to its change detection triggers, and understanding those updates was key to improving our own app performance. Change detection in Angular is powered by a library called Zone.js. This library monkey patches global asynchronous functions on the page and triggers change detection cycles when those asynchronous tasks complete. This is clever because most applications don’t need to update the view unless there is a user interaction or new data on the page. This is the default change detection that ships out of the box with Angular.</p><p>In almost all cases, the default change detection works well and has good performance. However, sometimes you don’t want to use the default. One big exception we found is for asynchronous events that fire rapidly, such as scroll events. In the first version of our application, our pages had poor performance during scrolling. This was the result of our scroll listener triggering hundreds of change detection cycles during scrolling.</p><p>To solve this problem, Angular provides a method on the <em>NgZone</em> provider that allows engineers to run a function outside of the Angular zone to prevent auto triggering change detection. After learning this, we made sure all rapid fire events were explicitly running outside of zones. When these events needed to update the DOM, we explicitly triggered change detection only when necessary using Angular’s <em>ChangeDetectionRef </em>provider. This simple change gave us a huge performance boost and resolved our scrolling jank.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14f195aaf02aeef9f06ae77500f3746e/href">https://medium.com/media/14f195aaf02aeef9f06ae77500f3746e/href</a></iframe><p>Aside from performance, Zones also have a huge impact on end-to-end testing with Protractor. After the conversion, we noticed that our e2e tests were running painfully slow. We learned that Protractor utilizes the Angular zone to handle testing synchronization. Essentially, Protractor waits for all zones to complete before moving on to the next step in the testing sequence. As a result, several long-running setTimeouts for things like notifications were causing serious delays during our tests. The solution for this was to run the setTimeout using outside of zones — as described above — and then to explicitly trigger change detection when the callback is finally fired.</p><h3>Lazy Loading</h3><p>The new Angular is a framework that requires compilation, which introduces a dramatic change to the way you ship and deploy apps. The new recommended way to ship a production app is through Ahead-Of-Time (AOT) compilation via the AOT compiler. This compiler runs as part of the build process to output performance optimized code.</p><p>Introducing the AOT compiler to our Webpack production build required us to make many changes to our build process and codebase because it introduces and enforces a lot of stylistic and architectural patterns. Some significant changes include:</p><ul><li>AOT templates can only access <em>public</em> class members.</li><li>There is no ability to add custom loaders for things like <em>HTML</em> files.</li><li>The compiler requires your code to use only a subset of JavaScript that is understood by the AOT <em>collector</em>.</li></ul><p>We found that with all the things going on in a black box, and it was challenging to create the custom tooling that our application required.</p><p>One challenge we faced was to add support for our route-independent lazy modules. For example, we have an Angular module that contains all of our modal components. Since modals never load immediately after app bootstrap, we lazy load this module 10 seconds after initial page load to reduce our page load time. With the Angular upgrade, this presented a problem for us since the currently prescribed way to connect and compile a module in Angular is through the router and this module is route independent. We went through several implementations utilizing both Webpack plugins and Angular tools before we came up with a simpler solution utilizing the router.</p><p>We solved this by adding an unreachable route referencing this module, which the Angular compiler would compile in the context of our application, just the way we needed it. To load the lazy modules, we built a service that utilizes the loader functionality on the Angular router. Once loaded, this service initializes the module with an Angular Injector and provides references to the module’s component factories. These factory references are consumed by our <em>lazy-module-outlet</em> directive which handles initializing a component from the factory and attaches it to the view. <a href="https://www.npmjs.com/package/ngx-lazy-module">This solution is available on NPM</a>.</p><p>An additional benefit to leveraging the Angular router in this way is the ability to manually pre-load any route modules when we anticipate users will need them soon — e.g., load the restaurant module after a user starts interacting with the search page. This gives us greater control of when modules are loaded in our application and has improved our user experience both on the initial load and when moving between routes.</p><h3>Unit Testing</h3><p>The performance of the application our diners use is generally our biggest priority, but performance of developer tooling is also important for maintaining a healthy codebase, and the Angular conversion introduced a lot of new tooling. In particular, our testing suites were hugely impacted by these changes. In addition to Zones significantly slowing down our Protractor tests, after the initial conversion, our unit tests were running disappointingly slow.</p><p>Although building our huge spec bundles was time consuming, we were surprised to find that the unit tests themselves were taking much longer to run post conversion. After investigating with the Chrome performance tab, we were able to identify the cause. In the new Angular testing tools, they recommend to call a function TestBed.configureTestingModule before each component test. It turns out that this function has very poor performance and was responsible for the slowdown. However, it is also a vital tool for testing components.</p><p>We refactored our unit tests and created a tool to allow us to only call TestBed.configureTestingModule once for each component we unit test. This tool prevents the TestBed from resetting between each test and instead resets only providers between each unit test. Implementing this decreased our component unit test runtime by about 70% for a suite of ~1200 component tests. This was a huge improvement for developers who regularly run the unit tests repeatedly during development and for our integration time.</p><p>Total post-build runtime of 1193 component tests:</p><ul><li>Without improvement: ~100s</li><li>With improvement: ~30s</li></ul><p>Code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/275518ec90cefd43c6cc0f22c22d02e3/href">https://medium.com/media/275518ec90cefd43c6cc0f22c22d02e3/href</a></iframe><h3>In Conclusion…</h3><p>Finishing the conversion that we initially automated required us to get to know new tooling, adapt our code to a new set of best practices, and develop some creative solutions. This post mentions a few key learning moments we faced, but there were many more we weren’t able to include such as translations, code splitting, and server-side rendering.</p><p>Automating the first part of our conversion allowed us to get our application bootstrapped quickly. This enabled our engineers to spend more time learning and solving problems and less time migrating boilerplate. As much as we wanted to automate the entire process, we were lucky to strike this balance between automation and manual development. We hope that sharing these experiences will be helpful to other teams going through similar challenges.</p><p><em>Do you want to learn more about opportunities with our team? Visit the</em><a href="http://bit.ly/WORK4GH"><em>Grubhub careers page</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa37061cb328" width="1" height="1" alt=""><hr><p><a href="https://medium.com/grubhub-bytes/the-angular-conversion-part-4-what-we-couldnt-automate-aa37061cb328">The Angular Conversion Part 4: What we couldn’t Automate</a> was originally published in <a href="https://medium.com/grubhub-bytes">Grubhub Bytes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Localstorage fails — a tale of cookies and crumbs]]></title>
            <link>https://medium.com/grubhub-bytes/when-localstorage-fails-a-tale-of-cookies-and-crumbs-8be0e5044aeb?source=rss-c9675007d974------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be0e5044aeb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Amanda DaSilva]]></dc:creator>
            <pubDate>Wed, 22 Feb 2017 22:26:32 GMT</pubDate>
            <atom:updated>2019-07-12T15:51:13.385Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at <a href="http://www.grubhub.com/">Grubhub</a>, we use localstorage to persist state in our applications. We migrated our main consumer-facing application to Angular some time ago, and it has since been a cheap, easy option to persist state. The problem? Safari private mode. Safari private mode sets the localstorage quota to zero, which triggers a javascript exception on each call to localstorage.setItem and prevents applications from storing data. For us, this meant that a group of users were unable use our site.</p><h3><strong>Quick Band Aid</strong></h3><p>Our temporary solution was to wrap localstorage calls with try/catch blocks. When these blocks intercepted a javascript error, the application redirected users to a page explaining that they could not use our website in private mode. This was a quick fix for us, thanks to our decision to wrap all localstorage calls in a <em>localStorageUtility</em> class. However, this was not a solution to the problem since it fully prevented Safari private users from interacting with our site.</p><h3><strong>Cookie Solution</strong></h3><p>After remedying application crashes with error handling, we came up with a solution to enable users to order food without localstorage. The plan: optimize and reduce localstorage usage and store this data in cookies when localstorage is not available.</p><p><em>Disclaimer:</em> We went about this task knowing that it is not advisable to bloat application cookies since it <strong>will slow down network requests</strong>. However, the architecture of our application made this developer sin permissible. Since we host the Grubhub apis on a separate domain, the only requests our cookies affect are around page load. In our opinion, a slower page load is preferable to a disabled website. If this cookie hack did affect our api requests, we might have come to a different conclusion.</p><h3><strong>Cookie Crumbs</strong></h3><p>A cookie-based storage solution requires addressing two main limitations to storing application data in cookies:</p><ul><li>Individual cookies have a size limit that can vary between browsers.</li><li>Domains have a cookie limit that can also vary between browsers.</li></ul><p>The effect of these limitations is that a cookie storage solution cannot simply set data on a cookie, it needs to handle cases where the data exceeds the cookie size limit. Our response to this is the aptly named <em>cookie</em> <em>crumb</em>. We define a <em>cookie crumb</em> as a cookie fragment that contains some part of a cookie’s data. A crumbled cookie’s value is derived by combining all of its crumbs.</p><p>Our crumb solution works because we have a naming convention that allows reassembling the crumbs in the correct order by sorting the keys. We create a crumb by taking either the first or second half of the parent cookie value and deriving a crumb key. Our algorithm appends these crumb keys with a binary value based on whether they are the first or second half of the value. This is a recursive pattern that results in the number of crumbs being a power of two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*oEmoWsKUEZrFgTx2.jpg" /></figure><p>This solution addresses the cookie size limit, which has proven to be the main limiting factor for our application. In the event that the application stores the maximum number of cookies or exceeds its data allotment, our implementation of this solution falls back on directing users to a page encouraging them to switch out of private mode. If a limitation to the number of cookies allowed were to become an issue, an algorithm that maximizes the size of each crumb should replace this one.</p><h3><strong>Implementation Details</strong></h3><p>For those interested in the details of how we implemented <em>cookie crumbs</em>, below is the relevant code and steps we took:</p><ul><li>Setup <em>localStorageUtility</em> to handle multiple generic storage solutions. This structure allows the application to easily switch between localstorage, cookie storage, and any future storage implementations of <em>IStorageInterface.</em> We did this in three steps:</li></ul><ol><li>Define a storage interface (<em>IStorageInterface</em>)</li><li>Implement the storage interface in a <em>localStorageImpl</em> class</li><li>Replace localStorage interactions in <em>localStorageUtility</em> with an instance of <em>localStorageImpl</em>.</li></ol><p>Our code:</p><pre>interface IStorageInterface {<br>		get: (key: string) =&gt; any;<br>		set: (key: string, value: any) =&gt; void;<br>		reset: (prefix: string) =&gt; void;<br>		remove: (key: string) =&gt; void;<br>		dictionary: () =&gt; Object;</pre><ul><li>Implement the CookieStorageImpl class. For quick access, this class maintains a dictionary of stored cookies and crumb keys.</li><li><em>Constructor:</em> first loads all the browser cookies into a dictionary then calls <em>gatherCrumbs</em> on that dictionary. The first loop inside <em>gatherCrumbs </em>identifies keys that have crumbs — their values are set to the <em>crumbKey</em> value. For each of those keys, a second loop searches the dictionary for keys that are crumbs of the parent key and appends the keys to a list. The final list is sorted, the strings appended, and the parent key is updated with the final encoded value.</li><li>g<em>et():</em> returns the decoded value for the key in the dictionary.</li><li><em>set(param):</em> first calls <em>remove</em> for the key in order to clean up any crumbs that may have been set previously. It then adds the encoded value to the dictionary and tests that the cookie was correctly set. If the cookie was not set correctly, it means the value is too large. Our recursive cookie logic follows:</li><li>Set the original key to <em>crumbKey</em> so we can quickly identify it as a “crumbled” cookie.</li><li>Divide the value in half and derive the two new crumb keys. The value <em>crumbKey</em> lets us quickly identify a crumb and adding the numerical suffix allows for sorting the crumbs when reassembling. Call <em>setCrumbs</em> with the new keys and split values.</li><li>First half key = key + ‘-’ + crumbKey + ‘-0’</li><li>Second half key = key + ‘-’ +crumbKey + ‘-1’</li><li><em>setCrumbs </em>will attempt to set the cookie and the dictionary, and once again test that the set cookie is correct. If it is not correct, we recursively call <em>setCrumbs </em>with new keys and the split values.</li><li>First half key = key + ‘0’</li><li>Second half key = key + ‘-1’</li><li>If the length of the value is less than 500, then it is likely that the browser is out of cookie storage and we reset the cookies and redirect to an error.</li><li>If setting a large cookie is successful, the browser cookies may include:</li><li>cookieKey-crumbKey-00</li><li>cookieKey-crumbKey-01</li><li>cookieKey-crumbKey-10</li><li>cookieKey-crumbKey-11</li><li><em>remove(key): </em>deletes the key from the dictionary and expires the cookie. Then, the call looks for any crumb references to delete in the same way.</li></ul><h3>Our code</h3><pre>export class CookieStorageImpl extends StorageConstants implements IStorageInterface{<br>    private loadedCookies;<br>    private crumbKey = &#39;ngCrumb&#39;;<br>    private defaultExp = 30;<br>    constructor(private $browserCookieUtils: BrowserCookies, private $location) {<br>        super();<br>        this.init();<br>    }<br>    public get(key: string): any {<br>        if (this.loadedCookies[key]) {<br>            return this.decode(this.loadedCookies[key]);<br>        }<br>    }<br>    public set(key: string, value: any, expDays?: number) {<br>        let encodedVal = this.encode(value);<br>        this.remove(key);<br>        this.loadedCookies[key] = encodedVal;<br>        expDays = angular.isDefined(expDays) ? expDays : defaultExp;<br>        this.$browserCookieUtils.createCookie(key, encodedVal, expDays, true, true);</pre><pre>if (this.cookieFailure(key, encodedVal)) {<br>            // if this fails, the cookie is likely too large, and we need to divide the cookie into crumbs<br>            this.$browserCookieUtils.createCookie(key, this.encode(this.crumbKey), expDays, true, true);<br>            this.setCrumbs(key + &#39;-&#39; + this.crumbKey + &#39;-0&#39;, value.slice(0, value.length / 2), expDays);<br>            this.setCrumbs(key + &#39;-&#39; + this.crumbKey + &#39;-1&#39;, value.slice(value.length / 2), expDays);           <br>        }<br>    }<br>    public remove(key: string) {<br>        delete this.loadedCookies[key];<br>        this.$browserCookieUtils.deleteCookie(key);</pre><pre>// remove crumbs<br>        for (let crumb in this.loadedCookies) {<br>            if (crumb.indexOf(key + &#39;-&#39; + this.crumbKey) &gt; -1) {<br>                delete this.loadedCookies[crumb];<br>                this.$browserCookieUtils.deleteCookie(crumb);<br>            }<br>        }<br>    }<br>    public reset(prefix: string): boolean {<br>        let hasReset= false;<br>        for (let key in this.loadedCookies) {<br>            if (key.substring(0, prefix.length) === prefix) {<br>                this.remove(key);<br>                hasReset = true;<br>            }<br>        }<br>        return hasReset;<br>    }<br>    public dictionary(): Object {<br>        return this.loadedCookies;<br>    }</pre><pre>private init() {<br>       let cookies = document.cookie,<br>            tempStore = {},<br>            temp;<br>        // loading cookies<br>        cookies.split(&#39;;&#39;).forEach((value) =&gt; {<br>            temp = value.split(&#39;=&#39;);<br>            if (temp[0] &amp;&amp; temp[1]) {<br>                tempStore[temp[0].trim()] = temp[1].trim();<br>            }<br>        });<br>        this.loadedCookies = this.gatherCrumbs(tempStore);<br>    }</pre><pre>/**<br> * helper function to re-assemble cookies that have been &#39;crumbled&#39; to fit<br> */<br>    private gatherCrumbs(cookieStore: Object): any {<br>        for (let key in cookieStore) {<br>            if (key.indexOf(this.crumbKey) === -1 &amp;&amp; cookieStore[key] === this.encode(this.crumbKey)) {<br>                let crumbs = [];<br>                 for (let possibleCrumb in cookieStore) {<br>                     if (possibleCrumb.indexOf(key + &#39;-&#39;) &gt; -1) {<br>                         crumbs.push(possibleCrumb);<br>                     }<br>                 }<br>                 crumbs.sort();<br>                 cookieStore[key] = crumbs.reduce((previousValue, currentKey) =&gt; {<br>                     let newVal = previousValue + cookieStore[currentKey];<br>                     cookieStore[currentKey] = &#39;&#39;;<br>                     return newVal;<br>                 }, &#39;&#39;);<br>            }<br>        }<br>        return cookieStore;<br>    }</pre><pre>/**<br> * helper function for setting and dividing cookies until the fit. We assume that<br> * all modern browsers will store at least 500 characters in a cookie.<br> */<br>    private setCrumbs(key: string, value: string, expDays: number): void {<br>        this.$browserCookieUtils.createCookie(key, value, expDays, true, true);</pre><pre>if (value &amp;&amp; value.length &gt; 500 &amp;&amp; this.cookieFailure(key, value)) { // need to split into spaller fragments<br>            this.remove(key);<br>            this.setCrumbs(key + &#39;0&#39;, value.slice(0, value.length / 2), expDays);<br>            this.setCrumbs(key + &#39;1&#39;, value.slice(value.length / 2), expDays);<br>        } else if (value &amp;&amp; value.length &lt;= 500) { // ran out of cookie storage or cookies disabled, clean up and redirect<br>            this.reset(this.PREFIX_KEY);<br>            this.$location.path(&#39;/cookiesError&#39;);<br>        } else { // success<br>            this.loadedCookies[key] = &#39;&#39;;<br>        }<br>    }<br>    private cookieFailure(key: string, value: string): boolean {<br>        return this.$browserCookieUtils.getCookie(key).length !== value.length;<br>    }</pre><pre>private encode(value: any): string {<br>        return encodeURIComponent(angular.toJson(value));<br>    }<br>    private decode(value: any): any {<br>        if (value === &#39;&#39; || !angular.isDefined(value)) {<br>            return;<br>        }<br>        return angular.fromJson(decodeURIComponent(value));<br>    }<br>}</pre><h3>Storage Today</h3><p>This cookie solution worked for our diner app temporarily, until the total size of our cookie data began exceeding browser limitations (iOS &lt; 10, this limit is about 8kb). We have little control over this since our production environment includes cookies from 3rd party sources that can fluctuate in size and significantly contribute to cookie bloat. Today we have implemented a server-side storage solution to serve our users without access to localstorage.</p><p>Although we no longer use it, we believe that this cookie solution may be helpful to others. For us, it successfully bought some time to implement server side storage. For others less reliant on localstorage and with a separate api domain, it could prove to be the entire solution for a frustrating edge case.</p><p><em>Do you want to learn more about opportunities with our team? Visit the </em><a href="http://bit.ly/WORK4GH"><em>Grubhub careers</em></a><em> page.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be0e5044aeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/grubhub-bytes/when-localstorage-fails-a-tale-of-cookies-and-crumbs-8be0e5044aeb">When Localstorage fails — a tale of cookies and crumbs</a> was originally published in <a href="https://medium.com/grubhub-bytes">Grubhub Bytes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>