<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Dylan Paulus&apos; Blog</title><description>Rambling on software.</description><link>https://dylanpaulus.com/</link><language>en-us</language><item><title>How to Use PostgreSQL for Data Normalization</title><link>https://dylanpaulus.com/posts/2024/how-to-use-postgres-for-data-normalization/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/how-to-use-postgres-for-data-normalization/</guid><pubDate>Fri, 20 Dec 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Managing a database is more than just storing information—it&apos;s about storing data efficiently, effectively, and balancing trade-offs. We can employ techniques like data normalization to optimize our data for maintainability and readability, or data denormalization to optimize for raw query speed. Data normalization is the process of breaking data down into structured tables to reduce duplication and make it easier to query and store by enforcing standardization.&lt;/p&gt;
&lt;p&gt;In this article, we&apos;ll take a look at what data normalization is, how to apply normal forms to achieve data normalization, challenges and tools for data normalization in PostgreSQL, tips on when to denormalize, and how TimescaleDB makes normalization easier.&lt;/p&gt;
</content:encoded></item><item><title>Resizing AWS Mac Volumes</title><link>https://dylanpaulus.com/posts/2024/resizing-mac-aws-volumes/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/resizing-mac-aws-volumes/</guid><pubDate>Tue, 03 Dec 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I recently ran into an issue with our Mac build machine in AWS, where the EC2 instance kept running out of disk space. It should be easy enough to bump the EBS volume size and call it a day. Wrong. No matter what I changed the volume size to, the Mac instance would not recognize the new space. What gives?&lt;br /&gt;
After some digging, I found that Mac requires us to resize the OS APFS (Apple File System) container after providing the volume with more space. Let’s walk through, from the start, how to increase the size of an EBS volume on a Mac AWS instance.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Increase EBS Volume Size&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In the EC2, under Instances, select the instance that needs the volume resized.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./ec2-dashboard.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Once inside the instance, select &lt;em&gt;Storage&lt;/em&gt; and the volume that needs to be resized.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./ec2-storage-section.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Then, with the volume selected, choose &lt;em&gt;Modify Volume&lt;/em&gt; from the &lt;em&gt;Actions&lt;/em&gt; dropdown.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./modify-volume-dash.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Update &lt;em&gt;Size&lt;/em&gt; to be the new desired size of the volume.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./modify-volume.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;After the volume has been resized, we need to reboot the EC2 instance. Navigate back to the instance dashboard and select &lt;em&gt;Instance State&lt;/em&gt; &amp;gt; &lt;em&gt;Reboot instance&lt;/em&gt;.&lt;br /&gt;
This may take some time for the instance to fully reboot.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./reboot.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;But once the instance is back up and in a healthy state, connect into the instance by going into the instance dashboard and selecting &lt;em&gt;Connect&lt;/em&gt;.&lt;br /&gt;
Use whichever method you prefer to connect to the instance.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./connect.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now we can see how much disk space this instance has. To do this run &lt;code&gt;df -h&lt;/code&gt; or &lt;em&gt;diskutil&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;diskutil list external physical
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./show-space.png&quot; alt=&quot;Output running &quot; /&gt;&lt;/p&gt;
&lt;p&gt;At this point you will notice that even though the volume has been increased, the OS has not recognized the new space. &lt;code&gt;diskutil&lt;/code&gt; and &lt;code&gt;df&lt;/code&gt; is showing the old volume size.&lt;br /&gt;
The Apple file system doesn&apos;t expand automatically to fill the new space to avoid potential data loss, and provide users control over the space on the system.&lt;/p&gt;
&lt;p&gt;To expand APFS use the new space run the following commands:&lt;/p&gt;
&lt;p&gt;First, repair the disk to fix and prevent any potential problems:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PDISK=$(diskutil list physical external | head -n 1 | cut -d &quot; &quot; -f 1)
yes | sudo diskutil repairDisk $PDISK
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, resize the APFS container to take advantage of the new space:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;APFSCONT=$(diskutil list physical external | grep &quot;Apple_APFS&quot; | tr -s &quot; &quot; | cut -d &quot; &quot; -f 8)
sudo diskutil apfs resizeContainer $APFSCONT 0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After running the above commands, you will see the new space reflected by again running &lt;code&gt;df -h&lt;/code&gt; or &lt;code&gt;diskutil list external physical&lt;/code&gt;!&lt;/p&gt;
</content:encoded></item><item><title>Recursive Query in SQL: What It Is, and How to Write One</title><link>https://dylanpaulus.com/posts/2024/recursive-query-in-sql-what-it-is-and-how-to-write-one/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/recursive-query-in-sql-what-it-is-and-how-to-write-one/</guid><pubDate>Mon, 04 Nov 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;As developers, querying in PostgreSQL for hierarchical data is difficult. SQL is a declarative programming language, but our brains are trained to think imperatively. Recursive queries using Common Table Expressions (CTE) simplify writing iterative queries and are essential in traversing hierarchical data, like tree or graph structures.&lt;/p&gt;
&lt;p&gt;Throughout this article, we&apos;ll explore SQL recursive queries with examples, look at optimizing recursive queries, and discuss advanced techniques.&lt;/p&gt;
</content:encoded></item><item><title>Understanding SQL Aggregate Functions</title><link>https://dylanpaulus.com/posts/2024/understanding-sql-aggregate-functions/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/understanding-sql-aggregate-functions/</guid><pubDate>Mon, 28 Oct 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;You may have heard that &quot;data is the new oil.&quot; By itself, data is unrefined and not valuable, but given processing and refinement, it becomes precious. We gain insights into our products, applications, and customers by exploring our data. PostgreSQL exposes aggregate functions that give us the tools to transform and process our data to provide meaning.&lt;/p&gt;
&lt;p&gt;In this article, we&apos;ll take a look at how to use SQL aggregate functions, the pitfalls, and how Timescale gives us advanced tooling to aggregate time-series data.&lt;/p&gt;
</content:encoded></item><item><title>Understanding Foreign Keys in PostgreSQL</title><link>https://dylanpaulus.com/posts/2024/understanding-postgres-foreign-keys/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/understanding-postgres-foreign-keys/</guid><pubDate>Sat, 28 Sep 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Foreign keys in PostgreSQL are a fundamental way of defining relationships between tables. Splitting data across multiple tables is foundational to relational databases and data normalization. However, when spreading related data across various tables, we must ensure that values in one table are valid and exist in another. Enter foreign keys.&lt;/p&gt;
</content:encoded></item><item><title>Explaining PostgreSQL EXPLAIN</title><link>https://dylanpaulus.com/posts/2024/explaining-postgresql-explain/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/explaining-postgresql-explain/</guid><pubDate>Tue, 30 Jul 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;EXPLAIN is a command we prepend to queries to tell us what operations PostgreSQL plans to run for that query, how many rows each operation touches in the database(s), and how long those operations take. EXPLAIN is the go-to performance diagnostic tool for discovering what is causing a query to run slowly.&lt;/p&gt;
</content:encoded></item><item><title>PostgreSQL Security Guide</title><link>https://dylanpaulus.com/posts/2024/postgres-security-guide/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/postgres-security-guide/</guid><pubDate>Thu, 04 Apr 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Databases store an application&apos;s most valuable asset: data. This data includes personal information like names, passwords, and street addresses, but it could also include company secrets. Having an insecure database is devastating for a few reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Leaking personal data erodes trust from users and customers&lt;/li&gt;
&lt;li&gt;Falling share prices or loss of revenue&lt;/li&gt;
&lt;li&gt;You can be hit with regulatory penalties (e.g., GDPR)&lt;/li&gt;
&lt;li&gt;In specific sectors, vulnerabilities can be used to cause physical harm&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>How to Use a Common Table Expression (CTE) in SQL</title><link>https://dylanpaulus.com/posts/2024/common-table-expressions-in-sql/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/common-table-expressions-in-sql/</guid><pubDate>Sat, 09 Mar 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Common Table Expressions (CTEs) are my go-to tool when writing complex SQL queries. They can be thought of as working like sub-queries or temporary tables but with their own superpowers.&lt;/p&gt;
&lt;p&gt;In this article, we&apos;ll take a deep dive into what CTEs are and how they can simplify your queries, how recursive CTES can turn impossible PostgreSQL queries into possible, and how to use CTEs to create optimization fences to improve the performance of your queries.&lt;/p&gt;
</content:encoded></item><item><title>Understanding PostgreSQL Tablespaces</title><link>https://dylanpaulus.com/posts/2024/understanding-postgres-tablespaces/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/understanding-postgres-tablespaces/</guid><pubDate>Sun, 28 Jan 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Tablespaces are a PostgreSQL feature that gets easily overlooked but can provide substantial speed improvements and cost-saving potential. As our database grows, tablespaces become a powerful tool in our toolbelt.&lt;/p&gt;
</content:encoded></item><item><title>How to Design Your PostgreSQL Database: Two Schema Examples</title><link>https://dylanpaulus.com/posts/2024/how-to-design-postgres-database-schemas/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2024/how-to-design-postgres-database-schemas/</guid><pubDate>Tue, 02 Jan 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;How we design and lay out our tables is one of the most important decisions in developing effective and efficient PostgreSQL databases. A database schema is the architecture or structure of the data in our database. It defines what tables we&apos;ll have, columns, data types, naming, and relationships between tables.&lt;/p&gt;
</content:encoded></item><item><title>Creating a Fast Time-Series Graph With Postgres Materialized Views</title><link>https://dylanpaulus.com/posts/2023/creating-fast-time-series-graph-with-postgres/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/creating-fast-time-series-graph-with-postgres/</guid><pubDate>Mon, 27 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;Imagine you have a massive amount of time-series data you want to explore and visualize. Seeing the latest trends, the historical patterns, and the outliers in your data can help you gain insights and make decisions. But how do you visualize and analyze time-series data effectively? How do you create graphs, plots, and other visualizations for real-time analytics showing the current state of your data and the historical changes over different time intervals? And how do you do it efficiently without sacrificing performance or accuracy?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div&gt;
&lt;p&gt;In this article with Timescale we dive into practical examples of using materialized views and continuous aggregates to create fast, performant time-series graphs.&lt;/p&gt;
&lt;/div&gt;</content:encoded></item><item><title>Easily Generate Mock Data with PostgreSQL</title><link>https://dylanpaulus.com/posts/2023/easily-generate-mock-data-with-postgresql/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/easily-generate-mock-data-with-postgresql/</guid><pubDate>Thu, 09 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { Accordion } from &quot;../../../../components/Accordion&quot;;&lt;/p&gt;
&lt;p&gt;When writing articles about PostgreSQL there are times I need to generate large swaths of data to test and demonstrate a topic (for example, these Timescale articles &lt;a href=&quot;https://www.timescale.com/blog/how-to-reduce-your-postgresql-database-size/&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;https://www.timescale.com/learn/how-to-reduce-bloat-in-large-postgresql-tables/&quot;&gt;here&lt;/a&gt;).&lt;br /&gt;
It can be a pain to manually insert data or create a CSV and import it into PostgreSQL--which I always have to StackOverflow.&lt;br /&gt;
Lately, I ran into a much simpler solution to generating data: the &lt;code&gt;generate_series&lt;/code&gt; &lt;a href=&quot;https://www.postgresql.org/docs/current/functions-srf.html&quot;&gt;function&lt;/a&gt;.&lt;br /&gt;
It&apos;s perfectly suited for integers and timestamp data types, streamlining various tasks such as populating test databases or setting up date ranges for reports.&lt;/p&gt;
&lt;h2&gt;Generating Mock Data&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;generate_series&lt;/code&gt; can be thought of as a for-loop or generator to produce a range of numbers or dates.&lt;/p&gt;
&lt;p&gt;To generate a range of numbers, we call &lt;code&gt;generate_series&lt;/code&gt; with a start and end value:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT * FROM generate_series(1, 10);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./generate-int-example.png&quot; alt=&quot;The output showing ten rows of integers from one to ten&quot; /&gt;&lt;/p&gt;
&lt;p&gt;We can specify a step value by providing &lt;code&gt;generate_series&lt;/code&gt; as an optional third argument.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT * FROM generate_series(1, 10, 2.5);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./generate-float-example-step.png&quot; alt=&quot;The output with four rows showing 1, 3.5, 6.0, and 8.5 using 2.5 step between one and ten&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;Inserting Mock Data&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;generate_series&lt;/code&gt;&apos; power comes to fruition when we need to insert mock data into a table.&lt;br /&gt;
We can easily insert a range of numbers into a table by using &lt;code&gt;generate_series&lt;/code&gt; in a &lt;code&gt;SELECT&lt;/code&gt; statement and then inserting the results into a table.&lt;/p&gt;
&lt;p&gt;For the rest of this article, we&apos;ll use &lt;code&gt;users&lt;/code&gt; table that looks like this for our examples:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CREATE TABLE users (
 id serial PRIMARY KEY,
 name text NOT NULL,
 created_on timestamptz
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, if we wanted to insert five users into the table we could run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO users (name)
SELECT
    &apos;Dylan&apos;
FROM generate_series(1, 5);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./user-dylan-create.png&quot; alt=&quot;Five rows in the users table all with their name as Dylan&quot; /&gt;&lt;/p&gt;
&lt;p&gt;This pattern can be used to insert any number of rows into a table.&lt;br /&gt;
If you&apos;re feeling brave, try inserting 1,000,000 users into the table by changing &lt;code&gt;generate_series(1, 5)&lt;/code&gt; to &lt;code&gt;generate_series(1, 1000000)&lt;/code&gt;!&lt;/p&gt;
&lt;p&gt;Up to this point we are creating a lot of duplicate data.&lt;br /&gt;
What if we wanted to create a bunch of users with all distinct names?&lt;br /&gt;
We can access the current index of the loop (using &lt;code&gt;as&lt;/code&gt;) to generate a unique name for each user.&lt;/p&gt;
&lt;p&gt;That would look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO users (name)
SELECT
    &apos;Dylan number &apos; || i
FROM generate_series(1, 5) as i;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./user-dylan-with-number.png&quot; alt=&quot;Five rows in the users table with names: Dylan number 1, Dylan, number 2, and so on until Dylan number 5&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Creating Time-Series Data&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;generate_series&lt;/code&gt; is incredibly effective at generating time series data.&lt;br /&gt;
This is where I get the most use out of it because it can become extremely tedious to create a lot of data around time ranges.&lt;/p&gt;
&lt;p&gt;Similar to the integer example, generate a range of timestamps by providing a start and end value followed by an optional step or interval.&lt;/p&gt;
&lt;p&gt;For example, to generate a user for every hour in a week, we could run the following SQL:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO users (name, created_on)
SELECT
    &apos;Dylan&apos;,
    time_hour
FROM generate_series(
    TIMESTAMPTZ &apos;2023-11-01&apos;,
    TIMESTAMPTZ &apos;2023-11-07&apos;,
    INTERVAL &apos;1 hour&apos;
) as time_hour;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./time-series-hour.png&quot; alt=&quot;Ten rows in the users table, each with the name Dylan and a created_on column for each hour between 2023-11-01 to 2023-11-07&quot; /&gt;&lt;/p&gt;
&lt;p&gt;This query creates 146 rows with a user named Dylan every hour between November 1st and November 7th, 2023.&lt;/p&gt;
&lt;p&gt;You may be asking yourself, can we use multiple &lt;code&gt;generate_series&lt;/code&gt; to populate multiple fields? Yes!&lt;br /&gt;
But, we need to use joins to combine the data from the two series.&lt;br /&gt;
To quickly create a grid of users and created_on dates we can take the cartesian product of two series, otherwise known as a cross join, by adding another &lt;code&gt;generate_series&lt;/code&gt; to the &lt;code&gt;FROM&lt;/code&gt; clause.&lt;/p&gt;

    A cartesian product is the result of joining two tables
    where the result is the combination of every row in the first table with every row in the second table.
&lt;pre&gt;&lt;code&gt;For example, let&apos;s say we have two pants (blue jeans and sweatpants) and three shirts (t-shirt, polo, and sweatshirt).

The cartesian product of our pants and shirts would look like:

| Pants       | Shirts      |
| ----------- | ----------- |
| Blue Jeans  | T-Shirt     |
| Blue Jeans  | Polo        |
| Blue Jeans  | Sweatshirt  |
| Sweatpants  | T-Shirt     |
| Sweatpants  | Polo        |
| Sweatpants  | Sweatshirt  |
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO users (name, created_on)
SELECT
    &apos;Dylan number&apos; || i,
    time_hour
FROM
    generate_series(1, 5) as i,
    generate_series(
        TIMESTAMPTZ &apos;2023-11-01&apos;,
        TIMESTAMPTZ &apos;2023-11-07&apos;,
        INTERVAL &apos;2 days&apos;
    ) as time_hour;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the &lt;code&gt;INSERT&lt;/code&gt; statement above, we&apos;ll create four &lt;code&gt;time_hour&lt;/code&gt; timestamps for every two days in the week for every iteration of &lt;code&gt;i&lt;/code&gt; (there are five of them).&lt;br /&gt;
Resulting in &lt;code&gt;4 * 5 = 20&lt;/code&gt; twenty rows created.&lt;br /&gt;
To better grasp what&apos;s happening here, it&apos;ll be easier to look at the &lt;code&gt;SELECT&lt;/code&gt; output of the users table.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./multiple-series.png&quot; alt=&quot;Twenty rows in the users tables showing a cross join between name and the created_on column&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Using multiple &lt;code&gt;generate_series&lt;/code&gt; functions combined with a cartesian product can be a powerful combination for creating unique, time-series data.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;PostgreSQL&apos;s &lt;code&gt;generate_series&lt;/code&gt; is a game-changer for developers like me, who frequently dive into the deep end of data generation for testing and optimizing queries. It&apos;s a powerhouse that can effortlessly create anything from a handful to millions of rows, transforming a potentially arduous task into a few simple lines of SQL.&lt;br /&gt;
So, when you need to mock up data, let &lt;code&gt;generate_series&lt;/code&gt; be your go-to solution.&lt;/p&gt;
&lt;p&gt;Happy data generating!&lt;/p&gt;
&lt;p&gt;Need a realistic dataset to test something more interesting than a flat table? &lt;a href=&quot;/posts/postgres-is-a-graph-database&quot;&gt;Postgres: The Graph Database You Didn&apos;t Know You Had&lt;/a&gt; uses &lt;code&gt;generate_series&lt;/code&gt; to populate nodes and edges, then walks through recursive CTEs against the same data. For performance work on bigger tables, &lt;a href=&quot;/posts/explaining-postgresql-explain&quot;&gt;Explaining PostgreSQL EXPLAIN&lt;/a&gt; covers how to read query plans once the rows pile up.&lt;/p&gt;
</content:encoded></item><item><title>Wrangling Table Bloat in Large PostgreSQL Tables</title><link>https://dylanpaulus.com/posts/2023/how-to-reduce-bloat-in-large-postgresql-tables/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/how-to-reduce-bloat-in-large-postgresql-tables/</guid><pubDate>Fri, 03 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I worked with &lt;a href=&quot;https://www.timescale.com/&quot;&gt;Timescale&lt;/a&gt; again to write an article on how table bloat effects large tables, and how we can fix it.&lt;/p&gt;
&lt;p&gt;We cover a range of topics including:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;What is table bloat?&lt;/li&gt;
  &lt;li&gt;Why is it an issue?&lt;/li&gt;
  &lt;li&gt;How to monitor table bloat?&lt;/li&gt;
  &lt;li&gt;What Vacuum and AutoVacuum is&lt;/li&gt;
  &lt;li&gt;Tips with tuning AutoVacuum&lt;/li&gt;
  &lt;li&gt;Table Partitioning&lt;/li&gt;
  &lt;li&gt;How Timescale chunks makes partitioning easier&lt;/li&gt;
  &lt;li&gt;And more!&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title>How to Reduce Your PostgreSQL Database Size</title><link>https://dylanpaulus.com/posts/2023/how-to-reduce-your-postgresql-database-size/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/how-to-reduce-your-postgresql-database-size/</guid><pubDate>Sat, 07 Oct 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I had the pleasure of working with &lt;a href=&quot;https://www.timescale.com/&quot;&gt;Timescale&lt;/a&gt; to&lt;br /&gt;
write an article on how to reduce your PostgreSQL database size.&lt;/p&gt;
&lt;p&gt;We cover a range of topics including:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;What are pages and tuples&lt;/li&gt;
  &lt;li&gt;How table bloat occurs&lt;/li&gt;
  &lt;li&gt;Why we should vacuum our tables&lt;/li&gt;
  &lt;li&gt;Timescale compression&lt;/li&gt;
  &lt;li&gt;Retention policies&lt;/li&gt;
  &lt;li&gt;And more!&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title>Unraveling Graph Structures: Exploring Adjacency Matrices</title><link>https://dylanpaulus.com/posts/2023/exploring-adjacency-lists-and-matrices/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/exploring-adjacency-lists-and-matrices/</guid><pubDate>Wed, 19 Jul 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { Image } from &quot;astro:assets&quot;;&lt;br /&gt;
import baseGraph from &quot;./base_graph.svg&quot;;&lt;br /&gt;
import table from &quot;./table.svg&quot;;&lt;br /&gt;
import unidirect from &quot;./unidirect.svg&quot;;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&quot;/posts/postgres-is-a-graph-database&quot;&gt;Postgres: The Graph Database You Didn&apos;t Know You Had&lt;/a&gt; we covered how we can store a DAG (Directed Acyclic Graph) in a relational database.&lt;br /&gt;
We looked at one representation of a graph data structure called an adjacency list--a table with two columns representing how nodes connect.&lt;br /&gt;
The columns store connections from the &lt;em&gt;source&lt;/em&gt; or &lt;em&gt;&quot;from&quot;&lt;/em&gt; node to a &lt;em&gt;destination&lt;/em&gt; or &lt;em&gt;&quot;to&quot;&lt;/em&gt; node.&lt;/p&gt;
&lt;div&gt;
&lt;section&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;strong&gt;Our Graph&lt;/strong&gt;
            
        &lt;/div&gt;
&lt;pre&gt;&lt;code&gt;    &amp;lt;div class=&quot;w-full lg:w-1/2 mt-16 lg:mt-0 mx-auto&quot;&amp;gt;
        &amp;lt;strong&amp;gt;Adjacency List&amp;lt;/strong&amp;gt;
        &amp;lt;table class=&quot;w-full mx-auto&quot;&amp;gt;
            &amp;lt;thead&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;th colspan=&quot;2&quot;&amp;gt;Edges&amp;lt;/th&amp;gt;
                &amp;lt;/tr&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;th&amp;gt;Source&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;Destination&amp;lt;/th&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;A&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;B&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;A&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;C&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;/section&gt;
&lt;p&gt;Using Python, a code representation would look like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Node:
    pass

A = Node()
B = Node()
C = Node()

adjacency_list = [
    { &quot;source&quot;: A, &quot;destination&quot;: B },
    { &quot;source&quot;: A, &quot;destination&quot;: C },
]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An adjacency list is a simple and efficient way to store graph data, but there are many more ways to represent graphs.&lt;br /&gt;
In this article, we&apos;ll explore one of these alternatives called the adjacency matrix.&lt;/p&gt;
&lt;h2&gt;Adjacency Matrix&lt;/h2&gt;
&lt;p&gt;An adjacency matrix is a table with a row and column for each node in the graph (or NxN matrix).&lt;br /&gt;
To represent the edges we store a 1 in a column for a connection and a 0 for no connection.&lt;br /&gt;
We will start out exploring how to represent DAG&apos;s as an adjacency matrix since we covered DAG&apos;s in the Postgres article.&lt;br /&gt;
To store &lt;em&gt;direction&lt;/em&gt; in an adjacency matrix the x-axis or rows represent the &quot;from&quot; or &quot;source&quot; node.&lt;br /&gt;
The y-axis represents the connection.&lt;br /&gt;
Using the same graph as above, the adjacency matrix would look like this:&lt;/p&gt;
&lt;div&gt;
&lt;section&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;strong&gt;Our Graph&lt;/strong&gt;
            
        &lt;/div&gt;
&lt;pre&gt;&lt;code&gt;    &amp;lt;div class=&quot;w-full lg:w-1/2 mt-16 lg:mt-0 mx-auto&quot;&amp;gt;
        &amp;lt;strong&amp;gt;Adjacency Matrix&amp;lt;/strong&amp;gt;
        &amp;lt;table class=&quot;w-full mx-auto&quot;&amp;gt;
            &amp;lt;thead&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;th&amp;gt;&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;A&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;B&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;C&amp;lt;/th&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
                &amp;lt;tr&amp;gt;

    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;A&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                &amp;lt;tr&amp;gt;
    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;B&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                    &amp;lt;tr&amp;gt;
    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;C&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;/section&gt;
&lt;pre&gt;&lt;code&gt;adjacency_matrix = [
  [0, 1, 1],
  [0, 0, 0],
  [0, 0, 0]
]
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;What about non-DAG graphs?&lt;/h3&gt;
&lt;p&gt;For undirected graphs, graphs where all connections are bidirectional, the setup is the same to create the adjacency matrix.&lt;br /&gt;
The only difference is our graph has no explicit &lt;em&gt;direction&lt;/em&gt;. If &lt;code&gt;A&lt;/code&gt; connects to &lt;code&gt;B&lt;/code&gt;, then &lt;code&gt;B&lt;/code&gt; also connects to &lt;code&gt;A&lt;/code&gt;.&lt;br /&gt;
Let&apos;s take our previous DAG graph, and remove the direction.&lt;/p&gt;
&lt;div&gt;
&lt;section&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;strong&gt;Our Graph&lt;/strong&gt;
            
        &lt;/div&gt;
&lt;pre&gt;&lt;code&gt;    &amp;lt;div class=&quot;w-full lg:w-1/2 mt-16 lg:mt-0 mx-auto&quot;&amp;gt;
        &amp;lt;strong&amp;gt;Adjacency Matrix&amp;lt;/strong&amp;gt;
        &amp;lt;table class=&quot;w-full mx-auto&quot;&amp;gt;
            &amp;lt;thead&amp;gt;
                &amp;lt;tr&amp;gt;
                    &amp;lt;th&amp;gt;&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;A&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;B&amp;lt;/th&amp;gt;
                    &amp;lt;th&amp;gt;C&amp;lt;/th&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
                &amp;lt;tr&amp;gt;

    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;A&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                &amp;lt;tr&amp;gt;
    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;B&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
                    &amp;lt;tr&amp;gt;
    &amp;lt;td class=&quot;bg-secondary-300&quot;&amp;gt;C&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;0&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;&lt;/section&gt;
&lt;p&gt;A cool property emerges from undirected graphs. Can you spot a pattern in the table above?&lt;br /&gt;
Draw a diagonal line from the top left of our matrix to the bottom right (sandwich square style) and fold the matrix along this line.&lt;/p&gt;
&lt;div&gt;
&lt;section&gt;
  &lt;div&gt;
    
  &lt;/div&gt;
&lt;/section&gt;
&lt;p&gt;The connections mirror each other across this line. Our matrix is considered &lt;a href=&quot;https://en.wikipedia.org/wiki/Symmetric_matrix&quot;&gt;symmetric&lt;/a&gt; when this occurs.&lt;br /&gt;
Symmetric matrices appear in all undirected graphs, but not DAGs!&lt;/p&gt;
&lt;h3&gt;This is great, but why would we use an Adjacency Matrix?&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Matrices are incredibly fast at checking if two nodes are connected&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Instead of having to loop through all the edges in an adjacency list to find if two nodes are connected, an adjacency matrix acts&lt;br /&gt;
as a hash table. In our example graph above, if we wanted to check if &lt;em&gt;A&lt;/em&gt; has an edge to &lt;em&gt;B&lt;/em&gt; it would be as simple as checking the &lt;code&gt;[B][A]&lt;/code&gt; position&lt;br /&gt;
in the matrix.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: Since we&apos;re working with DAG&apos;s and 2D arrays, the order we look up a connection is flipped: &lt;code&gt;[Destination][Source]&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;A = 0
B = 1

has_connection = adjacency_matrix[B][A]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Removing and adding a connection between nodes is similar and run in constant time.&lt;br /&gt;
Need to connect two nodes? Modify the position in the matrix to be &lt;code&gt;1&lt;/code&gt; (&lt;code&gt;adjacency_matrix[destiation][source] = 1&lt;/code&gt;).&lt;br /&gt;
What about deleting an edge? Update the value to be &lt;code&gt;0&lt;/code&gt; (&lt;code&gt;adjacency_matrix[destiation][source] = 0&lt;/code&gt;)!&lt;/p&gt;
&lt;h3&gt;Why would I not use an Adjacency Matrix?&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;They&apos;re huge!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If we look at an adjacency matrix we need to store every bit of information about the graph, the connected nodes (1&apos;s), and not connected nodes(0&apos;s).&lt;br /&gt;
Compared to an adjacency list which stores only the connections; adjacency matrices take up a lot of space!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It&apos;s expensive to add/remove nodes&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We talked about how adjacency matrices are fast at looking up, adding, and removing connections between nodes.&lt;br /&gt;
On the flip side, adjacency matrices are slow when adding or removing nodes from the graph.&lt;br /&gt;
To add a node we need to copy our matrix to a new matrix with an additional row and column(of size N+1 x N+1).&lt;br /&gt;
Then, populate the matrix with the connections to or from the new node.&lt;br /&gt;
To compare, adding a new node to an adjacency list is a matter of pushing a new node to the list of nodes.&lt;/p&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;There are many different ways to represent and visualize a graph.&lt;br /&gt;
A different representation may be better based on your personal use cases and requirements.&lt;br /&gt;
Need to quickly look up which nodes are connected or need to quickly add or remove edges? Then the adjacency matrix may be the best choice.&lt;br /&gt;
Are you constantly adding nodes to the graph and are limited in your memory footprint? The adjacency list is the representation for you!&lt;/p&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><title>Improve Your Prompts for LLMs: Simple and Effective Techniques</title><link>https://dylanpaulus.com/posts/2023/improve-your-prompts-llms/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/improve-your-prompts-llms/</guid><pubDate>Wed, 07 Jun 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { Prompt } from &quot;./prompt&quot;;&lt;/p&gt;
&lt;p&gt;Tools like ChatGPT and Bing have been skyrocketing in popularity.&lt;br /&gt;
ChatGPT took five days since launch to &lt;a href=&quot;https://twitter.com/rauchg/status/1655950701951082497?s=20&quot;&gt;reach 1 million users&lt;/a&gt;.&lt;br /&gt;
Governments all over the world are trying to &lt;a href=&quot;https://www.asahi.com/ajw/articles/14903078&quot;&gt;figure out&lt;/a&gt; what to do &lt;a href=&quot;https://www.bbc.com/news/technology-65139406&quot;&gt;with this technology&lt;/a&gt;.&lt;br /&gt;
Sweet &lt;a href=&quot;https://www.theguardian.com/technology/2022/nov/12/when-ai-can-make-art-what-does-it-mean-for-creativity-dall-e-midjourney&quot;&gt;AI-generated images&lt;/a&gt; are showing up everywhere; like this dog I generated using Bing:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./dog-fire.jpeg&quot; alt=&quot;AI-generated picture of a astronaut dog jumping over a fire on the moon&quot; /&gt;&lt;/p&gt;
&lt;figcaption&gt;
  &quot;Can you generate a picture of an astronaut dog jumping over a fire on the
  moon?&quot;
&lt;/figcaption&gt;
&lt;p&gt;Though LLMs (Large Language Models) are still in their infancy, research has shown some &lt;a href=&quot;https://www.oneusefulthing.org/p/secret-cyborgs-the-present-disruption&quot;&gt;pretty big productivity boosts&lt;/a&gt; in a range of different professions.&lt;br /&gt;
Using metrics from Github Copilot, an AI-based coding tool, Github has found that developers &lt;a href=&quot;https://github.blog/2022-09-07-research-quantifying-github-copilots-impact-on-developer-productivity-and-happiness/&quot;&gt;complete tasks in 55% less time when taking advantage of AI&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is all to say that LLMs are a tool we&apos;ll need to learn to use and &lt;em&gt;use well&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;There are many options when choosing a LLM, with the most popular being ChatGPT and Bing.&lt;br /&gt;
OpenAI&apos;s &lt;a href=&quot;https://chat.openai.com/&quot;&gt;ChatGPT&lt;/a&gt; is the most well-known, but if we want to use the latest features like ChatGPT-4 (an upgrade to ChatGPT-3) we&apos;ll need to pay $20 a month.&lt;br /&gt;
Microsoft has released new &lt;a href=&quot;https://www.bing.com/new&quot;&gt;Bing&lt;/a&gt; that takes advantage of ChatGPT-4 behind the scenes and is free to use.&lt;br /&gt;
Finally, Google has &lt;a href=&quot;https://bard.google.com/&quot;&gt;Bard&lt;/a&gt; which is also free to use.&lt;br /&gt;
All offerings come with their unique pros and cons.&lt;/p&gt;
&lt;p&gt;Regardless of which tool you use, the question remains: how do we get the most out of these tools?&lt;/p&gt;
&lt;h2&gt;Prompt Engineering&lt;/h2&gt;
&lt;p&gt;We interact with LLMs by giving them a prompt, or text input, generally in the form of a question or instruction.&lt;br /&gt;
LLMs then reason out the answer and respond.&lt;br /&gt;
Prompt Engineering is a term coined to describe the process of writing prompts to get the best results from LLMs.&lt;br /&gt;
Just like in everyday conversation, the words we choose to ask in a question can dramatically change the response we get.&lt;br /&gt;
For example, if I ask “What is the best way to get to the airport?” I’ll get a different response than asking “How do I get to the airport?“.&lt;/p&gt;
&lt;p&gt;Throughout this article we’ll build on a prompt to create a meal plan for a single day; taking advantage of different Prompt Engineering techniques.&lt;br /&gt;
I’ll provide the prompt used, and the response I got back from the LLM—in my case I’ll be using ChatGPT-3.&lt;br /&gt;
Try it for yourself, but remember that the results will vary by the LLM being used.&lt;/p&gt;
&lt;section&gt;
&lt;div&gt;

  Please create me a low sugar meal plan for one day.


**Low-Sugar Meal Plan for One Day**
&lt;p&gt;&lt;strong&gt;Breakfast&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Scrambled eggs with vegetables (spinach, bell peppers, mushrooms)&lt;/li&gt;
&lt;li&gt;Whole grain toast&lt;/li&gt;
&lt;li&gt;A small serving of fresh berries (such as strawberries or blueberries)&lt;/li&gt;
&lt;li&gt;Herbal tea or black coffee (unsweetened)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Greek yogurt with a sprinkle of cinnamon&lt;/li&gt;
&lt;li&gt;A handful of unsalted almonds&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Lunch&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Grilled chicken breast&lt;/li&gt;
&lt;li&gt;Mixed greens salad with cherry tomatoes, cucumber, and avocado&lt;/li&gt;
&lt;li&gt;Olive oil and lemon juice dressing (no added sugar)&lt;/li&gt;
&lt;li&gt;Steamed broccoli&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sliced cucumber and carrot sticks with hummus&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Baked salmon fillet with lemon and dill&lt;/li&gt;
&lt;li&gt;Quinoa pilaf with mixed vegetables (broccoli, carrots, peas)&lt;/li&gt;
&lt;li&gt;Steamed asparagus&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dessert&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Fresh fruit salad (such as watermelon, cantaloupe, and kiwi)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; Remember to drink plenty of water throughout the day.&lt;br /&gt;
Adjust portion sizes according to your specific dietary needs and consult with&lt;br /&gt;
a healthcare professional or a registered dietitian for personalized advice.&lt;/p&gt;
  
  &lt;/div&gt;
  &lt;/section&gt;
&lt;h3&gt;Constraints&lt;/h3&gt;
&lt;p&gt;Just like people, LLMs need constraints and clarity to understand what&apos;s being asking.&lt;br /&gt;
Be specific when writing prompts, and have a desired outcome in mind.&lt;br /&gt;
The best mental model I&apos;ve been told is to think of LLMs as an intern, brand new to the job.&lt;br /&gt;
They are eager to get stuff done, but need clear and direct instructions.&lt;br /&gt;
The best way to get the best results out of LLMs is to be specific.&lt;/p&gt;
&lt;p&gt;Let&apos;s improve upon our prompt by adding some constraints.&lt;/p&gt;
&lt;section&gt;
&lt;div&gt;

  Please create me a low sugar meal plan for one day. The plan should be a
  maximum 1,800 calories, and do not include breakfast. No gluten. High in
  protein.


**Low-Sugar, Gluten-Free, High-Protein Meal Plan for One Day**
&lt;p&gt;&lt;strong&gt;Lunch&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Grilled chicken breast (4 oz)&lt;/li&gt;
&lt;li&gt;Quinoa salad with mixed vegetables (cucumber, cherry tomatoes, bell peppers)&lt;br /&gt;
dressed with lemon vinaigrette&lt;/li&gt;
&lt;li&gt;Steamed broccoli (1 cup)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Greek yogurt (6 oz) with sliced almonds (1 tbsp) and a sprinkle of cinnamon&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Baked salmon fillet (4 oz) with garlic and herbs&lt;/li&gt;
&lt;li&gt;Sautéed kale (1 cup) with garlic and olive oil&lt;/li&gt;
&lt;li&gt;Roasted sweet potatoes (1 medium) with a sprinkle of paprika&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Celery sticks with almond butter (2 tbsp)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dessert&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Mixed berries (1 cup) with a dollop of unsweetened whipped cream&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; Please note that portion sizes and specific calorie counts may&lt;br /&gt;
vary depending on the size and brand of the ingredients used. Adjust the&lt;br /&gt;
portion sizes and consult a healthcare professional or a registered&lt;br /&gt;
dietitian for any specific dietary needs or concerns.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;/div&gt;
&lt;/section&gt;
&lt;h3&gt;Role prompting, or &quot;Act like a...&quot;&lt;/h3&gt;
&lt;p&gt;Role Prompting or &quot;Act like a ...&quot; is a technique that can be used to provide more context and constraints to LLMs.&lt;br /&gt;
First we tell the LLM to assume a role or persona. Then we provide a prompt.&lt;br /&gt;
For example, if we had a question about woodworking we might say, &lt;code&gt;&quot;Act like a master woodworker. What is the best way to cut a dovetail joint?&quot;&lt;/code&gt;.&lt;br /&gt;
Role prompting is another great way to provide constraints to LLMs.&lt;/p&gt;
&lt;p&gt;Let&apos;s improve upon our meal plan prompt by adding a role.&lt;/p&gt;
&lt;section&gt;
&lt;div&gt;

  Act as an expert nutritionist with 20 years of experience. Please create me a
  low sugar meal plan for one day. The plan should be a maximum 1,800 calories,
  and do not include breakfast. No gluten. High in protein.


**Low Sugar Meal Plan**
&lt;p&gt;&lt;strong&gt;Maximum 1,800 Calories | No Gluten | High in Protein&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lunch&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Grilled chicken breast (4 oz) seasoned with herbs and spices&lt;/li&gt;
&lt;li&gt;Quinoa salad with mixed vegetables (such as bell peppers, cucumbers, and cherry&lt;br /&gt;
tomatoes) dressed with lemon juice and olive oil&lt;/li&gt;
&lt;li&gt;Steamed broccoli (1 cup) -&lt;br /&gt;
Mixed greens salad with avocado slices and a light vinaigrette dressing&lt;/li&gt;
&lt;li&gt;Sparkling water with a squeeze of fresh lemon&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Greek yogurt (6 oz) topped with mixed berries (such as strawberries and&lt;br /&gt;
blueberries)&lt;/li&gt;
&lt;li&gt;Handful of unsalted almonds&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Baked salmon fillet (4 oz) marinated in a mix of lemon juice, garlic, and dill&lt;/li&gt;
&lt;li&gt;Roasted Brussels sprouts with garlic and olive oil (1 cup)&lt;/li&gt;
&lt;li&gt;Steamed asparagus (1 cup)&lt;/li&gt;
&lt;li&gt;Quinoa (1/2 cup) cooked with vegetable broth&lt;/li&gt;
&lt;li&gt;Herbal tea or water with a slice of lemon&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Evening Snack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Celery sticks and carrot sticks with hummus&lt;/li&gt;
&lt;li&gt;Green tea or water&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This meal plan is designed to be low in added sugars and gluten-free while&lt;br /&gt;
providing ample protein from lean sources like chicken, fish, and Greek&lt;br /&gt;
yogurt. It incorporates a variety of colorful vegetables, healthy fats from&lt;br /&gt;
avocado and olive oil, and whole grains like quinoa for additional fiber.&lt;br /&gt;
Remember to drink plenty of water throughout the day to stay hydrated.&lt;/p&gt;
&lt;p&gt;Please note that this is a generalized meal plan, and it&apos;s always a good idea to consult with a registered dietitian or nutritionist who can create a personalized meal plan based on your specific dietary needs and health goals.&lt;/p&gt;
  
  &lt;/div&gt;
  &lt;/section&gt;
&lt;h3&gt;Few shot prompting&lt;/h3&gt;
&lt;p&gt;Few shot prompting is my favorite technique, and can really take the performance of LLMs to the next level.&lt;br /&gt;
First we provide the LLM with a few examples (or shots) of what we want, and then we ask the LLM to generate a similar response (furthering adding constraints to our prompt).&lt;br /&gt;
The term &quot;shot&quot; is synonymous with &quot;example&quot;. In Pompt Engineering you will also find zero shot prompting and one shot prompting.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Zero Shot Prompting:&lt;/strong&gt; No examples are provided&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One Shot Prompting:&lt;/strong&gt; One example is provided&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Few Shot Prompting:&lt;/strong&gt; Two or more examples are provided&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The shots, or examples, can be given in the same prompt, or broken out into separate prompts.&lt;/p&gt;
&lt;p&gt;For example, in our meal plan example we could ask the LLM in a single prompt:&lt;/p&gt;
&lt;section&gt;
&lt;div&gt;

Use the following examples of a meal plan:
&lt;p&gt;&lt;strong&gt;example 1:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Breakfast (364 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Egg &amp;amp; Avocado Toast with Spinach &amp;amp; Salsa&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;A.M. Snack (59 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 medium peach&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Lunch (584 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Hot Turkey Pesto Sandwich&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;P.M. Snack (200 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 cup edamame in pods&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner (306 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving One-Pot Lentil &amp;amp; Vegetable Soup with Parmesan&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Daily Totals: 1,512 calories, 65g fat, 93g protein, 140g carbohydrate, 34g fiber, 1,538mg sodium&lt;/p&gt;
&lt;p&gt;To make it 1,200 calories: Omit the morning and afternoon snacks and reduce the pesto from 1 Tbsp. to 1 tsp. on the sandwich at lunch.&lt;/p&gt;
&lt;p&gt;To make it 2,000 calories: Add 1/2 cup unsalted roasted cashews to A.M. snack and increase to 1 1/2 cups edamame at P.M. snack.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;example 2:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Breakfast (302 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Copycat Spinach and Mushroom Egg Bites&lt;/li&gt;
&lt;li&gt;1 slice whole-wheat bread&lt;/li&gt;
&lt;li&gt;1 1/4 cups sliced strawberries&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;A.M. Snack (315 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 medium banana&lt;/li&gt;
&lt;li&gt;2 Tbsp. creamy natural peanut butter&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Lunch (306 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving One-Pot Lentil &amp;amp; Vegetable Soup with Parmesan&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;P.M. Snack (247 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;32 unsalted dry-roasted almonds&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner (349 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Chicken, Quinoa &amp;amp; Sweet Potato Casserole&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Daily Totals: 1,518 calories, 67g fat, 75g protein, 158g carbohydrate, 31g fiber, 1,482mg sodium&lt;/p&gt;
&lt;p&gt;To make it 1,200 calories: Omit peanut butter at A.M. snack and reduce almonds to 18 at P.M. snack.&lt;/p&gt;
&lt;p&gt;To make it 2,000 calories: Increase to 2 slices bread and 1 1/2 cups strawberries at breakfast, increase peanut butter to 1/4 cup at A.M. snack, and increase almonds to 1/2 cup at P.M. snack.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Act as an expert nutritionist with 20 years of experience. Please create me a&lt;br /&gt;
low sugar meal plan for one day. The plan should be a maximum 1,800 calories,&lt;br /&gt;
and do not include breakfast. No gluten. High in protein.&lt;/p&gt;

&lt;/div&gt;
&lt;/section&gt;
&lt;p&gt;Or ask the LLM to read a few examples first before we ask our question.&lt;br /&gt;
To reduce the amount of time needed for the LLM to repond, we can ask it to confirm once it has read the example.&lt;/p&gt;
&lt;section&gt;
&lt;div&gt;
&lt;div&gt;

Read the following meal plan and respond with, &quot;yes&quot; once you read it.
&lt;p&gt;&lt;strong&gt;Breakfast (364 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Egg &amp;amp; Avocado Toast with Spinach &amp;amp; Salsa&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;A.M. Snack (59 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 medium peach&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Lunch (584 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Hot Turkey Pesto Sandwich&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;P.M. Snack (200 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 cup edamame in pods&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner (306 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving One-Pot Lentil &amp;amp; Vegetable Soup with Parmesan&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Daily Totals: 1,512 calories, 65g fat, 93g protein, 140g carbohydrate, 34g fiber, 1,538mg sodium&lt;/p&gt;
&lt;p&gt;To make it 1,200 calories: Omit the morning and afternoon snacks and reduce the pesto from 1 Tbsp. to 1 tsp. on the sandwich at lunch.&lt;/p&gt;
&lt;p&gt;To make it 2,000 calories: Add 1/2 cup unsalted roasted cashews to A.M. snack and increase to 1 1/2 cups edamame at P.M. snack.&lt;/p&gt;


Read the following meal plan and respond with, &quot;yes&quot; once you read it.
&lt;p&gt;&lt;strong&gt;Breakfast (302 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Copycat Spinach and Mushroom Egg Bites&lt;/li&gt;
&lt;li&gt;1 slice whole-wheat bread&lt;/li&gt;
&lt;li&gt;1 1/4 cups sliced strawberries&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;A.M. Snack (315 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 medium banana&lt;/li&gt;
&lt;li&gt;2 Tbsp. creamy natural peanut butter&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Lunch (306 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving One-Pot Lentil &amp;amp; Vegetable Soup with Parmesan&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;P.M. Snack (247 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;32 unsalted dry-roasted almonds&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner (349 calories)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1 serving Chicken, Quinoa &amp;amp; Sweet Potato Casserole&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Daily Totals: 1,518 calories, 67g fat, 75g protein, 158g carbohydrate, 31g fiber, 1,482mg sodium&lt;/p&gt;
&lt;p&gt;To make it 1,200 calories: Omit peanut butter at A.M. snack and reduce almonds to 18 at P.M. snack.&lt;/p&gt;
&lt;p&gt;To make it 2,000 calories: Increase to 2 slices bread and 1 1/2 cups strawberries at breakfast, increase peanut butter to 1/4 cup at A.M. snack, and increase almonds to 1/2 cup at P.M. snack.&lt;/p&gt;


Using the meal plan examples from before act as an expert nutritionist with 20 years of experience. Please create me a
low sugar meal plan for one day. The plan should be a maximum 1,800 calories,
and do not include breakfast. No gluten. High in protein.

&lt;/div&gt;

As an expert nutritionist with 20 years of experience, I&apos;ve created a low-sugar meal plan for one day that is gluten-free, 
high in protein, and falls within the maximum 1,800 calorie range. 
Please note that individual nutritional needs may vary, so it&apos;s always a good idea to consult with a healthcare professional or registered dietitian for personalized advice. Here&apos;s the meal plan:
&lt;p&gt;&lt;strong&gt;Lunch (approximately 400-500 calories):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Grilled Chicken Salad with Avocado Dressing:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;4-6 ounces of grilled chicken breast&lt;/li&gt;
&lt;li&gt;Mixed salad greens (spinach, arugula, or your preferred greens)&lt;/li&gt;
&lt;li&gt;Sliced cucumber, cherry tomatoes, and red onion&lt;/li&gt;
&lt;li&gt;1/4 avocado, sliced&lt;/li&gt;
&lt;li&gt;1-2 tablespoons of homemade avocado dressing (made with avocado, lemon juice, olive oil, salt, and pepper)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Afternoon Snack (approximately 150 calories):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Greek Yogurt Parfait:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;1/2 cup of plain Greek yogurt&lt;/li&gt;
&lt;li&gt;1/4 cup of mixed berries (such as blueberries and raspberries)&lt;/li&gt;
&lt;li&gt;1 tablespoon of chopped nuts (almonds, walnuts, or your preference)&lt;/li&gt;
&lt;li&gt;Optional: sprinkle of cinnamon or drizzle of honey (if desired)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Dinner (approximately 500-600 calories):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Baked Salmon with Quinoa and Roasted Vegetables:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;4-6 ounces of baked or grilled salmon fillet&lt;/li&gt;
&lt;li&gt;1/2 cup of cooked quinoa&lt;/li&gt;
&lt;li&gt;Roasted vegetables of your choice (such as broccoli, bell peppers, and zucchini) seasoned with herbs and olive oil&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Evening Snack (approximately 150-200 calories):&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Celery with Almond Butter and Chia Seeds:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;2-3 celery stalks&lt;/li&gt;
&lt;li&gt;1-2 tablespoons of almond butter (make sure it&apos;s free of added sugars)&lt;/li&gt;
&lt;li&gt;Sprinkle of chia seeds for added fiber and healthy fats&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Remember to drink plenty of water throughout the day and adjust portion sizes based on your individual needs and preferences.&lt;br /&gt;
It&apos;s also essential to include regular physical activity and maintain a balanced overall diet for optimal health.&lt;/p&gt;

&lt;/div&gt;
&lt;/section&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Compare the first meal plan to the final result. After taking advantage of the prompt engineering techniques we learned, we can see that the last meal plan is much more specific, detailed, and closer to the answer we would expect!&lt;/p&gt;
&lt;p&gt;Using constraints, role prompting, and shot prompting, we can improve the quality of our prompts, impress our friends, and increase our productivity.&lt;/p&gt;
</content:encoded></item><item><title>Faster and Easier Python Debugging with breakpoint() and PDB</title><link>https://dylanpaulus.com/posts/2023/debugging-using-python/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/debugging-using-python/</guid><pubDate>Mon, 08 May 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Debugging is an essential skill for any software developer.&lt;br /&gt;
It allows us to find and fix errors in our code, improve quality and performance, and learn from our mistakes.&lt;/p&gt;
&lt;p&gt;One of the most common and powerful tools for debugging Python code is the &lt;a href=&quot;https://docs.python.org/3/library/pdb.html&quot;&gt;Python Debugger (PDB)&lt;/a&gt;.&lt;br /&gt;
PDB is a module that provides an interactive command-line interface for inspecting and manipulating the state of a running program.&lt;br /&gt;
With PDB, we can set breakpoints, step through the code line by line, examine variables and expressions, modify values, and more.&lt;/p&gt;
&lt;p&gt;However, using PDB can also be cumbersome and tedious.&lt;br /&gt;
To invoke PDB, we need to import the pdb module and insert a &lt;code&gt;pdb.set_trace()&lt;/code&gt; statement in our code where we want to pause the execution and enter the debugger.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pdb

def add(a: int, b:int) -&amp;gt; int:
  pdb.set_trace()  # pause here and enter the debugger
  return a + b

print(add(1, 2))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means we have to modify our source code every time we want to debug it and remember to remove or comment out the pdb statements when we are done.&lt;br /&gt;
Moreover, if we want to use a different debugger than PDB, such as IPython or PuDB, we have to change the import statement and the function call accordingly.&lt;/p&gt;
&lt;p&gt;Fortunately, &lt;a href=&quot;https://peps.python.org/pep-0553/&quot;&gt;Python 3.7&lt;/a&gt; introduced a new built-in function that simplifies this process: &lt;code&gt;breakpoint()&lt;/code&gt;.&lt;br /&gt;
The &lt;code&gt;breakpoint()&lt;/code&gt; function is a convenient way to start a debugger at any point in our code without having to import anything or write debugger-specific code.&lt;br /&gt;
All we have to do is insert a &lt;code&gt;breakpoint()&lt;/code&gt; statement where we want to pause the execution and enter the debugger!&lt;/p&gt;
&lt;p&gt;In this article, we will learn what &lt;code&gt;breakpoint()&lt;/code&gt; is, how to use it with PDB and other debuggers, and how to change its behavior with environment variables.&lt;/p&gt;
&lt;h2&gt;Using breakpoint()&lt;/h2&gt;
&lt;p&gt;When using PDB, we need to learn a couple commands to interact with the debugger.&lt;br /&gt;
There is a long list of commands PDB gives us, but we only need to know a few of them to get started.&lt;br /&gt;
For example, if we want to print values we use the &lt;code&gt;p&lt;/code&gt; command.&lt;br /&gt;
If we want to execute the next line of code we use the &lt;code&gt;n&lt;/code&gt; or &lt;code&gt;next&lt;/code&gt; command.&lt;br /&gt;
To continue execution until the next breakpoint we use the &lt;code&gt;c&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; command.&lt;br /&gt;
Finally, the &lt;code&gt;l&lt;/code&gt; or &lt;code&gt;list&lt;/code&gt; command shows us the code around the current line we are debugging.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Command&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;p [variable_name]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Print the value of a expression.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;n&lt;/code&gt; or &lt;code&gt;next&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Continue execution until the next line in the current function is reached or it returns.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;s&lt;/code&gt; or &lt;code&gt;step&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Execute the current line, stop at the first possible occasion (either in a function that is called or in the current function).&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;c&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Continue execution, only stop when a breakpoint is encountered.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;l&lt;/code&gt; or &lt;code&gt;list&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;List source code for the current file.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;h&lt;/code&gt; or &lt;code&gt;help&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Prints a list of commands we can use with PDB.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Let&apos;s see how &lt;code&gt;breakpoint()&lt;/code&gt; works.&lt;br /&gt;
Below is a recursive function that calculates the factorial of a given number.&lt;br /&gt;
I&apos;ve added a &lt;code&gt;breakpoint()&lt;/code&gt; statement to the function so we can pause the execution and enter the debugger.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# main.py

def factorial(number: int) -&amp;gt; int:
  if number &amp;lt; 0:
    raise ValueError(&quot;`n` must be non-negative.&quot;)
  elif number &amp;lt;= 1:
    return 1
  else:
    breakpoint()  # pause here and enter the debugger
    return number * factorial(number - 1)


# factorial(5) is: 5 * 4 * 3 * 2 * 1 = 120
print(factorial(5))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we run this code, the program will stop at the &lt;code&gt;breakpoint()&lt;/code&gt; statement and launch the default debugger, which is PDB by default.&lt;br /&gt;
We can then use the PDB commands to inspect and manipulate the program state.&lt;/p&gt;

&lt;a href=&quot;https://replit.com/@DylanPaulus/factorial-breakpoint#main.py&quot; target=&quot;_blank&quot;&gt;
  Open in new window
&lt;/a&gt;
&lt;figcaption&gt;
&lt;ul&gt;
  Play with PDB by clicking green &quot;Run&quot; button near the top right of the
  code editor.
&lt;p&gt;If you want to navigate back to the code, click &quot;Show files&quot; at the top left&lt;br /&gt;
of the code editor and select &quot;main.py&quot;.&lt;/p&gt;
&lt;/ul&gt;
&lt;/figcaption&gt;
&lt;p&gt;We can see that &lt;code&gt;breakpoint()&lt;/code&gt; pauses the execution at the line where it is called.&lt;br /&gt;
By using the commands we learned above, we can inspect the program state (&lt;code&gt;p number&lt;/code&gt; to see the value of &lt;code&gt;n&lt;/code&gt;) and step through the code line by line (&lt;code&gt;s&lt;/code&gt;).&lt;/p&gt;
&lt;h2&gt;Changing the debugger behavior&lt;/h2&gt;
&lt;p&gt;One of the advantages of using &lt;code&gt;breakpoint()&lt;/code&gt; over &lt;code&gt;pdb.set_trace()&lt;/code&gt; is that we can switch to a different debugger at any time.&lt;br /&gt;
By setting the &lt;code&gt;PYTHONBREAKPOINT&lt;/code&gt; environment variable we can tell Python which debugger we would like to use.&lt;br /&gt;
For example, if we want to use IPython as our debugger, we can run:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ export PYTHONBREAKPOINT=IPython.core.debugger.set_trace
$ python3 main.py
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Another advantage of using &lt;code&gt;breakpoint()&lt;/code&gt; is that we can disable all breakpoints in our code by setting the &lt;code&gt;PYTHONBREAKPOINT&lt;/code&gt; environment variable to 0.&lt;br /&gt;
This is useful when we want to run our code without entering the debugger; without having to remove or comment out all the &lt;code&gt;breakpoint()&lt;/code&gt; statements.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ export PYTHONBREAKPOINT=0
$ python3 main.py
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;End&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;breakpoint()&lt;/code&gt; is a much needed improvement over &lt;code&gt;pdb.set_trace()&lt;/code&gt;!&lt;br /&gt;
It gives us the ability to quickly debug our code, and easily switch between different debuggers.&lt;/p&gt;
</content:encoded></item><item><title>Postgres: The Graph Database You Didn&apos;t Know You Had</title><link>https://dylanpaulus.com/posts/2023/postgres-is-a-graph-database/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/postgres-is-a-graph-database/</guid><pubDate>Tue, 28 Mar 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;PostgreSQL (Postgres), is a powerful relational database that can store a wide range of data types and data structures.&lt;br /&gt;
When it comes to storing graph data structures we might reach for a database marketed for that use case like Neo4J or Dgraph. Hold your horses!&lt;br /&gt;
While Postgres is not generally thought of when working with graph data structures, it is perfectly capable to store and query graph data efficiently.&lt;/p&gt;
&lt;h2&gt;Understanding Graph Data Structures&lt;/h2&gt;
&lt;p&gt;Before we introduce Postgres as a graph database we need to know what a graph data structure is.&lt;br /&gt;
A graph, or a graph data structure, is a collection of nodes and edges,&lt;br /&gt;
where each node represents an entity or &lt;em&gt;&quot;thing&quot;&lt;/em&gt;, and each edge represents the relationship between two nodes.&lt;/p&gt;
&lt;div&gt;
  
    
      
    
    
      
        
      
    
&lt;pre&gt;&lt;code&gt;&amp;lt;g
  stroke-linecap=&quot;round&quot;
  transform=&quot;translate(398 284) rotate(0 69.5 70.5)&quot;&amp;gt;
  &amp;lt;path
    d=&quot;M83.43 1.23 C93.23 2.08, 104.25 7.29, 112.17 13.41 C120.08 19.53, 126.57 28.93, 130.91 37.96 C135.26 46.99, 137.88 57.39, 138.24 67.6 C138.59 77.82, 137.09 89.73, 133.03 99.23 C128.97 108.73, 121.58 118.15, 113.87 124.6 C106.16 131.06, 96.49 135.31, 86.76 137.97 C77.03 140.64, 65.19 142.3, 55.48 140.59 C45.78 138.88, 36.62 134.12, 28.52 127.7 C20.42 121.28, 11.8 111.36, 6.9 102.06 C1.99 92.76, -0.65 82.01, -0.93 71.91 C-1.2 61.81, 0.91 50.75, 5.23 41.48 C9.54 32.22, 17.07 22.98, 24.96 16.3 C32.85 9.63, 41.75 3.74, 52.58 1.43 C63.4 -0.87, 82.78 1.56, 89.9 2.49 C97.02 3.42, 95.73 5.89, 95.29 7.02 M63.98 1.05 C73.4 -0.84, 85.27 0.85, 94.81 4.48 C104.36 8.11, 114.42 15.3, 121.26 22.83 C128.1 30.35, 133.15 39.55, 135.85 49.62 C138.55 59.7, 139.24 73.18, 137.46 83.29 C135.68 93.4, 130.57 102.19, 125.14 110.28 C119.71 118.37, 113.5 126.68, 104.86 131.83 C96.22 136.97, 83.33 140.64, 73.28 141.14 C63.22 141.63, 53.7 138.46, 44.52 134.79 C35.35 131.11, 25.15 126.48, 18.25 119.09 C11.35 111.69, 6.16 100.5, 3.13 90.43 C0.1 80.36, -1.3 68.81, 0.07 58.65 C1.44 48.49, 5.24 37.69, 11.33 29.48 C17.43 21.26, 27.64 14.29, 36.64 9.36 C45.65 4.42, 60.78 1.06, 65.38 -0.13 C69.97 -1.32, 63.98 1.22, 64.21 2.23&quot;
    stroke-width=&quot;1&quot;
    &amp;gt;&amp;lt;/path&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g
  stroke-linecap=&quot;round&quot;
  transform=&quot;translate(255 590) rotate(0 69.5 70.5)&quot;&amp;gt;
  &amp;lt;path
    d=&quot;M50.22 2.43 C58.78 -1.42, 69.79 -1.29, 79.71 0.31 C89.64 1.9, 101.36 5.96, 109.78 11.99 C118.21 18.02, 125.27 27.46, 130.28 36.5 C135.29 45.54, 139.35 56.17, 139.84 66.25 C140.33 76.32, 137.01 87.51, 133.19 96.96 C129.38 106.4, 124.17 116.21, 116.95 122.9 C109.74 129.6, 99.76 134.2, 89.9 137.14 C80.04 140.08, 67.65 142.15, 57.78 140.53 C47.9 138.92, 38.75 133.23, 30.66 127.43 C22.58 121.63, 14.34 114.4, 9.27 105.74 C4.21 97.09, 0.99 85.8, 0.27 75.53 C-0.46 65.26, 1.09 53.71, 4.93 44.11 C8.76 34.51, 15.08 24.91, 23.26 17.92 C31.44 10.93, 48.18 4.81, 54.01 2.18 C59.84 -0.46, 58.06 1.18, 58.22 2.1 M38.48 7.08 C46.49 1.45, 59.19 -1.28, 69.19 -1.46 C79.18 -1.64, 89.2 1.53, 98.44 6 C107.69 10.47, 118.19 17.23, 124.66 25.35 C131.12 33.46, 135.16 44.69, 137.23 54.69 C139.29 64.69, 139.07 75.18, 137.04 85.32 C135.02 95.46, 131.09 107.57, 125.07 115.51 C119.04 123.45, 109.86 128.77, 100.9 132.95 C91.94 137.13, 81.65 140.15, 71.29 140.59 C60.93 141.02, 48.06 139.62, 38.75 135.55 C29.43 131.49, 21.47 124.29, 15.41 116.2 C9.34 108.1, 4.8 97.11, 2.38 86.99 C-0.04 76.88, -1.43 65.42, 0.87 55.49 C3.17 45.56, 9.7 35.64, 16.18 27.41 C22.65 19.18, 35.81 9.33, 39.71 6.12 C43.62 2.91, 39.08 7.06, 39.61 8.15&quot;
    stroke-width=&quot;1&quot;
    &amp;gt;&amp;lt;/path&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g
  stroke-linecap=&quot;round&quot;
  transform=&quot;translate(584 538) rotate(0 69.5 70.5)&quot;&amp;gt;
  &amp;lt;path
    d=&quot;M103.2 7.88 C112.19 11.55, 119.45 20.72, 125.29 29.19 C131.13 37.65, 136.3 48.81, 138.24 58.67 C140.19 68.53, 139.86 78.66, 136.98 88.34 C134.1 98.03, 127.69 108.95, 120.96 116.78 C114.23 124.61, 105.73 131.24, 96.59 135.32 C87.46 139.4, 76.05 141.55, 66.16 141.25 C56.26 140.95, 46.09 138.22, 37.25 133.49 C28.41 128.77, 19 121.33, 13.1 112.91 C7.2 104.49, 3.51 93.29, 1.84 82.97 C0.17 72.65, 0.4 60.81, 3.07 50.99 C5.74 41.17, 11.33 31.59, 17.86 24.05 C24.39 16.51, 33.18 9.72, 42.26 5.74 C51.33 1.77, 61.81 -0.66, 72.33 0.18 C82.84 1.03, 99.53 8.64, 105.33 10.83 C111.12 13.02, 107.81 12.36, 107.09 13.32 M82.33 1.63 C92.34 2.11, 103.37 6.67, 111.28 12.6 C119.19 18.53, 125.02 28.06, 129.78 37.22 C134.55 46.38, 139.02 57.6, 139.88 67.57 C140.73 77.54, 138.82 87.69, 134.9 97.06 C130.98 106.44, 124.21 117.06, 116.34 123.82 C108.48 130.58, 97.37 134.74, 87.69 137.61 C78.01 140.48, 67.85 142.83, 58.26 141.02 C48.68 139.22, 38.6 132.95, 30.19 126.78 C21.77 120.61, 12.89 112.72, 7.74 103.99 C2.59 95.25, -0.42 84.61, -0.71 74.37 C-1 64.13, 1.79 51.85, 6.01 42.54 C10.23 33.23, 16.93 24.99, 24.62 18.52 C32.31 12.06, 42.8 6.88, 52.14 3.75 C61.48 0.62, 75.98 0.04, 80.65 -0.26 C85.31 -0.56, 80.03 0.63, 80.15 1.95&quot;
    stroke-width=&quot;1&quot;
    &amp;gt;&amp;lt;/path&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g stroke-linecap=&quot;round&quot; transform=&quot;translate(10 10) rotate(0 69.5 70.5)&quot;&amp;gt;
  &amp;lt;path
    d=&quot;M54.43 2.18 C63.73 -1.18, 75.84 -1.09, 85.64 1.13 C95.44 3.35, 105.57 9.17, 113.23 15.51 C120.89 21.85, 127.22 29.92, 131.62 39.17 C136.01 48.41, 139.34 60.8, 139.58 70.98 C139.83 81.16, 137.59 91.17, 133.09 100.23 C128.59 109.29, 120.63 118.8, 112.57 125.33 C104.5 131.87, 94.34 137.18, 84.68 139.44 C75.03 141.71, 64.24 141.11, 54.64 138.94 C45.04 136.76, 34.87 132.53, 27.08 126.39 C19.3 120.25, 12.56 111.49, 7.94 102.07 C3.32 92.65, -0.31 80.25, -0.64 69.87 C-0.98 59.49, 1.41 48.89, 5.95 39.8 C10.5 30.7, 16.76 21.96, 26.61 15.28 C36.45 8.61, 56.83 1.86, 65.01 -0.27 C73.18 -2.39, 75.55 1.34, 75.65 2.51 M86.8 1.08 C96.43 2.68, 107.51 9.76, 115.37 16.7 C123.24 23.64, 130.21 33.31, 133.99 42.7 C137.78 52.09, 138.85 62.82, 138.11 73.04 C137.37 83.27, 133.99 94.87, 129.56 104.03 C125.14 113.2, 119.56 121.92, 111.55 128.05 C103.54 134.17, 91.44 139.17, 81.51 140.78 C71.58 142.4, 61.44 140.58, 51.97 137.73 C42.51 134.89, 32.52 130.11, 24.73 123.72 C16.95 117.33, 9.24 108.89, 5.28 99.38 C1.32 89.87, 0.34 76.83, 0.95 66.65 C1.55 56.47, 4.54 47.28, 8.91 38.3 C13.28 29.33, 19.39 18.91, 27.16 12.8 C34.92 6.68, 45.6 3.51, 55.51 1.62 C65.43 -0.28, 81.52 1.25, 86.64 1.42 C91.76 1.59, 86.13 1.47, 86.22 2.64&quot;
    stroke-width=&quot;1&quot;
    &amp;gt;&amp;lt;/path&amp;gt;
&amp;lt;/g&amp;gt;
&amp;lt;g stroke-linecap=&quot;round&quot;&amp;gt;
  &amp;lt;g transform=&quot;translate(144.5 103.5) rotate(0 148.60048447307202 92.8671882355213)&quot;&amp;gt;
    &amp;lt;path
      d=&quot;M-1.1 0.36 C48.42 31.32, 246.55 154.37, 296.08 185.15 M0.52 -0.5 C50.5 30.65, 248.65 155.18, 298.31 186.23&quot;
      stroke-width=&quot;1&quot;
      &amp;gt;&amp;lt;/path&amp;gt;
  &amp;lt;/g&amp;gt;
&amp;lt;/g&amp;gt;

&amp;lt;g stroke-linecap=&quot;round&quot;&amp;gt;
  &amp;lt;g transform=&quot;translate(96.5 149.5) rotate(0 4.303626279905416 65.03650238673202)&quot;&amp;gt;
    &amp;lt;path
      d=&quot;M-0.87 -0.6 C0.68 20.83, 7.77 107.34, 9.48 129.09 M0.88 1.7 C2.2 23.29, 7.02 109.62, 8.25 130.67&quot;
      stroke-width=&quot;1&quot;
      &amp;gt;&amp;lt;/path&amp;gt;
  &amp;lt;/g&amp;gt;
&amp;lt;/g&amp;gt;

&amp;lt;g stroke-linecap=&quot;round&quot;&amp;gt;
  &amp;lt;g transform=&quot;translate(139.5 406.5) rotate(0 89.83021834012123 91.4829672742635)&quot;&amp;gt;
    &amp;lt;path
      d=&quot;M-0.15 -1.03 C29.93 29.8, 151.28 153.22, 181.35 184 M-1.69 1.04 C28.19 31.64, 149.84 152.3, 180.58 182.4&quot;
      stroke-width=&quot;1&quot;
      &amp;gt;&amp;lt;/path&amp;gt;
  &amp;lt;/g&amp;gt;
&amp;lt;/g&amp;gt;

&amp;lt;g stroke-linecap=&quot;round&quot;&amp;gt;
  &amp;lt;g transform=&quot;translate(515.5 407.5) rotate(0 57.04129605777564 66.19997333149428)&quot;&amp;gt;
    &amp;lt;path
      d=&quot;M-0.98 0.08 C18.17 22.19, 95.75 111.04, 115.06 133.32 M0.71 -0.92 C19.77 20.75, 95.69 109.25, 114.67 131.37&quot;
      stroke-width=&quot;1&quot;
      &amp;gt;&amp;lt;/path&amp;gt;
  &amp;lt;/g&amp;gt;
&amp;lt;/g&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  
  &lt;figcaption&gt;A visual example of a graph data structure.&lt;/figcaption&gt;
&lt;/div&gt;
&lt;p&gt;To think about graphs in terms of code, we may write TypeScript that looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Node {
  edges: Edge[] = [];
  data: string;
}

class Edge {
  previousNode: Node;
  nextNode?: Node;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
  &lt;figcaption&gt;
    Each node contains a list of its edges, and each edge contains a reference
    to the next/previous node. As we&apos;ll see in SQL later, the nodes don&apos;t always
    need to know about their edges.
  &lt;/figcaption&gt;
&lt;/div&gt;
&lt;p&gt;Facebook is a popular social media platform that uses a graph to represent people and their relationships.&lt;br /&gt;
A person can have friends, and those friends also have their list of friends.&lt;br /&gt;
Each person is represented as a node, and each friendship would be represented as an edge.&lt;br /&gt;
Graphs are used to model a lot of different applications like your&lt;br /&gt;
&lt;a href=&quot;https://www.dylanpaulus.com/posts/node-dependency-types&quot;&gt;npm dependencies&lt;/a&gt;,&lt;br /&gt;
&lt;a href=&quot;https://dagster.io/&quot;&gt;workflows&lt;/a&gt;, transportation systems, manufacturing lines, and more!&lt;/p&gt;
&lt;h2&gt;Storing Graph Data Structures in Postgres&lt;/h2&gt;
&lt;p&gt;To store a graph in Postgres we only need to create two tables: &lt;code&gt;nodes&lt;/code&gt; and &lt;code&gt;edges&lt;/code&gt;.&lt;br /&gt;
The &lt;code&gt;nodes&lt;/code&gt; table will store information about each entity, while the &lt;code&gt;edges&lt;/code&gt; table will store information about the relationships between entities.&lt;/p&gt;
&lt;p&gt;Let&apos;s start by creating a &lt;code&gt;nodes&lt;/code&gt; table:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CREATE TABLE nodes (
  id SERIAL PRIMARY KEY,
  data VARCHAR(255)
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;nodes&lt;/code&gt; table we defined here has two columns: id and data. The id column is an auto-incrementing integer that serves as the primary key for the table. The data column is a string that stores any extra data associated with the node.&lt;br /&gt;
For this example, we&apos;re keeping it simple and only storing a string column, but in real-world applications, this table could be anything and have any number of columns.&lt;/p&gt;
&lt;p&gt;The most important table when creating a graph data structure is the &lt;code&gt;edges&lt;/code&gt; table:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CREATE TABLE edges (
  previous_node INTEGER REFERENCES nodes(id),
  next_node INTEGER REFERENCES nodes(id),
  PRIMARY KEY (previous_node, next_node)
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we are creating two columns, &lt;code&gt;previous_node&lt;/code&gt; and &lt;code&gt;next_node&lt;/code&gt;, that represent our relationships between nodes.&lt;br /&gt;
Each of these columns represents a foreign key to a node. The important take away is an &lt;code&gt;edges&lt;/code&gt; table references two rows in the same table.&lt;br /&gt;
An edge can only have one &lt;code&gt;previous_node&lt;/code&gt; and &lt;code&gt;next_node&lt;/code&gt; pairing, so we are using a composite primary key to ensure that each edge is unique and cannot reference itself.&lt;/p&gt;
&lt;p&gt;With our tables created, we can now insert data into them.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO nodes (data) VALUES (&apos;Bob&apos;);
INSERT INTO nodes (data) VALUES (&apos;Hank&apos;);
INSERT INTO nodes (data) VALUES (&apos;Jeff&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then let&apos;s connect our nodes with edges:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO edges (previous_node, next_node) VALUES (1, 2);
INSERT INTO edges (previous_node, next_node) VALUES (1, 3);
&lt;/code&gt;&lt;/pre&gt;
&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;nodes&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;id&lt;/th&gt;
      &lt;th&gt;data&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;Bob&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;Hank&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;Jeff&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;edges&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;previous_node&lt;/th&gt;
      &lt;th&gt;next_node&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;If we were to visualize our graph at this point, it would look like this:&lt;/p&gt;
&lt;div&gt;
  ![A graph representation of the SQL created above](./example-1.svg)
&lt;/div&gt;
&lt;h2&gt;Querying Graph Data Structures in Postgres&lt;/h2&gt;
&lt;p&gt;With our graph data structure created, we can now query it using SQL we know and love!&lt;/p&gt;
&lt;p&gt;Want to know who Bob is friends with?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT id, data
FROM nodes
JOIN edges ON nodes.id = edges.next_node
WHERE edges.previous_node = 1;
&lt;/code&gt;&lt;/pre&gt;
&lt;figcaption&gt;
  Find all `nodes` connected to the node with `id` 1 (Bob&apos;s id).
&lt;/figcaption&gt;
&lt;p&gt;Looks like Bob is popular! But what if we want to know who Bob&apos;s friends are friends with?&lt;/p&gt;
&lt;p&gt;Let&apos;s insert a few more nodes and edges to show this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;INSERT INTO nodes (data) VALUES (&apos;Sally&apos;);
INSERT INTO nodes (data) VALUES (&apos;Sue&apos;);
INSERT INTO nodes (data) VALUES (&apos;Sam&apos;);

INSERT INTO edges (previous_node, next_node) VALUES (2, 4);
INSERT INTO edges (previous_node, next_node) VALUES (3, 4);
INSERT INTO edges (previous_node, next_node) VALUES (4, 5);
&lt;/code&gt;&lt;/pre&gt;
&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;nodes&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;id&lt;/th&gt;
      &lt;th&gt;data&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;Bob&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;Hank&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;Jeff&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;Sally&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;Sue&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;Sam&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;edges&lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;previous_node&lt;/th&gt;
      &lt;th&gt;next_node&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;5&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;To query for all Bob’s friends of friends we could extend the previous query to join the &lt;code&gt;edges&lt;/code&gt; table again, but that would cause a maintenance nightmare having to join on each “level” in the graph.&lt;/p&gt;
&lt;p&gt;Postgres has a built-in feature that allows us to query graph data without having to know exactly how many joins we need: &lt;a href=&quot;https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE&quot;&gt;recursive queries&lt;/a&gt;. Recursive queries allow us to traverse the graph starting from a specific node and following its edges until some determined endpoint.&lt;/p&gt;
&lt;p&gt;Writing a recursive query to find all Bob’s friends and their friends we would write the following SQL:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;WITH RECURSIVE friend_of_friend AS (
  SELECT edges.next_node
  FROM edges
  WHERE edges.previous_node = 1
  UNION
  SELECT edges.next_node
  FROM edges
  JOIN friend_of_friend ON edges.previous_node = friend_of_friend.next_node
)
SELECT nodes.data
FROM nodes
JOIN friend_of_friend ON nodes.id = friend_of_friend.next_node;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This can be confusing at first glance, so let&apos;s break it down.&lt;br /&gt;
A recursive query is made up of two parts: the base case and the recursive case.&lt;br /&gt;
The base case is where we want to start our query.&lt;br /&gt;
The recursive case is the &quot;loop&quot; that will continue to run until some endpoint is reached.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;WITH RECURSIVE {name} AS (
  {base case}
  UNION
  {recursive case}
)
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
  &lt;figcaption&gt;
    The basic SQL structure of a recursive query.
  &lt;/figcaption&gt;
&lt;/div&gt;
&lt;p&gt;In our example we want to start our query with Bob&apos;s friends, so we find the edges where Bob (id: 1) is the &lt;code&gt;previous_node&lt;/code&gt;.&lt;br /&gt;
Then in the recursive case we continually join the &lt;code&gt;edges&lt;/code&gt; table to itself until we reach the end of Bob&apos;s graph (eg. when we reach &lt;code&gt;friend_of_friend.next_node = NULL&lt;/code&gt;).&lt;br /&gt;
Finally outside our recursive query we bring it all together. We need to query the &lt;code&gt;nodes&lt;/code&gt; that are associated with the edges from the recursive query so we can get each of Bob&apos;s friends&apos; names.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;data&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Hank&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Jeff&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sally&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;By using features built into Postgres, we can store and query graph data structures.&lt;br /&gt;
We used a similar approach in my previous job to dynamically generate work instructions on a manufacturing line.&lt;br /&gt;
Based on parameters given, and rules defined on each edge, we could generate the correct document by traversing a graph stored entirely in Postgres.&lt;br /&gt;
If you are already using Postgres for your relational data, you can integrate graph data structures into your existing database without adding extra systems!&lt;/p&gt;
&lt;p&gt;If you want to try the queries in this post against a populated table, the &lt;a href=&quot;/posts/easily-generate-mock-data-with-postgresql&quot;&gt;&lt;code&gt;generate_series&lt;/code&gt; walkthrough&lt;/a&gt; covers how to spin up nodes and edges quickly. For more on the recursive CTE pattern used above, see &lt;a href=&quot;/posts/recursive-query-in-sql-what-it-is-and-how-to-write-one&quot;&gt;Recursive Query in SQL: What It Is, and How to Write One&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Git Worktree: Enhance your Git Workflow</title><link>https://dylanpaulus.com/posts/2023/git-worktree/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2023/git-worktree/</guid><pubDate>Fri, 10 Mar 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Have you ever found yourself in the middle of coding a feature, only to receive a notification that production is down? If you&apos;re using Git, you now have a few options: commit your work, stash your work, or discard your work.&lt;br /&gt;
Each of these options has its own set of problems, depending on the situation.&lt;br /&gt;
If you commit half-baked code, you may need to come back later and rebase to clean up your commit history.&lt;br /&gt;
Stashing can also cause problems. What if you need to stash extra code later before switching back to your original feature work?&lt;br /&gt;
As for me, I tend to throw away my current changes if they&apos;re small, but otherwise, I prefer not to.&lt;/p&gt;
&lt;p&gt;Recently, I stumbled upon &lt;a href=&quot;https://git-scm.com/docs/git-worktree/2.39.0&quot;&gt;Git worktree&lt;/a&gt;, and it has been an amazing boost to my productivity.&lt;/p&gt;
&lt;h3&gt;What is Git Worktree?&lt;/h3&gt;
&lt;p&gt;Git worktree allows us to checkout multiple branches in a Git repository, enabling us to switch between different branches without losing our non-committed work.&lt;br /&gt;
Git achieves this by creating new, separate directories called &quot;linked worktrees&quot; that are associated with a single &quot;main worktree&quot; (the directory created using git clone or git init).&lt;/p&gt;
&lt;p&gt;To checkout a new worktree, we use the &lt;code&gt;git worktree add &amp;lt;path&amp;gt; &amp;lt;branch_name&amp;gt;&lt;/code&gt; command. Worktrees are created as new directories, with the add command taking a path argument to specify where to create the new directory, and a branch name argument to specify which Git branch to checkout.&lt;br /&gt;
We can create new branches by adding the &lt;code&gt;-b&lt;/code&gt; argument, like this: &lt;code&gt;git worktree add -b &amp;lt;branch_name&amp;gt; &amp;lt;path&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We can view all the worktrees we&apos;ve created using the &lt;code&gt;git worktree list&lt;/code&gt; command.&lt;/p&gt;
&lt;div&gt;
  
&lt;/div&gt;
&lt;p&gt;With our different linked worktrees created, we can change code and switch between isolated instances of our codebase. The changes done in one worktree do not affect the other worktrees.&lt;/p&gt;
&lt;div&gt;
  
&lt;/div&gt;
&lt;p&gt;What about if we want to commit and push our changes out to Github? No problem! Git worktree is a way to checkout many branches.&lt;br /&gt;
So once we&apos;re done making changes in our worktree we can &lt;code&gt;git add&lt;/code&gt;, &lt;code&gt;git commit&lt;/code&gt;, and &lt;code&gt;git push origin&lt;/code&gt; like if we are working on a different branch.&lt;br /&gt;
The changes would show up on Github under the &lt;code&gt;&amp;lt;branch_name&amp;gt;&lt;/code&gt; we gave in &lt;code&gt;git worktree add &amp;lt;path&amp;gt; &amp;lt;branch_name&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;When we are done with a worktree we can call &lt;code&gt;git worktree remove &amp;lt;path_to_worktree&amp;gt;&lt;/code&gt; to delete it.&lt;/p&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;I keep all worktrees in a separate directory &lt;code&gt;~/.worktree&lt;/code&gt;, outside of my general projects directory &lt;code&gt;~/projects&lt;/code&gt;, to reduce clutter and keep &quot;main worktrees&quot; explicit from &quot;linked worktrees&quot;.&lt;br /&gt;
I am constantly switching between branches and code, and Git worktree has been a huge help to my workflow!&lt;/p&gt;
</content:encoded></item><item><title>Advice for New Software Engineers</title><link>https://dylanpaulus.com/posts/2022/advice-for-new-software-engineers/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2022/advice-for-new-software-engineers/</guid><pubDate>Mon, 04 Jul 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A few months ago I had an opportunity to give a presentation to soon-to-be Computer Science (CS) graduates. We presented the software development process (&lt;a href=&quot;https://geekflare.com/software-development-life-cycle-sdlc-guide/&quot;&gt;SDLC&lt;/a&gt;), and how different teams at Schweitzer Engineering Laboratories adapt the development process to their needs. We ended the presentation with tips for what to expect entering the industry.&lt;br /&gt;
There is a big disconnect between what we learn while getting a CS degree and writing software that makes money. Not to say a CS degree isn&apos;t worth it; quite the opposite. I still use the algorithms, graph theory, data structures, and development processes taught in college. But, there is so much more to software engineering than code and theory. In this article we&apos;ll walk through the tips I would give myself leaving college, and the tips I gave to those soon-to-be CS graduates.&lt;/p&gt;
&lt;h2&gt;Don&apos;t worry about knowing everything&lt;/h2&gt;
&lt;p&gt;I&apos;ve been programming a long time--I&apos;m &lt;a href=&quot;https://www.spacejam.com/1996/&quot;&gt;1996 Space Jam&lt;/a&gt; websites old. I&apos;ve contributed to many coding communities, built and maintained high-traffic applications with near-zero downtime, gave conference talks, released a course, and written a lot of these silly articles. If you were to pull me out of a crowd and ask me to invert a binary tree I would probably struggle. I&apos;ve been rejected from many job interviews and called &quot;not senior enough&quot;. The point is we all face rejection no matter how much we know, or how much experience we have. We can always be better. Don&apos;t fret about not knowing everything, and don&apos;t be afraid to say, &quot;I don&apos;t know&quot;, but always follow up with, &quot;But I&apos;ll find out&quot;. Throughout my four years getting a Computer Science degree I thought if I knew all the algorithms, and produced the fastest code I would be the best programmer. These things help, but after my first experience as a professional software engineer, I quickly learned there is so much more to software than Big O notation. It&apos;s not about knowing everything; it&apos;s being curious and able to figure it out.&lt;/p&gt;
&lt;h2&gt;Ask questions, have opinions&lt;/h2&gt;
&lt;p&gt;This piece of advice piggybacks &quot;Don&apos;t worry about knowing everything&quot;, and adds some spice. Don&apos;t be afraid to ask questions. Ask the senior developer why they came to a certain solution, or how &lt;code&gt;Map()&lt;/code&gt; is different than &lt;code&gt;{}&lt;/code&gt; in JavaScript. This is a two-way street. When you become a senior software engineer ask the junior engineers questions. Remember, we can&apos;t know everything, but speak up when we do know something! Have opinions. Yeah, not every opinion will be correct, but this is how we learn. As a manager, I like when interns have opinions on architecture. This shows they care, they&apos;re engaged, and they&apos;re learning. Just don&apos;t be a jerk about it. Ask questions on the things you don&apos;t know, and have opinions on the things you do know!&lt;/p&gt;
&lt;h2&gt;Have a business-oriented mindset&lt;/h2&gt;
&lt;p&gt;We leave college with the wrong mindset of what companies look for. I thought software companies wanted the best software engineers because it makes them the best. Don&apos;t get me wrong, there is value in being good at writing software. Let&apos;s say we write a highly decoupled, blazing-fast, platform-agnostic, cleanest code application. If no one uses the application then all we did was create a waste of time and money pit. Great software engineers consider both technical &lt;strong&gt;and&lt;/strong&gt; business needs. We need to think about how our decisions produce value. Switching frameworks may sound cool, but who gets the value out of that? If the old framework isn&apos;t maintained anymore, and we need to change to get security patch support then maybe it&apos;s worth switching frameworks. If we want to change frameworks, because we saw a post on &lt;a href=&quot;https://news.ycombinator.com/&quot;&gt;Hacker News&lt;/a&gt; about it then maybe reconsider.&lt;/p&gt;
&lt;p&gt;When I get asked how to get promoted and move up the software engineering ladder this is the biggest advice I can give. Consider how your skills produce value for your company. Same for writing a resume or interviewing. It&apos;s cool you know &lt;a href=&quot;https://www.haskell.org/&quot;&gt;Haskell&lt;/a&gt;, but how does that transfer to producing value at the company you&apos;re being hired for? Maybe since you had to learn Haskell for a class you are a quick learner, and can onboard quickly?&lt;/p&gt;
&lt;p&gt;Technology is a &lt;a href=&quot;https://www.dictionary.com/e/slang/means-to-an-end/&quot;&gt;a means to an end&lt;/a&gt;. Our applications solve problems users have is the goal.&lt;/p&gt;
&lt;h2&gt;Everyone breaks production&lt;/h2&gt;
&lt;p&gt;You&apos;re going to break production. Everyone does it. Even that lead engineer you look up to who never does wrong has broke production at some point. Don&apos;t stress about &lt;em&gt;if&lt;/em&gt; you&apos;re going to break production. &lt;em&gt;Breathe in.&lt;/em&gt; &lt;em&gt;Breathe out.&lt;/em&gt; &lt;em&gt;Let it go.&lt;/em&gt;&lt;br /&gt;
A colleague, who did the talk with CS graduates with me, has a saying, &quot;Optimize for mean to recovery.&quot; Find ways to reduce the blast radius once production is broken instead of worrying about breaking production in the first place. This could be:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Having &lt;em&gt;battle buddies&lt;/em&gt; you can rely on when &lt;em&gt;sh*t hits the fan&lt;/em&gt;. Find a support system who can jump in and help when production breaks&lt;/li&gt;
&lt;li&gt;Learn everything about the environment. Ask questions not just about the systems you work on, but neighboring systems. How does each piece connect?&lt;/li&gt;
&lt;li&gt;Improve your skills and learn different parts of the software stack. Learn how Databases work, maybe learn networking and DNS, and if you&apos;re working in containers maybe introduce yourself to Kubernetes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When interviewing for a company look for blameless cultures. This means when something eventually breaks in production the team doesn&apos;t start pointing fingers. Ask the interviewers how they deal with outages, and watch out for warning signs. Many buzzwords without any concrete plan/action can be a cause for concern.&lt;/p&gt;
&lt;p&gt;Lastly, writing software is a team effort. When software breaks there are multiple chains in the process of breaking down. Maybe code reviews weren&apos;t as thorough as they could have been? Or maybe we&apos;re missing testing or test cases that would have caught the error? Did the &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuous_integration&quot;&gt;Continuous Integration&lt;/a&gt; step run? Maybe the architecture is inherently complex? As engineers we like to point to a root cause (&lt;a href=&quot;https://en.wikipedia.org/wiki/Fallacy_of_the_single_cause&quot;&gt;Fallacy of the single cause&lt;/a&gt;), but the &lt;a href=&quot;https://en.wikipedia.org/wiki/Titanic&quot;&gt;Titanic&lt;/a&gt; didn&apos;t sink for one reason. The builders of the ship cut costs, the ship was moving too fast, and the ship&apos;s radio operator dismissed the warning (Pruitt, 2018). Find a team with a blameless culture and don&apos;t point fingers when systems fail. Iterate on failures to learn and get better. Software is a team pursuit.&lt;/p&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;p&gt;Pruitt, S., 2018. _Why Did the Titanic Sink?_. [online] History. Available at: &lt;a href=&quot;https://www.history.com/news/why-did-the-titanic-sink&quot;&gt;https://www.history.com/news/why-did-the-titanic-sink&lt;/a&gt; [Accessed 4 July 2022].&lt;/p&gt;
</content:encoded></item><item><title>NPM: What are project dependencies?</title><link>https://dylanpaulus.com/posts/2021/node-dependency-types/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2021/node-dependency-types/</guid><pubDate>Tue, 17 Aug 2021 00:00:00 GMT</pubDate><content:encoded>
&lt;p&gt;Code dependencies are like &lt;a href=&quot;https://www.lego.com/en-us&quot;&gt;Lego&apos;s&lt;/a&gt;. We are able to pull in other people&apos;s code, combining and stacking different packages together to achieve our goals. Using dependencies greatly reduces the complexity of developing software. We can take advantage of the hard work someone has already done to solve a problem so that we can continue building the projects we want. A development pipeline can have multiple kinds of code dependencies:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;dependencies&lt;/li&gt;
&lt;li&gt;developer dependencies &lt;em&gt;(devDependencies)&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;peer dependencies &lt;em&gt;(peerDependencies)&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In JavaScript, we have a &lt;code&gt;package.json&lt;/code&gt; file that holds metadata about our project. &lt;code&gt;package.json&lt;/code&gt; can store things like our project name, the version of our project, and any dependencies our project has. Dependencies, devDependencies, and peerDependencies are properties that can be included in a &lt;code&gt;package.json&lt;/code&gt; file.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;dependencies&quot;: {
        ...
    },
    &quot;devDependencies&quot;: {
        ...
    },
    &quot;peerDependencies&quot;: {
        ...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Production vs. Development&lt;/h2&gt;
&lt;p&gt;The type of dependency a package is changes depending on the instance where code will be used. Some packages are necessary for users to run our code. By &quot;users&quot;, we refer to people who are not directly working in our code-base, such as those who interact with an application we wrote or a developer writing a separate library. In other words, these are packages that are required in a production environment. On the other hand, there are packages that are only needed by developers or systems while working in our code, such as linters, testing frameworks, and build tools. These are packages that users won&apos;t need, but developers or build systems will need.&lt;/p&gt;

&lt;h2&gt;Dependencies&lt;/h2&gt;
&lt;p&gt;Dependencies refer to packages that our project uses in &lt;em&gt;production&lt;/em&gt;. They are essential for making our application run, as they are included with our code. Whenever we install a dependency, the package and any of its dependencies are downloaded onto our local hard drive. The more dependencies we add, the larger our production code becomes, since each new dependency is included in the production build of our code. It&apos;s important to evaluate whether new dependencies are truly needed before adding them, in order to minimize the size of our production code.&lt;/p&gt;
&lt;p&gt;Dependencies are installed using &lt;code&gt;npm install X&lt;/code&gt; or &lt;code&gt;yarn add X&lt;/code&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Examples of dependencies: React, stylized-components, jQuery&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Dev Dependencies&lt;/h2&gt;
&lt;p&gt;Packages needed in &lt;em&gt;development&lt;/em&gt;, or while developing our code, are considered dev dependencies. These are programs, libraries, and tools that assist in our development workflow. Dev dependencies also get downloaded to your local hard drive when installed, but the user will never see these dependencies. So adding a lot of dev dependencies only affects the initial &lt;code&gt;yarn&lt;/code&gt; or &lt;code&gt;npm install&lt;/code&gt; completion time.&lt;/p&gt;
&lt;p&gt;Dev Dependencies are installed using &lt;code&gt;npm install --save-dev X&lt;/code&gt; or &lt;code&gt;yarn add --dev X&lt;/code&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Examples of Dev Dependencies: Jest, ESLint, Webpack&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;Peer Dependencies&lt;/h2&gt;
&lt;p&gt;Peer dependencies are similar to dependencies except for a few key features. First, when installing a peer dependency it doesn&apos;t get added to your &lt;code&gt;node_modules/&lt;/code&gt; directory on your local hard drive. Why is that? Well, peer dependencies are dependencies that are needed in &lt;em&gt;production&lt;/em&gt;, but we expect the user of our code to provide the package. The package doesn&apos;t get included in our code. This is to reduce including multiples of the same dependency in &lt;em&gt;production&lt;/em&gt;. If every React library included a version of React as a dependency, then in &lt;em&gt;production&lt;/em&gt; our users would download React multiple times. Peer dependencies are a tool for library owners to optimize their project size.&lt;/p&gt;
&lt;p&gt;Peer Dependencies are installed using &lt;code&gt;yarn add --peer X&lt;/code&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Examples of Peer Dependencies: React, Bootstrap&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;End&lt;/h2&gt;

&lt;p&gt;I recently released a course, Creating React Libraries from Scratch, where we walk through deploying a React library from &lt;code&gt;yarn init&lt;/code&gt; to &lt;code&gt;yarn publish&lt;/code&gt;. Creating React Libraries from Scratch includes content just like this and more!&lt;/p&gt;
&lt;p&gt;To learn more click the image below!&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://www.newline.co/courses/creating-react-libraries-from-scratch&quot;&gt;&lt;img src=&quot;/images/create-react-libraries-card.png&quot; alt=&quot;Click here to learn more!&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>CSS Box Model</title><link>https://dylanpaulus.com/posts/2020/css-box-model/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2020/css-box-model/</guid><pubDate>Sat, 24 Oct 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;CSS is one of those technologies that has a low barrier to entry (good thing 🎉), but because of this sometimes how it works can seem like magic. It&apos;s easy to get started writing CSS, so we dive head first into it. Sometimes we smash our face into the concrete with frustration. Why won&apos;t my text move over yonder? Where did that scroll bar come from? How do I center this junk?&lt;/p&gt;
&lt;p&gt;This is a series I&apos;m starting called, &quot;CSS: The Important Stuff&quot;. The goal is to take a dive into the mechanics of CSS so we can get a better intuition when styling and positioning elements. In part one we&apos;ll take a look at Box Model; the underlying layout of the web.&lt;/p&gt;
&lt;h2&gt;What is the Box Model?&lt;/h2&gt;
&lt;p&gt;It comes with great danger to myself to tell you that the web is made of boxes. Yes, it&apos;s boxes all the way down. Take a look at this website—open the Element Inspector in the browser&apos;s dev tools and add &lt;code&gt;* { border: 1px solid red; }&lt;/code&gt;. Look at all those fine boxes.&lt;/p&gt;
&lt;div&gt;
  &lt;img src=&quot;./css-box-model-red-boxes.png&quot; alt=&quot;The dylanpaulus.com website with visible borders around each box element.&quot; /&gt;
&lt;/div&gt;
&lt;p&gt;The browser uses boxes to layout and render our websites. Within each box there are four properties: content, padding, border, and margin. &lt;a href=&quot;https://youtu.be/-FtCTW2rVFM?t=44&quot;&gt;Boxes are like onions, they have layers.&lt;/a&gt; Each property defines the size of our box (ie. width and height), styling, and how content around the box flows.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Content&lt;/strong&gt; is what we&apos;re usually thinking of when we create HTML elements. Text, images, video, etc. This is at the center of the box&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Padding&lt;/strong&gt; gives space around the edges of the content. Separating the content from the border&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Borders&lt;/strong&gt; are used to separate boxes from each other—as seen in our red border example above&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Margin&lt;/strong&gt; is non-stylistic spacing &lt;em&gt;around&lt;/em&gt; the box. This is useful to separate boxes from each other and position boxes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;./css-box-model.png&quot; alt=&quot;Showing the layout of content, padding, border, and margin to make up a box.&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Why does this matter?&lt;/h2&gt;
&lt;h3&gt;Dimensions&lt;/h3&gt;
&lt;p&gt;There are different ways to determine the width and height of a box. Is the box&apos;s dimensions determined by all its layers (margin, border, padding, content)? Or is it determined by the content?&lt;/p&gt;
&lt;p&gt;The browser made a choice in &lt;code&gt;box-sizing&lt;/code&gt; and the default is &lt;code&gt;content-box&lt;/code&gt;. When we give our element a width and height, lets say &lt;code&gt;.box { width: 100px; height: 100; }&lt;/code&gt; , the default behavior with &lt;code&gt;content-box&lt;/code&gt; is to give the content layer the width and height of 100px. But, the box still has extra layers with padding and border. We would assume if we gave the element of 100px that it would be 100px, but the browser needs to add the values of padding and border on top of the content to get its &quot;rendered dimensions&quot;.&lt;/p&gt;
&lt;p&gt;Given the styling on our moon icon below, what would you expect the width and height to be on the box?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.moon {
  box-sizing: content-box;
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid #FFF;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./css-box-model-content-box.png&quot; alt=&quot;Showing a moon icon using box sizing content-box.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;That&apos;s easy it&apos;s 100px... wait, 122px, what? How did we get 122px? Remember when we gave the width and height of 100px it only applies to the &lt;strong&gt;content&lt;/strong&gt; layer. We also applied a &lt;strong&gt;padding&lt;/strong&gt; of 10px on &lt;em&gt;each&lt;/em&gt; side of the box and a 1px &lt;strong&gt;border&lt;/strong&gt; around it. If we were to calculate the width of the box, we start with 100px, add 10px for the left padding, add 10px for the right padding, add 1px for the left border, and finally 1px for the right border.&lt;/p&gt;
&lt;p&gt;$$&lt;br /&gt;
100px + 10px + 10px + 1px + 1px = 122px&lt;br /&gt;
$$&lt;/p&gt;
&lt;p&gt;Seems a little counter intuitive—if I set my box to have a 100px width then it should be 100px darn-it! Luckily, there are more ways for the browser to calculate a box&apos;s size. When I think of the size of a box, I think of &lt;code&gt;border-box&lt;/code&gt; . Think of the layers of a box, and when assigning box-sizing think of the value as being cascading. When an element has &lt;code&gt;content-box&lt;/code&gt; that means the browser determines the size of a box starting from content and adding any child layers. Since there are no children to content width/height only applies to content. When using &lt;code&gt;border-box&lt;/code&gt;, width/height is set for the border, padding, and content.&lt;/p&gt;
&lt;p&gt;Let&apos;s take a look at the same moon icon, but apply &lt;code&gt;border-box&lt;/code&gt; instead.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.moon {
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  padding: 10px;
  border: 1px solid #FFF;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;./css-box-model-border-box.png&quot; alt=&quot;Showing a moon icon using box sizing as border-box.&quot; /&gt;&lt;/p&gt;
&lt;p&gt;What we see is something quite different, the width and height of the moon is now a hard 100x100. This isn&apos;t magic though, the missing dimensions have to come from somewhere. Using &lt;code&gt;border-box&lt;/code&gt; the &lt;strong&gt;content&lt;/strong&gt; layer gets shrunk to make room for &lt;strong&gt;padding&lt;/strong&gt; and &lt;strong&gt;border&lt;/strong&gt;. With &lt;code&gt;content-box&lt;/code&gt; our width was guaranteed to be 100px, but what is the width of our content now with &lt;code&gt;border-box&lt;/code&gt;?&lt;/p&gt;
&lt;p&gt;$$&lt;br /&gt;
100px - 10px - 10px - 1px - 1px = 78px&lt;br /&gt;
$$&lt;/p&gt;
&lt;p&gt;To me &lt;code&gt;border-box&lt;/code&gt; is easier to intuit and reason around, and becomes my default, but if the width and height of the content matters more than the visible box itself, use &lt;code&gt;content-box&lt;/code&gt;.&lt;/p&gt;
&lt;br /&gt;
&lt;h2&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model&quot;&gt;Introduction to the CSS basic box model&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model&quot;&gt;The box model&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Start With No</title><link>https://dylanpaulus.com/posts/2020/start-with-no/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2020/start-with-no/</guid><pubDate>Sun, 13 Sep 2020 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;Our default response to any idea that comes up should be: “Interesting. Maybe some day.” In other words, a very soft “no” that leaves all our options open. We don’t put it in a backlog. We give it space so we can learn whether it’s really important and what it might entail.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div&gt;
    &lt;sub&gt;
        &lt;a href=&quot;https://basecamp.com/shapeup/1.2-chapter-03#responding-to-raw-ideas&quot;&gt;&quot;Shape Up&quot; - Ryan Singer (Basecamp)&lt;/a&gt;
    &lt;/sub&gt;
&lt;/div&gt;
&lt;p&gt;Here&apos;s a story: At a previous employer, I had a boss who I thought was pretty tough. Not to me, but to our users. No matter the request, his response was always the same: &quot;No.&quot; Eventually, we implemented around 40% of the requests, but the constant rejection of these requests stuck with me. Now that I lead a team, I notice myself using the same mindset. &quot;No&quot; isn&apos;t negative, and it&apos;s not dismissive. &quot;No&quot; is a way of protecting the team, the project, and the users.&lt;/p&gt;
&lt;h3&gt;No?&lt;/h3&gt;
&lt;p&gt;There is a natural progression to projects that looks something like this: first, the honeymoon phase. The pastures are green; the project has no technical debt, and every feature is a great idea. As we add functionality, our user base grows. If we&apos;re lucky enough to get traction, we move to phase two: the monolith. Our application now handles a bunch of use-cases. It does your taxes, picks up your dog&apos;s poop, and reminds you to call your mom. Only power users can fully grasp the purpose of the application. The technical debt is increasing with every new feature added. Finally, we get to the last phase. The application has become so bloated that it&apos;s hard to develop new features. New users aren&apos;t willing to learn the ins-and-outs of the product. A new startup comes around with a trimmed-down version of your application. It&apos;s so easy to use! Around this time, users are jumping ship.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./feature-graph.jpg&quot; alt=&quot;Diagram showing a product&apos;s lifecycle&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Saying &quot;no&quot; is a buffer in our development process. It gives us, the developer, time to think of an optimal solution. Could a feature being asked for be solved in a way that satisfies multiple feature requests? Is there some domain logic we have yet to understand? Does the feature really make sense in &lt;em&gt;this&lt;/em&gt; application? All these questions help reduce the lifecycle described above. It reduces feature churn by keeping the application simple and by solving issues the users actually have.&lt;/p&gt;
&lt;p&gt;Be mindful of how features interact within your application. Nothing comes without a cost—especially in software development.&lt;/p&gt;
&lt;h3&gt;No.&lt;/h3&gt;
&lt;p&gt;&quot;No&quot; is a way of protecting people—the users and the development team. There is a gradient of experience when it comes to using your application. Users will be complete beginners, and others will be power users. As a product owner, we need to balance these two extremes. If the application is too power-user-centric, then it&apos;s harder for new users to grasp. When the application is too hand-holding, power users become frustrated. Saying &quot;no&quot; to one extreme is a way of keeping the scales balanced. But be mindful of what you say &quot;no&quot; to. Some features may be vital to the application&apos;s success. This is part of the art.&lt;/p&gt;
&lt;p&gt;&quot;No&quot; gives time to find the optimal solution to a problem. Users ask for a solution to X and suggest implementing Y, but what they really need is K. Feature requests give us an opportunity to improve processes and workflows. Our users are domain experts but are prone to doing things the way they&apos;ve &quot;always done them.&quot; We can come in and find ways to simplify. Ask the user, &quot;do we really need this step?&quot; or &quot;Could the system handle that instead of a person?&quot; Once code is written and users get accustomed to the feature, it&apos;s really hard to change. Do this step upfront.&lt;/p&gt;
&lt;p&gt;&quot;No&quot; keeps the development team doing meaningful work. Spending a sprint or two implementing a feature nobody uses or finds frustrating is demoralizing. Think about the workflow before writing any code. Question the feature and the users. Does the application need this? Could we implement it in a simple way? Reduce code churn; reduce developer churn.&lt;/p&gt;
&lt;h3&gt;No!&lt;/h3&gt;
&lt;p&gt;Work needs to get done. At some point, you need to say &quot;yes,&quot; but instead of taking on every task, you get to be mindful of what to prioritize. You get to take on the tasks that add the most business value and delight users. Use &quot;no&quot; as a tool.&lt;/p&gt;
</content:encoded></item><item><title>Making React Fast: Tips on Optimizing ReactJS</title><link>https://dylanpaulus.com/posts/2020/making-react-fast/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2020/making-react-fast/</guid><pubDate>Tue, 04 Feb 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import { Image } from &quot;astro:assets&quot;;&lt;br /&gt;
import htmlDiagramImage from &quot;./html-diagram.svg?url&quot;;&lt;br /&gt;
import reactRenderingImage from &quot;./react-rendering.svg?url&quot;;&lt;/p&gt;
&lt;p&gt;React does a fantastic job abstracting away the rendering of webpages. When state changes, our UI&apos;s reflect it. But, have you ever gotten done writing your application just to notice things seem off? Clicking a button displaying a popover stutters for a second, or animations don&apos;t run smoothly.&lt;br /&gt;
With React being just a view layer there is a single bottleneck causing &quot;jank&quot; (stuttering in the interaction)... Rendering. If our applications never had to render they&apos;d all be blazing fast running at millions of frames per second (I had top scientists run the numbers)!&lt;br /&gt;
Fortunately we don&apos;t live in that world. Our applications are useful--they render and then re-render.&lt;/p&gt;
&lt;p&gt;The majority of devices have screens refreshing 60 times a second. Our applications have a short time-frame to update, render, and interact with users. &lt;a href=&quot;https://developers.google.com/web/fundamentals/performance/rendering/&quot;&gt;According to Google all work needs to be completed within 10ms&lt;/a&gt;. Yes you read that right, 10ms. A daunting task. React gives us a lot of tools to take on this challenge. Let&apos;s take a look at a few of these.&lt;/p&gt;
&lt;h3&gt;The DOM Tree&lt;/h3&gt;
&lt;p&gt;Before moving onto improving React we need to take a step back. We need to get a few foundational ideas out of the way. The universal data structure of the internet is the &lt;a href=&quot;https://en.wikipedia.org/wiki/Tree_%28data_structure%29&quot;&gt;Tree&lt;/a&gt;. HTML is built off of it.&lt;br /&gt;
If we consider the following HTML:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;div&amp;gt;
  &amp;lt;span&amp;gt;Hello&amp;lt;/span&amp;gt;
  &amp;lt;p&amp;gt;World&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then the data structure representation would look like:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;React takes the same DOM (Document Object Model.. ie. HTML) tree structure, and mirrors it in memory--called the Virtual DOM. Kind of like how a cache is to I/O, the Virtual DOM is to the DOM Tree. It&apos;s faster to perform CRUD operations (Create, Read, Update, Delete) in the Virtual DOM. The browser performs massive amounts of work when the DOM Tree is changed: painting, layout, calculations, etc. The Virtual DOM is only a representation of the DOM in memory, so things like painting and layout don&apos;t need to be calculated. It&apos;s easier to perform many changes to the Virtual DOM then commit the final result, than it is to perform each change to the browser&apos;s DOM tree.&lt;/p&gt;
&lt;p&gt;When thinking to optimizing React, think of the Virtual and browser&apos;s DOM Tree. The less work each of these structures have to perform, the faster our applications behave!&lt;/p&gt;
&lt;h3&gt;What causes React to render?&lt;/h3&gt;
&lt;p&gt;There are two main reasons for components to render in React: when a component&apos;s &lt;em&gt;state&lt;/em&gt; changes, or when its &lt;em&gt;props&lt;/em&gt; change. Out of the box React chooses the naive approach in deciding what needs re-rendered. Re-render the element, and any of its children nodes, every time the props/state changes. For example in the figure below, say we change the state of node 2. All elements contained within the dashed line would also be re-rendered.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Don&apos;t take this as a bad thing! React cannot make any preconceived assumptions on how our application functions, so it chooses the most user friendly approach. It would instead be frustrating if we updated our application with a logged-in user prop, and the MenuBar component six layers deep didn&apos;t reflect this change.&lt;/p&gt;
&lt;h3&gt;shouldComponentUpdate()&lt;/h3&gt;
&lt;p&gt;Every (class-based) React component has a &lt;code&gt;shouldComponentUpdate()&lt;/code&gt; method which returns a boolean. It does exactly what the name suggests, returns &lt;code&gt;true&lt;/code&gt; if the component should render on prop/state changes, or &lt;code&gt;false&lt;/code&gt; if it shouldn&apos;t. Remember how we said a component always updates on prop/state changes? By default each component&apos;s &lt;code&gt;shouldComponentUpdate()&lt;/code&gt; looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;shouldComponentUpdate() {
  return true;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yup, on every update the component re-renders! But, what if we only wanted a component to update when certain props change? React will first call &lt;code&gt;shouldComponentUpdate()&lt;/code&gt;, then move to updating the component if &lt;code&gt;true&lt;/code&gt; is returned. &lt;code&gt;shouldComponentUpdate()&lt;/code&gt; takes two parameters: the next props and the next state. We could calculate any number of scenarios to optimize our application. Consider,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;shouldComponentUpdate(nextProps, nextState) {
  if (!this.props.isOpen &amp;amp;&amp;amp; nextProps.isOpen) {
    return true;
  }

  return this.state.textInput === nextState.textInput;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is great for components with a few props and state, but as components grow so do the need to check every prop and state. There has to be an easier way, right? Stay tuned!&lt;/p&gt;
&lt;h3&gt;PureComponent/Memo&lt;/h3&gt;
&lt;p&gt;Let&apos;s start with memoization... what is it? Why do we care?&lt;/p&gt;
&lt;p&gt;Think of when a function receives arguments, like &lt;code&gt;add(1, 2)&lt;/code&gt;. Given the same inputs we can assume that we&apos;ll receive the same output (from our add example, the output is always 3). Let&apos;s also assume we have bad code and &lt;code&gt;add(a, b)&lt;/code&gt; is a function that performs a bunch of computation. On average it takes three seconds to complete. After running the &lt;code&gt;add(1, 2)&lt;/code&gt; function once we already know it outputs 3, so why should we waste additional time computing the output? &lt;a href=&quot;https://en.wikipedia.org/wiki/Memoization&quot;&gt;Memoization&lt;/a&gt; is the act of caching, or storing, the result of a function call and returning the cached result on future requests.&lt;/p&gt;
&lt;p&gt;In the same way, memoization is also utilized within React to prevent having to compute expensive renders (computations) over and over again.&lt;/p&gt;
&lt;p&gt;Remember our friend &lt;code&gt;shouldComponentUpdate()&lt;/code&gt;? We can achieve the same effect with PureComponent. Generally, our class-based React components will look like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MyComponent extends React.Component {
  ....
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But, for extra optimization goodness we can replace &lt;code&gt;React.Component&lt;/code&gt; with &lt;code&gt;React.PureComponent&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MyComponent extends React.PureComponent {
  ....
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These two classes differ in their implementation of &lt;code&gt;shouldComponentUpdate()&lt;/code&gt;. React.Component&apos;s &lt;code&gt;shouldComponentUpdate()&lt;/code&gt; will always return true unless we override it (ie. always re-render on update). React.PureComponent has its own implementation of &lt;code&gt;shouldComponentUpdate()&lt;/code&gt; which automatically performs a shallow comparison of all the component&apos;s props and state. If any of the new props the component receives are changed, then return true. Otherwise, it will return false (ie. not triggering a re-render, and returning the previously calculated render of the component).&lt;/p&gt;
&lt;p&gt;Up until this point we&apos;ve only talked about class-based components. You may be asking yourself, &quot;Fine, but what about function components?&quot; Since our goal is to &apos;cache&apos; the output of a function component, React gives us a handy utility for memoizing our function components... &lt;code&gt;React.memo&lt;/code&gt;! This works similarly to React.PureComponent in class-based components. If the component receives new props/state it re-renders. Otherwise, return the computed output from before.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function MyComponent(props) {
  ...
}

export React.memo(MyComponent);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Warning:&lt;/em&gt; Don&apos;t get &lt;code&gt;React.memo()&lt;/code&gt; confused with &lt;code&gt;React.useMemo()&lt;/code&gt;. These are different, and used in different ways!&lt;/p&gt;
&lt;h3&gt;Hooks (useMemo, useCallback)&lt;/h3&gt;
&lt;p&gt;I won&apos;t specifically go over how hooks work in this section. For an introduction, &lt;a href=&quot;https://react.dev/learn#using-hooks&quot;&gt;check out the infinitely better documentation&lt;/a&gt; from the official website. Instead, we&apos;ll be checking out two hooks that help us improve the rendering speed of our applications.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;useMemo()&lt;/code&gt; is useful for &apos;caching&apos; the results of a computationally expensive expression which returns a value. For example,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function MyComponent(props) {
  const result = React.useMemo(() =&amp;gt; JSON.parse(props.value), [props.value]); // highlight-line

  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We provide &lt;code&gt;useMemo()&lt;/code&gt; a second argument, which says whenever the value changes (props.value), rerun the function provided in the first argument. This makes it so values only get recalculated when they change.&lt;/p&gt;
&lt;br /&gt;
&lt;p&gt;&lt;code&gt;useCallback()&lt;/code&gt; instead returns a &apos;cached&apos; version of a function.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function MyComponent(props) {
  /* highlight-range{1-3} */
  const handleClick = React.useCallback((event) =&amp;gt; {
    console.log(event);
  }, []);

  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead of rebuilding the function on every render, &lt;code&gt;useCallback()&lt;/code&gt; calculates a function only when needed.&lt;/p&gt;
&lt;h3&gt;Extracting Components&lt;/h3&gt;
&lt;p&gt;Large components are hard to maintain. To make our components easier to manage we may break them up into smaller, easier to manage pieces. Great! We achieved clean code! But, splitting components into smaller chunks also makes it easier to optimize computational heavy code. Its hard to optimize certain aspects of a gigantic component. In React either the whole component re-renders, or it doesn&apos;t. If components are broken down, using the techniques mentioned above (memo, pureComponent, and shouldComponentUpdate) become really powerful. We can isolate the bottlenecks in our applications and optimize.&lt;/p&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;There is a tradeoff in optimization. Memoized components create more memory that needs to be stored (ie. the output being cached). Also, there are additional computations needed in figuring out when and when not to re-render. Don&apos;t prematurely optimize. Run performance tests when you can, and optimize the pieces of your code that really need it!&lt;/p&gt;
</content:encoded></item><item><title>Music That Defined My Decade: 2010-2019</title><link>https://dylanpaulus.com/posts/2019/albums-2010-2020-decade/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/albums-2010-2020-decade/</guid><pubDate>Sun, 29 Dec 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This is an attempt at a different kind of post. Something less technical. Something more personal. I&apos;m a pretty big music fan, and I&apos;m always scrounging around the internet for new artists and songs to fill my Spotify portfolio. One of my biggest fears is being that 50 year old dude who still only listens to those same two Def Leppard songs. Mullet optional.&lt;/p&gt;
&lt;p&gt;Just to be clear, this isn&apos;t a list of the best albums/songs/whatever in the last decade--though I think they&apos;re pretty dope--but an anthology of nostalgia from the last ten years. Some songs are associated with life events, which I&apos;ll go in to. Others, just cool songs. For myself this is a journal. Maybe for the reader, a novelty to find new music.&lt;/p&gt;
&lt;p&gt;To give some context, when 2010 reared its head I had just turned 17. Still in high school! I had just became an uncle, and my favorite artists were The White Stripes and The Red Hot Chili Peppers. A big change from Blink-182 and My Chemical Romance from years before (we all listened to it, don&apos;t judge). This was all fueled by that drunk next door neighbor who knew all the cool bands. It was around this time that I had been playing guitar for a few years. Playing in a band was the natural progression. We played all the covers: Iron Man, Smoke on the Water, and Crazy Train. This was short lived--we wanted music that related to us.&lt;/p&gt;
&lt;h3&gt;Wavelets split w/ Senders&lt;/h3&gt;
&lt;p&gt;Really, I don&apos;t remember how I ever stumbled across The Wavelets. What I do remember is that I found them on MySpace. The second I heard the intro lick to Let Off Some Steam I was instantly hooked. It wasn&apos;t grandpa&apos;s music. The sound coming from my speakers was raw in every sense of the word. The recording quality, vocals, lyrics, instruments. Despite that the lyrics were relatable, the guitar was all over the place, and it was a sound I never heard before. It was Let Off Some Steam that made me do a 180, and completely changed the music I was into. The Wavelets eventually stopped playing, and a few of the members created a new band, Dikembe, which hold some of my favorite songs of all time. Though they had a short discography, The Wavelets are the pioneers to the rest of this list. The home base. I&apos;ve been playing music for close to ten years, and I&apos;m still trying to recreate my own version of Let Off Some Steam.&lt;/p&gt;

&lt;a href=&quot;http://wavelets.bandcamp.com/album/split-w-senders&quot;&gt;Split w/ Senders by wavelets&lt;/a&gt;

&lt;h3&gt;This Town Needs Guns (TTNG) and Moving Mountains&lt;/h3&gt;
&lt;p&gt;I&apos;m grouping these two bands, because they came around the same time. Though, totally different in sound, they equally expanded my musical pallette in different ways. These bands pushed me further off course. It started with rawness, The Wavelets, then got more mature with TTNG and Moving Mountains. A lot of the experiences I had in this decade can be equated to these three bands. The people I met, the places I got to travel to.&lt;/p&gt;
&lt;p&gt;We&apos;ll start with Moving Mountains...&lt;/p&gt;
&lt;h4&gt;Moving Mountains&lt;/h4&gt;
&lt;p&gt;Pneuma, the first album from Moving Mountains, is a whirlwind of an album. Its loud and in your face, but also soft and melodic. The first song I heard from this band is 8105. It was completely different than other songs. First, it was freaking 8 minutes long! Second, it didn&apos;t follow the classic song writing structure. There is no verse, chorus, verse chorus... Just one long linear story. 8105 taught me to experiment, try radical new sonic escapes, and got me into the genre Postrock.&lt;/p&gt;

&lt;a href=&quot;http://movingmountains.bandcamp.com/album/pneuma&quot;&gt;Pneuma by Moving Mountains&lt;/a&gt;

&lt;h4&gt;TTNG&lt;/h4&gt;
&lt;p&gt;TTNG is a different beast. Ever heard of Math Rock? No, it&apos;s not songs about multiplication tables. Math Rock is a style of music that fluctuates in time signatures. It can almost sound disjointed. But, TTNG with their song 26 is Dancier Than 4 is not just a crazy time signature free-for-all with guitars and drums flying everywhere. It&apos;s beautiful. Just listen to that outro! TTNG got me into the exocentric side of music and at the same time, the twinkly &quot;pretty&quot; stuff. Most bands I&apos;ve played in, or played with have been categorized as &quot;Math Rock&quot;. It has almost became a label for me now.&lt;/p&gt;

&lt;a href=&quot;http://thistownneedsguns.bandcamp.com/album/this-town-needs-guns&quot;&gt;This Town Needs Guns by TTNG&lt;/a&gt;

&lt;h3&gt;The Appleseed Cast&lt;/h3&gt;
&lt;p&gt;I have a weird love/hate with The Appleseed Cast. Their music isn&apos;t bad--in fact it&apos;s amazing. Do you ever have one of those bands or songs that remind you of a time in your life? The Appleseed Cast is one of those bands. Around the time their album Illumination Ritual came out I had been hanging out with a girl I really liked. She liked me. But, depression and anxiety was running rampant. I went into a spiral--pushing everyone away (spoiler, this happens a few more times for different reasons). You know, college stuff where we really don&apos;t know what we want in life and what we&apos;re doing. What was the result? A year lost to isolation and drinking a lot. Spring came and I began to hike after class everyday. A mile. Then more. The Liberty Lake Loop was my favorite coming in at around 8 miles round-trip. My classes ended at 11am. I was generally done with the hike around 5pm. The whole hike I would listen to The Appleseed Cast&apos;s latest album over-and-over again, on repeat, for the full 8 miles, every time. The Appleseed Cast will always be associated to the time I went into that abyss, and found my way out. The good and the bad.&lt;/p&gt;



&lt;h3&gt;The Hotelier&lt;/h3&gt;
&lt;p&gt;Before I was even done with college I got a job offer for my dream job. Ever since six years old I wanted to work in the games industry. Here it was, I got an offer to be a programmer for Playstation in San Diego, CA. The experience was amazing--it was everything I would of wanted. Would.. Here I was in a totally new city. Everyday after work I would go home, and isolate myself. Stare at the walls of my 500 square foot apartment until I fell asleep. Then back to work. I had went from playing gigs every weekend and hanging with friends all the time to nothing. There was no future. To throw fuel on the fire, my dog got cancer. Then a second one did (we had three dogs). And a close grandparent started to show signs of Alzheimer&apos;s. Fuck! This is my life when The Hotelier&apos;s album Goodness came out. I would walk around a nearby lake, Lake Miramar, and listen the heck out of this album. Something about Goodness always lifted me up. It made me hopeful that even though I had achieved what I had always wanted to do, someday I would be back in my town playing my old crappy songs with the people closest to me.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;When this began.&lt;br /&gt;
This was a thing.&lt;br /&gt;
That we could both share.&lt;br /&gt;
A bit of shade.&lt;br /&gt;
The goodness fades.&lt;br /&gt;
And we begin there.&lt;/p&gt;
&lt;/blockquote&gt;



&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;Now there are probably hundreds, if not thousands of songs that could put on here. But, this is the music that stood out. That mean the most to me. Think of it as my most memorable five songs of the decade--without the clickbait. What would your top five songs be of the decade? What songs mean the most to you?&lt;/p&gt;
</content:encoded></item><item><title>Lost Connections: Why You’re Depressed and How to Find Hope</title><link>https://dylanpaulus.com/posts/2019/lost-connections/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/lost-connections/</guid><pubDate>Sun, 01 Dec 2019 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;You need your nausea. It is a message. It will tell us what is wrong with you.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Lost Connections is a challenge to the classic story any of us with depression and anxiety have heard. Go to a doctor. Get anti-depression pills. Become &lt;em&gt;normal&lt;/em&gt;. Johann doesn&apos;t completely remove that fact that medical anti-depressants work, they do; just for a smaller subset of humans than is currently being prescribed. We live in the loneliest age. The internet has made us shelter away from society. During a study participants were asked, &quot;In a crisis, how many close friends could you call?&quot; Years ago the most common answer was five. Today it is &lt;strong&gt;none&lt;/strong&gt;. In Lost Connections, Johann travels across the world to talk to leading psychologists and researchers to figure out the leading causes for depression and anxiety. He came across nine symptoms that may be the leading factors for making us (society) depressed and anxious.&lt;/p&gt;
&lt;h3&gt;Disconnection from Meaningful Work&lt;/h3&gt;
&lt;p&gt;For many of us, work is 8 hours a week day--1/4&lt;sup&gt;th&lt;/sup&gt; of the day. It&apos;s no wonder that a lack of autonomy in our jobs, and a lack of real purpose causes depression. Johann mentions that between 2011 and 2012, a polling company Gallup studied millions of workers across 142 countries. They found 13 percent of workers said they were &quot;engaged.&quot; 63 percent said they were &quot;not engaged.&quot; And finally the remaining 24 percent were &quot;actively disengaged.&quot; Which means these workers were not only unhappy with their job, but actively acting out against the other employees and company.&lt;/p&gt;
&lt;h3&gt;Disconnection from Other People&lt;/h3&gt;
&lt;p&gt;As we dive head first into social media, the disconnection from humans grows. We no longer have real connections. Physical face-to-face connections. Johann talks of an experiment performed at Berkley by two professors. Groups from four countries were asked to put conscious effort into making themselves happier--The United States, Russia, Taiwan, and Japan. What they found is the group from the west (USA) didn&apos;t get any happier. Groups from the east (Russia, Taiwan, Japan) did. Why is that? Western countries tend to be more individualistic. You&apos;ll be happier if you buy that car, or get a promotion--build up the ego. The East instead looks at the group. How can I contribute to the community? They instead ignore the ego, and push to connect with other people.&lt;/p&gt;
&lt;h3&gt;Disconnection from Meaningful Values&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Just as we have shifted en masse from eating food to eating junk food [...] we have shifted from having meaningful values to having junk values.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This chapter describes the shift in our culture from intrinsic values to extrinsic values (ie. trying to learn the piano, because we love it vs. learning the piano is impress others). Society has started to push &quot;junk values&quot; (extrinsic) as a solution to happiness. Studies have shown the opposite. An American psychologist, Tim Kasser, gives four reasons why extrinsic values make us feel bad.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Thinking extrinsically poisons your relationships with other people&lt;/li&gt;
&lt;li&gt;The ego shrinks while performing intrinsic values. Extrinsic does the opposite. Intrinsic activities produces more flow states than extrinsic activities&lt;/li&gt;
&lt;li&gt;Extrinsic thinking keeps us wondering, &quot;How are people judging me?&quot; It&apos;s an infinite game. Once we become rich, we want to become richer. &quot;Materialism leaves you constantly vulnerable to a world beyond your control&quot;&lt;/li&gt;
&lt;li&gt;We all have innate needs--to feel connected, valued, secure, a feeling we&apos;re making a difference in the world. Extrinsic values chases a way of life that does a bad job of meeting these needs&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Disconnection from Childhood Trauma&lt;/h3&gt;
&lt;p&gt;Dr. Vincent Felitti was tasked with investigating Kaiser Permanete&apos;s, a not-for-profit medical provider, fastest-growing cost--obesity. He thought, what if we try a radical diet. Have people not eat anything, and then provide them with the required nutrients to stay alive. It worked. Vincent saw amazing results. One woman, Susan, went from 408 pounds to 132 pounds. But, there was a problem. After his patients lost the weight they became depressed, anxious, and even suicidal. Susan gained back 37 pounds in three weeks. Vincent asked her what has changed since losing the weight. She thought. When Susan was obese men never looks at her, but once she got to a healthy weight a colleague asked her out. Vincent was curious, when did she initially start to gain weight? Eleven, when Susan&apos;s grandfather began to rape her. &quot;Overweight is overlooked, and that&apos;s the way I need to be.&quot;&lt;/p&gt;
&lt;h3&gt;Disconnection from Status and Respect&lt;/h3&gt;
&lt;p&gt;Many of us would expect status and respect to be linked to depression and anxiety. The lower we are on the social totem pole the more depressed we should be, right? It was found in baboons that even the alpha, the top dog, shows high degrees on depression and anxiety also. They are constantly being challenged for the perks of leader. A constant threat of displacement. Which in time, happens to all baboons when they grow old.&lt;/p&gt;
&lt;p&gt;Two social scientists studied the same behavior in humans. What they found is the wider the gap between the poor and rich, the higher the society suffers from depression and anxiety. &quot;When the status gap is too big, it creates a sense of defeat that you can&apos;t escape from.&quot; Today, more than any other time, we have a much wider status gap. &quot;The six heirs to the Walmart fortune own more [wealth] than the bottom 100 million Americans.&quot;&lt;/p&gt;
&lt;h3&gt;Disconnection from the Natural World&lt;/h3&gt;
&lt;p&gt;Just go outside, damnit.&lt;/p&gt;
&lt;h3&gt;Disconnection from a Hopeful or Secure Future&lt;/h3&gt;
&lt;p&gt;Depression causes a shrinking of the future. A fog. People with depression can barely get through the day, let alone see a possible future. So any possibility of a tomorrow becomes less and less visible. This myopia ensures further depression. Without the availability of a secure future an individual gets thrown into a downwards spiral. Depression is a negative feedback loop.&lt;/p&gt;
&lt;h3&gt;The Role of Genes and Brain Changes&lt;/h3&gt;
&lt;p&gt;A group of scientists lead by Avshalom Caspi did the most detailed study of genetic based causes of depression. They found a gene, 5-HTT, that does relate having depression. &quot;If you have a particular flavor of 5-HTT, you have a greatly increased risk of depression, but &lt;em&gt;only is a certain environment&lt;/em&gt;.&quot; So certain genes make us more vulnerable to depression and anxiety, but it doesn&apos;t condemn us. Neuroplasticity also plays a role in depression. Our brains are constantly changing, growing, and killing off unused synapses. Just because we are depressed, doesn&apos;t mean we&apos;ll always be.&lt;/p&gt;
&lt;h3&gt;Thoughts and Conclusion&lt;/h3&gt;
&lt;p&gt;&quot;You need your nausea. It is a message. It will tell us what is wrong with you.&quot; This is what a doctor told Johann after he ate an apple, coated with pesticides, causing him to almost die. If the doctor just prescribed nausea medication, then Johann would of surely died. It was a symptom, not the illness. Johann describes depression and anxiety exactly in the same terms. We feel terrible, because we need meaning in our lives, we need nature, and we need other people. It&apos;s a mourning for natural humanistic needs.&lt;/p&gt;
&lt;p&gt;Lost Connections is an interesting take on the concept of non-chemical anti-depressants, and the ailments of modern society.&lt;/p&gt;
</content:encoded></item><item><title>How Facebook Avoids Ad Blockers</title><link>https://dylanpaulus.com/posts/2019/how-fb-avoids-adblockers/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/how-fb-avoids-adblockers/</guid><pubDate>Sun, 24 Nov 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Many sites try to avoid our ad blockers through limiting content or just straight out pleaing. Other companies are looking at encrypting any kind of indicator that screams &quot;AD!&quot; through obfuscation and other fancy techniques--confusing ad blockers. Here we&apos;ll look at some interesting techniques Facebook deploys to ensure we view their ads.&lt;/p&gt;
&lt;h3&gt;What does a Facebook ad look like?&lt;/h3&gt;
&lt;p&gt;Facebook ads take the form of a card containing the text &apos;Sponsored&apos; (as shown below).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./fb_ad.png&quot; alt=&quot;Image of a Facebook Ad containing &apos;Sponsored&apos; text&quot; /&gt;&lt;/p&gt;
&lt;p&gt;At first glance blocking these ads seems simple. Look for elements with the text containing &apos;Sponsored&apos;. Maybe even look at the class names to be more specific. Then, slap on a good-ol&apos; &lt;em&gt;display: none;&lt;/em&gt;. Hold up cowboy--it&apos;s a little bit more complex than that!&lt;/p&gt;
&lt;p&gt;First, Facebook doesn&apos;t actually have &apos;Sponsored&apos; in their HTML. At least, not together as we would think. In the DOM, &apos;Sponsored&apos; is actually broken up character by character.&lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;Instead of:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;span&amp;gt;Sponsored&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In Facebook it &lt;em&gt;(kinda)&lt;/em&gt; looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;span&amp;gt;
  &amp;lt;span&amp;gt;S&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;p&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;o&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;n&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;s&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;o&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;r&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;e&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;d&amp;lt;/span&amp;gt;
&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice the &lt;em&gt;&apos;kinda&apos;&lt;/em&gt; above? Facebook actually doesn&apos;t put the text directly in the DOM. Instead, it&apos;s embeded in &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes&quot;&gt;data attributes&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So really it looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;span&amp;gt;
  &amp;lt;span data-content=&quot;S&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;p&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;o&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;n&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;s&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;o&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;r&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;e&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;span data-content=&quot;d&quot;&amp;gt;&amp;lt;/span&amp;gt;
&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Obfuscation&lt;/h3&gt;
&lt;p&gt;This kind of structure seems relatively easy to block. It can even be achieved in a few lines of CSS. We&apos;ll write a quick CSS ad blocker! It&apos;ll look for a sequence of &apos;Sponsored&apos; as data attributes, then hide it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;span[data-content=&quot;S&quot;]
  + span[data-content=&quot;p&quot;]
  + span[data-content=&quot;o&quot;]
  + span[data-content=&quot;n&quot;]
  + span[data-content=&quot;s&quot;]
  + span[data-content=&quot;o&quot;]
  + span[data-content=&quot;r&quot;]
  + span[data-content=&quot;e&quot;]
  + span[data-content=&quot;d&quot;] {
  display: none;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What&apos;s the catch? Well... I&apos;m glad you asked!&lt;br /&gt;
To block against this simple ad blocker, Facebook deploys a few techniques.&lt;/p&gt;
&lt;p&gt;First, I simplified the &lt;em&gt;true&lt;/em&gt; structure of how the &apos;Sponsored&apos; text is displayed. Remember how Facebook uses data attributes? Well, those span&apos;s are actually nested. This is to prevent the adjacency modifier seen in our CSS example &lt;code&gt;+&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;S&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;p&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;o&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;n&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;s&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;o&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;r&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;e&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;
    &amp;lt;span data-content=&quot;d&quot;&amp;gt;&amp;lt;/span&amp;gt;
  &amp;lt;/span&amp;gt;
&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But, this doesn&apos;t completely ruin our CSS ad blocker. We can refer to the parent of the data attribute and drill down.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;span
  span[data-content=&quot;S&quot;]
  + span
  span[data-content=&quot;p&quot;]
  + span
  span[data-content=&quot;o&quot;]
  + span
  span[data-content=&quot;n&quot;]
  + span
  span[data-content=&quot;s&quot;]
  + span
  span[data-content=&quot;o&quot;]
  + span
  span[data-content=&quot;r&quot;]
  + span
  span[data-content=&quot;e&quot;]
  + span
  span[data-content=&quot;d&quot;] {
  display: none;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next technique, this is the point where it gets particularly interesting, Facebook actually hides &apos;dummy&apos; DOM nodes between the &apos;Sponsored&apos; text. These values are entirely random characters, with a random number of DOM nodes between them. Invisible characters.&lt;br /&gt;
&lt;br /&gt;&lt;/p&gt;

  &lt;img alt=&quot;Animation showing the obfuscation techniques by Facebook.&quot; src=&quot;./fb_encode.gif&quot; /&gt;

&lt;p&gt;At this point our CSS ad blocker is completely broken. There is no way for us to possibly code every possible value in CSS. Ugh.&lt;/p&gt;
&lt;p&gt;We could try playing around with ids or class names, but these are pretty generic. A lot of content within the Facebook code share similar classes, so there is no unique identifier in finding an &lt;em&gt;ad&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;We&apos;ve looked at a few techniques Facebook deploys to prevent ad blockers from... blocking ads. Using data attributes instead of straight text in the DOM, nesting DOM elements to make DOM parsing more difficult, and adding random DOM nodes between characters to obfuscate the output. The next time an ad blocker doesn&apos;t completely remove all the ads on a site, try looking at the DOM. There may be some interesting techniques at play to keep the ads flowing through!&lt;/p&gt;
</content:encoded></item><item><title>On Writing Clean Code</title><link>https://dylanpaulus.com/posts/2019/clean-code/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/clean-code/</guid><pubDate>Sun, 21 Jul 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;We can all agree that writing clean code is important. It makes it easier to work in a team, and even if we&apos;re a single developer, clean code keeps our future selves happy. Ever look at your old code and wonder, &quot;What is this crap?&quot; If you said &quot;no&quot;, write more code--the feeling will come. For those who said &quot;yes&quot;, let&apos;s look at some techniques that will improve your code readability.&lt;/p&gt;
&lt;h2&gt;Use Good Names&lt;/h2&gt;
&lt;p&gt;Coming up with good names is hard, but anything is better than using &apos;foo&apos;. When creating names use something descriptive: what does the variable hold? what is the purpose of that function? Remember, we write code for humans to read!&lt;/p&gt;
&lt;p&gt;Without context of your code it&apos;s hard to say, &quot;this is what you should be naming things&quot;, but there are a few guidelines we can use when choosing names.&lt;/p&gt;
&lt;h3&gt;Booleans&lt;/h3&gt;
&lt;p&gt;Booleans are used to split code into two paths (true/false.. yes/no). When naming booleans, it helps to ask a question. For example, we might have some code that looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let content = false;

if (content) {
  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is ok, but it really doesn&apos;t give any context of what &lt;code&gt;content&lt;/code&gt; is. While naming booleans, prefix it with &lt;code&gt;is&lt;/code&gt;, &lt;code&gt;are&lt;/code&gt;, &lt;code&gt;should&lt;/code&gt;, &lt;code&gt;has&lt;/code&gt;, etc... Just something that makes the variable asking a question.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let hasContent = true;

if (hasContent) {
  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Lists/Arrays&lt;/h3&gt;
&lt;p&gt;Make lists/arrays plural--they can hold multiple values so reflect it in the naming!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let salesOrder = []; // :(
let salesOrderList = []; // :|
let salesOrders = []; // :D Yay!
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Don&apos;t be afraid of going long&lt;/h3&gt;
&lt;p&gt;Sometimes a single word doesn&apos;t explicitly explain what a piece of code does. As in what a function is supposed to do, or what a variable contains. It&apos;s perfectly fine to name something with a &lt;em&gt;sentence&lt;/em&gt;, just watch out if we start naming our variables with &lt;em&gt;paragraphs&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function doStuff() { ... } // Bad!

function getSalesOrder() { ... } // Better!

function getSalesOrderByLineId() { ... } // Even Better!

function getSalesOrderByItemIdInTheDatabaseThenValidateReturnObject() { ... } // What? Bad!
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Let the type-checker do its thing&lt;/h3&gt;
&lt;p&gt;This mostly applies to programming languages that have type checking. Using the example above with the variable name &lt;code&gt;salesOrderList&lt;/code&gt;, don&apos;t specify the type of a variable in the name. The type-checker already gives us this information. Switching languages (slightly), let&apos;s see an example of this in Typescript.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let salesOrderList: SalesOrder[] = []; // We already know the type!
let salesOrders: SalesOrder[] = []; // Better!

let nameString = &quot;Name&quot;; // :(
let name = &quot;Name&quot;; // :D
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Use the features of the language&lt;/h3&gt;
&lt;p&gt;Aside from taking advantage of a type-checker. Look at making good use of a programming language&apos;s other grouping features! What I mean by &apos;grouping features&apos; are things like &lt;strong&gt;class&lt;/strong&gt; and &lt;strong&gt;namespace&lt;/strong&gt;. There is generally no need to repeat the names of a namespace in a class. Similarly, the same can be applied to repeating class names in a method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/* It&apos;s easy to get lost what&apos;s going on. (SalesOrder.SalesOrder.SalesOrder(...)) */
namespace SalesOrder {
  class SalesOrder {
    function SalesOrder() {
      ...
    }
  }
}

/*
 * Following our naming structure, it&apos;s extremely easy to figure out what&apos;s going on
 * while not repeating ourselves.
 * (Repositories.SalesOrder.GetById(...))
 */
namespace Repositories {
  class SalesOrder {
    function GetById() {
      ...
    }
  }
}

/*
 * This is also perfectly fine, as namespaces generally get include/using/import &apos;d away
 * to not be seen.
 * (SalesOrderRepository.GetById(...))
 */
namespace Repositories {
  class SalesOrderRepository {
    function GetById() {
      ...
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Whitespace&lt;/h2&gt;
&lt;p&gt;No, this isn&apos;t tabs vs. spaces. Pick one, then roll with it. What I mean by whitespace is that consistent line-breaks and whitespace between statements of code is extremely valuable. Just like we break logical sections of code into classes/functions/files/etc, we should also separate explicit blocks of code with whitespace.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Anyone else going cross-eyed? Remember, write code for humans!
function add(a, b) {
  return a + b;
}
function doStuff(a, b) {
  let j = add(a, b);
  if (j &amp;gt; 2) {
    j = 5;
  } else {
    return a;
  }
  for (let i = 0; i &amp;lt; 20; i++) {
    j += i;
  }
  return j;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// Much better! Statements are separated by new-lines to give context,
// and makes it a lot easier to read!
function add(a, b) {
  return a + b;
}

function doStuff(a, b) {
  let j = a + b;

  if (j &amp;gt; 2) {
    j = 5;
  } else {
    return a;
  }

  for (let i = 0; i &amp;lt; 20; i++) {
    j += i;
  }

  return j;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To sum it up, leave atleast one blank line before and after:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;if/else&lt;/strong&gt; statements&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;for/while&lt;/strong&gt; loops&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;functions/methods/classes/namespaces&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and one blank line before:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;return&lt;/strong&gt; statements at the end of functions&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Functions/Methods&lt;/h2&gt;
&lt;p&gt;We can take a lot of useful ideas from functional programming (&lt;a href=&quot;/posts/functional-programming/&quot;&gt;I give an introduction of function programming here!&lt;/a&gt;) when it comes to writing clean code. Let&apos;s look at one of these ideas from the functional programming paradigm.&lt;/p&gt;
&lt;h3&gt;Only do one thing!&lt;/h3&gt;
&lt;p&gt;Functions/Methods should only do one thing. Living up to this philosophy makes testing functions easier, swapping functions or other functions trivial, and debugging a breeze!&lt;/p&gt;
&lt;p&gt;While naming our function, we are good programmers and give a good descriptive name. But, there are a few dead give aways that a function is doing more work than it should if we see &lt;code&gt;or&lt;/code&gt; or &lt;code&gt;and&lt;/code&gt; in the name.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Common occurance of OR!
function updateOrCreate() {
  ...
}

// Better!
function update() {
  ...
}

function create() {
  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Don&apos;t just avoid &lt;code&gt;or&lt;/code&gt; or &lt;code&gt;and&lt;/code&gt; while naming functions--be honest with yourself! It&apos;ll help with keeping your code more maintainable!&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Finally,&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Be Consistent!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The biggest aspect of writing clean code, even if you end up not using any of the styles above, is to be consistent! Keeping you and your team&apos;s coding style the same makes it easier to get up to speed with current projects, and any future endeavors.&lt;/p&gt;
</content:encoded></item><item><title>Leveling Up Your Terminal/Command-Line Navigation</title><link>https://dylanpaulus.com/posts/2019/level-terminal-navigation/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/level-terminal-navigation/</guid><pubDate>Mon, 17 Jun 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;One motivating factor in using a terminal is the productivity gains... that is, once you can sweep the keyboard like an 80&apos;s metal guitarist. Getting a few basic keyboard shortcuts/commands down can drastically improve the usability of the terminal. Let&apos;s take a look at a few of my favorites.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(I&apos;ll be showing off Git Bash in this article, but these commands work in most terminals)&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Movement&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Move to the end of the input&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;ctrl + e&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/eqz7oivtmwvm2lecozxv.gif&quot; alt=&quot;Move to the end of the input&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Move to the beginning of the input&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;ctrl + a&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/pcviwamsu92rsbvv1rl6.gif&quot; alt=&quot;Move to the beginning of the input&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Move between each &apos;word&apos;&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;ctrl + [arrow left/right]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/5piz8q8un1bk2ui1fw3r.gif&quot; alt=&quot;Move between each &apos;word&apos;&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;Deleting&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Delete backwards a whole &apos;word&apos;&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;ctrl + w&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/5fhignw1fjziw7x72jjh.gif&quot; alt=&quot;Delete backwards a whole &apos;word&apos;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Delete everything&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;ctrl + u&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/ijiermx0qon7zuea799t.gif&quot; alt=&quot;Delete everything&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;Open File Explorer&lt;/h3&gt;
&lt;p&gt;Opening the file explorer at the current location can be super useful. The command varies based on operating system.&lt;/p&gt;
&lt;p&gt;(Open file explorer at the current directory. Change &apos;.&apos; to be any location!)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Windows:&lt;/strong&gt; &lt;code&gt;explorer .&lt;/code&gt;&lt;br /&gt;
&lt;strong&gt;Unix/MacOS:&lt;/strong&gt; &lt;code&gt;open .&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/0xcgy3c1453zwizjrhaq.gif&quot; alt=&quot;Open File Explorer&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;History&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Rerun the last command&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;!!&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/sqofemwp8trpnsf4pwss.gif&quot; alt=&quot;Rerun the last command&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Get the full history of commands&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;history&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Rerun command from the History&lt;/strong&gt;&lt;br /&gt;
&lt;code&gt;![#number]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://thepracticaldev.s3.amazonaws.com/i/skse39zh5t8ozz9rkkax.gif&quot; alt=&quot;history&quot; /&gt;&lt;/p&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;These are shortcuts/commands I find myself going to daily that make the terminal a pleasure to deal with. Are there any I missed that you love? Let us know in the comments!&lt;/p&gt;
</content:encoded></item><item><title>Intro to Functional Programming</title><link>https://dylanpaulus.com/posts/2019/intro-functional-programming/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2019/intro-functional-programming/</guid><pubDate>Sun, 31 Mar 2019 00:00:00 GMT</pubDate><content:encoded>
&lt;p&gt;This post comes from an example I presented at &lt;a href=&quot;http://www.boisecodecamp.org/&quot;&gt;Boise Code Camp 2019&lt;/a&gt; comparing imperative and functional ways of solving problems. The goal was not to teach functional programming in its entirety, but introduce a different way of thinking that is outside of traditional approaches (loops, mutation, etc). Having a different frame of reference adds more tools to the toolbox when faced with a problem.&lt;/p&gt;
&lt;p&gt;The foundation of functional programming can be presented in three main ideas:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Immutable Data Structures&lt;/li&gt;
&lt;li&gt;Pure Functions&lt;/li&gt;
&lt;li&gt;First Class Functions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let&apos;s go quickly into what each of these bullets mean.&lt;/p&gt;
&lt;h3&gt;Immutable Data Structures&lt;/h3&gt;
&lt;p&gt;When working in a programming language like JavaScript, we can assign data to variables &lt;code&gt;let myVariable = 5;&lt;/code&gt;. But, nothing stops up from reassigning the variable to something else later on &lt;code&gt;myVariable = &quot;Now I&apos;m a string.&quot;&lt;/code&gt;. This can be dangerous--maybe another function relies on &lt;code&gt;myVariable&lt;/code&gt; to be a number, or what if some asynchronous functions are both working on &lt;code&gt;myVariable&lt;/code&gt; at the same time! We could run into merge conflicts.&lt;/p&gt;
&lt;h4&gt;Example&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;const obj = {
  a: 1,
  b: 2,
};

function addOne(input) {
  return {
    a: input.a + 1,
    b: input.b + 1,
  };
}

const newObj = addOne(obj);

newObj === obj; // false
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Pure Functions&lt;/h3&gt;
&lt;p&gt;Pure functions are side effect free. What does that mean? Well, a function that calculates an output based solely on it&apos;s input can be considered a pure function. If our function takes an input, performs a database update, then returns a value, then we contain a side effect in our code--updating the database. Calling the function multiple times might not always return the same result (out of memory, database is locked, etc). Having pure functions is crucial in helping us write bug-free, easily testable code.&lt;/p&gt;
&lt;h4&gt;Example&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;function notPureAdd(a, b) {
  return a + new Date().getMilliseconds();
}

function pureAdd(a, b) {
  return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;First Class Functions&lt;/h3&gt;
&lt;p&gt;The term First Class might seem strange, but all it means is that functions can be passed around and used just like we might use other data-types. For example, strings, ints, floats, etc. A programming language that supports first class functions allow us to pass functions into other functions. Think of this like dependency injection. If you&apos;ve worked with JavaScript first class functions are used everywhere, and we&apos;ll touch on them more in the coming examples.&lt;/p&gt;
&lt;h4&gt;Example&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;// robot expects a function to be passed in
function robot(voiceBox) {
  return voiceBox(&quot;bzzzz&quot;);
}

// console.log is a function that logs to the console
robot(console.log);
// alert is a function that shows a dialog box
robot(alert);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Comparing Imperative and Functional Programming&lt;/h3&gt;
&lt;p&gt;To show a basic comparison between imperative and functional programming let&apos;s add the numbers in an array &lt;code&gt;[1, 2, 3, 4]&lt;/code&gt; and get its sum.&lt;/p&gt;
&lt;p&gt;Imperatively we might write something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const list = [1, 2, 3, 4];

let sum = 0;

for (let i = 0; i &amp;lt; list.length; i++) {
  sum += list[i];
}

console.log(sum); // 10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Converting this to be in a functional style, we have one big problem. We mutate &lt;code&gt;sum&lt;/code&gt; to have a different value at every iteration of the list. Remember... immutable data structures.&lt;/p&gt;
&lt;p&gt;To make this code functional, let&apos;s break down how a summation is calculated.&lt;/p&gt;
&lt;p&gt;First, we start at some value, which in our case is &lt;code&gt;0&lt;/code&gt; (see the line &lt;code&gt;let sum = 0;&lt;/code&gt;)! Next, we pull out the first item in the array &lt;code&gt;1&lt;/code&gt; and add it to our sum. Now we have &lt;code&gt;0 + 1 = 1&lt;/code&gt;. We then repeat this step pulling out &lt;code&gt;2&lt;/code&gt; and adding it to the sum &lt;code&gt;1 + 2 = 3&lt;/code&gt;. This continues on until we have traversed the length of the array.&lt;/p&gt;
&lt;p&gt;To visualize this in a different way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;0 + [1,2,3,4] 0 + 1 + [2,3,4] 1 + 2 + [3,4] 3 + 3 + [4] 6 + 4 10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can think of this algorithm as two separate functions, first we need some way of adding numbers together.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function add(a, b) {
  return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Easy!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Next we&apos;ll need some way of looping through an array given to us. Since most functional programming generally relies on recursion instead of loops, we&apos;ll create a recursive function that&apos;ll loop through our array. Let&apos;s look at what that may look like.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function loop(list, index = 0) {
  if (!list || index &amp;gt; list.length - 1) {
    // We&apos;re at the end of the list
    return;
  }

  return loop(list, index + 1);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this function we take the list we want to loop through, and an index we&apos;ll use to determine the position in the list we&apos;re currently at. If we reach the end of the list, or an invalid list is given, then we&apos;re done looping. If not, we&apos;ll call &lt;code&gt;loop&lt;/code&gt; again, incrementing the index. Try adding a &lt;code&gt;console.log(list[index])&lt;/code&gt; inside the loop function, before &lt;code&gt;return loop(list, index + 1);&lt;/code&gt;! We should see &lt;code&gt;1 2 3 4&lt;/code&gt; printed to the console!&lt;/p&gt;
&lt;p&gt;To finally sum our array, we&apos;ll need to combine both our &lt;code&gt;loop&lt;/code&gt; and &lt;code&gt;add&lt;/code&gt; functions. Keep in mind our algorithm above while going through this example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function loop(list, accu = 0, index = 0) {
  if (!list || index &amp;gt; list.length - 1) {
    return accu;
  }

  const result = add(accu, list[index]);

  return loop(list, result, index + 1);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We rearranged some arguments in the &lt;code&gt;loop&lt;/code&gt; function. Now we have an &lt;code&gt;accu&lt;/code&gt; parameter (accumulation), which will keep track of the sum at a given place in the list. We also directly use our &lt;code&gt;add&lt;/code&gt; function to get the result of the &lt;code&gt;accu&lt;/code&gt; added with the current item in the list. If we &lt;code&gt;console.log(loop(list));&lt;/code&gt; we should get the result &lt;code&gt;10&lt;/code&gt; printed to the console!&lt;/p&gt;
&lt;p&gt;How about we take this a step further? What if we didn&apos;t want to sum up the list of numbers, but instead multiply them? Currently we&apos;d have to copy our &lt;code&gt;loop&lt;/code&gt; function, paste it, and change &lt;code&gt;add&lt;/code&gt; to be something else (&lt;code&gt;multiply&lt;/code&gt; maybe?). What a pain! Remember first class functions? We&apos;ll we can use that idea here to make our code greatly more generic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function loop(func, list, accu = 0, index = 0) {
  if (!list || index &amp;gt; list.length - 1) {
    return accu;
  }

  const result = func(accu, list[index]);

  return loop(func, list, result, index + 1);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the example above, the only thing that changed is that we now added a new argument to &lt;code&gt;loop&lt;/code&gt; that takes a function. Instead of &lt;code&gt;add&lt;/code&gt;, we&apos;ll call our passed in function to get a result. Now we can very easily &lt;code&gt;add&lt;/code&gt;, &lt;code&gt;multiply&lt;/code&gt;, &lt;code&gt;subtract&lt;/code&gt;, etc our list.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;loop(add, list);&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;loop(function(a, b) { return a * b; }, list);&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We are no longer just looping through our array, but folding our array like paper until we reach a single result. In functional programming this function might be called &lt;code&gt;fold&lt;/code&gt;, and in Javascript we see it as &lt;code&gt;reduce&lt;/code&gt;!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function reduce(func, list, accu = 0, index = 0) {
  if (!list || index &amp;gt; list.length - 1) {
    return accu;
  }

  const result = func(accu, list[index]);

  return reduce(func, list, result, index + 1);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;End&lt;/h3&gt;
&lt;p&gt;We looked at the basics of functional programming, and how breaking down a problem can give us different solutions to the same problem. &lt;code&gt;reduce&lt;/code&gt; is seen as the foundation for other operations like &lt;code&gt;map()&lt;/code&gt; or &lt;code&gt;filter()&lt;/code&gt;. Here is my test for you, how can we implement these two functions only using our &lt;code&gt;reduce()&lt;/code&gt; we just created?&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Hint&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Remember the algorithm for reduce?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;0 + [1,2,3,4] 0 + 1 + [2,3,4] 1 + 2 + [3,4] 3 + 3 + [4] 6 + 4 10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What if instead of starting with &lt;code&gt;0&lt;/code&gt; we start with an &lt;code&gt;[]&lt;/code&gt; array instead ?&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://jsbin.com/femoburako/1/edit?js,console&quot;&gt;Answer&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Introducing React-Scroll-To v2</title><link>https://dylanpaulus.com/posts/2018/introducing-react-scroll-to-v2/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/introducing-react-scroll-to-v2/</guid><pubDate>Sat, 03 Nov 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The latest version of a React component I maintain just released, v2 of react-scroll-to. First, it started out as a component I needed, but over time a few people started using it. Because it was initially created for my specific use-case it started to show its warts when new features were ask for. The goals for v2 were two-part: introduce a more flexible API and implement some highly asked for features (scroll by a ref and smooth scrolling).&lt;/p&gt;
&lt;p&gt;So what is react-scroll-to? React-scroll-to is a pretty simple component. It allows the control of scrolling either the brower&apos;s window, or a component (overflow) to a specific point.&lt;/p&gt;
&lt;p&gt;We&apos;ll look at a few examples to show off what react-scroll-to can do.&lt;br /&gt;
&lt;em&gt;(As a note, in this post I&apos;ll only be showing render props, but react-scroll-to also supports higher order components. Examples can be found at: https://github.com/ganderzz/react-scroll-to)&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Basics&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  render() {
    return &amp;lt;ScrollTo&amp;gt;{({ scrollTo }) =&amp;gt; &amp;lt;a onClick={() =&amp;gt; scrollTo({ y: 500 })}&amp;gt;Scroll to Bottom&amp;lt;/a&amp;gt;}&amp;lt;/ScrollTo&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the component above we&apos;re importing the &lt;code&gt;ScrollTo&lt;/code&gt; component from react-scroll-to. This is a render prop, so we&apos;ll pass a function as its children. &lt;code&gt;ScrollTo&lt;/code&gt;&apos;s children has an object as its parameter--this is so the consumer of this component can choose, exactly, what properties they care about. Generally we&apos;ll only need &lt;code&gt;scrollTo&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;scrollTo()&lt;/code&gt; is a function, when called, will either:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Scroll the brower&apos;s window based on the given parameters (in this case, scroll 500px from the top of the page)&lt;/li&gt;
&lt;li&gt;Scroll all &lt;code&gt;&amp;lt;ScrollArea&amp;gt;&lt;/code&gt; components, inside &lt;code&gt;&amp;lt;ScrollTo /&amp;gt;&lt;/code&gt;, to the given parameters (We&apos;ll see this later)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;Note: react-scroll-to uses absolute positions--the ability to use relative positioning is coming soon!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;When a user clicks on the link, in the example, we&apos;ll see the window scroll down 500px!&lt;/p&gt;
&lt;h3&gt;Scroll Area&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;&amp;lt;ScrollArea&amp;gt;&lt;/code&gt; component gives &lt;code&gt;scrollTo&lt;/code&gt; the ability to scroll components, instead of the window.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo, ScrollArea } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  render() {
    return (
      &amp;lt;ScrollTo&amp;gt;
        {({ scrollTo }) =&amp;gt; (
          &amp;lt;&amp;gt;
            &amp;lt;a onClick={() =&amp;gt; scrollTo({ y: 500 })}&amp;gt;Scroll to Bottom&amp;lt;/a&amp;gt;

            &amp;lt;ScrollArea&amp;gt;My long content...&amp;lt;/ScrollArea&amp;gt;
          &amp;lt;/&amp;gt;
        )}
      &amp;lt;/ScrollTo&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since a &lt;code&gt;&amp;lt;ScrollArea/&amp;gt;&lt;/code&gt; component lives as a child component of &lt;code&gt;&amp;lt;ScrollTo /&amp;gt;&lt;/code&gt;, whenever we call &lt;code&gt;scrollTo()&lt;/code&gt;, it&apos;ll scroll all of the &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; components. So in this example when the link is clicked only the &quot;My long content...&quot; area will scroll.&lt;/p&gt;
&lt;p&gt;But what if we have multiple &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; components?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo, ScrollArea } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  render() {
    return (
      &amp;lt;ScrollTo&amp;gt;
        {({ scrollTo }) =&amp;gt; (
          &amp;lt;&amp;gt;
            &amp;lt;a onClick={() =&amp;gt; scrollTo({ y: 500 })}&amp;gt;Scroll to Bottom&amp;lt;/a&amp;gt;

            &amp;lt;ScrollArea&amp;gt;My long content...&amp;lt;/ScrollArea&amp;gt;

            &amp;lt;ScrollArea&amp;gt;My long content 2...&amp;lt;/ScrollArea&amp;gt;
          &amp;lt;/&amp;gt;
        )}
      &amp;lt;/ScrollTo&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the case where more than one &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; components exist in a &lt;code&gt;&amp;lt;ScrollTo /&amp;gt;&lt;/code&gt;, both components will scroll.&lt;/p&gt;
&lt;p&gt;What if we only want to scroll one of the &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; components?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo, ScrollArea } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  render() {
    return (
      &amp;lt;ScrollTo&amp;gt;
        {({ scrollTo }) =&amp;gt; (
          &amp;lt;&amp;gt;
            &amp;lt;a onClick={() =&amp;gt; scrollTo({ id: &quot;content-two&quot;, y: 500 })}&amp;gt;Scroll to Bottom&amp;lt;/a&amp;gt;

            &amp;lt;ScrollArea&amp;gt;My long content...&amp;lt;/ScrollArea&amp;gt;

            &amp;lt;ScrollArea id=&quot;content-two&quot;&amp;gt;My long content 2...&amp;lt;/ScrollArea&amp;gt;
          &amp;lt;/&amp;gt;
        )}
      &amp;lt;/ScrollTo&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By adding an &lt;code&gt;id&lt;/code&gt; property to a &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; we are able to reference that component in our &lt;code&gt;scrollTo()&lt;/code&gt; function. &lt;code&gt;scrollTo()&lt;/code&gt; then takes another field, &apos;id&apos;, that&apos;ll scroll any &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; component that matches that id (id&apos;s must be unique).&lt;/p&gt;
&lt;h3&gt;V2 Features&lt;/h3&gt;
&lt;p&gt;scrollTo and ScrollArea have both existed in v1; let&apos;s look at branch new features.&lt;/p&gt;
&lt;h5&gt;Smooth Scrolling&lt;/h5&gt;
&lt;p&gt;Smooth scrolling couldn&apos;t be simpler. By adding a &lt;code&gt;smooth: true&lt;/code&gt; property to the &lt;code&gt;scrollTo()&lt;/code&gt; object, react-scroll-to will automatically apply smooth scrolling.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  render() {
    return (
      &amp;lt;ScrollTo&amp;gt;
        {({ scrollTo }) =&amp;gt; (
          &amp;lt;a onClick={() =&amp;gt; scrollTo({ x: 200, smooth: true })}&amp;gt;
            {/* Oh yeah, we can scroll by x also! */}
            Scroll to Bottom
          &amp;lt;/a&amp;gt;
        )}
      &amp;lt;/ScrollTo&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h5&gt;Scroll by Ref&lt;/h5&gt;
&lt;p&gt;Maybe instead of using a &lt;code&gt;&amp;lt;ScrollArea /&amp;gt;&lt;/code&gt; component, we have a ref to a component we want to scroll. Or maybe instead we want to scroll a component outside &lt;code&gt;&amp;lt;ScrollTo /&amp;gt;&lt;/code&gt;&apos;s children. Now we have the ability by providing the ref through the &lt;code&gt;scrollTo()&lt;/code&gt; argument object!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { ScrollTo } from &quot;react-scroll-to&quot;;

export default class MyComponent extends Component {
  myRef = React.createRef();

  render() {
    return (
      &amp;lt;ScrollTo&amp;gt;
        {({ scrollTo }) =&amp;gt; (
          &amp;lt;a onClick={() =&amp;gt; scrollTo({ ref: this.myRef, y: 200, smooth: true })}&amp;gt;
             Scroll to Bottom
          &amp;lt;/a&amp;gt;
        )}
      &amp;lt;/ScrollTo&amp;gt;

      &amp;lt;div ref={this.myRef}&amp;gt;
        I&apos;m outside ScrollTo!
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;V2 of react-scroll-to provides a lot of behind-the-scenes structural changes that&apos;ll allow for a better developer experience while implementing new features. We also added many new features that have been in demand. As things solidify, we hope to expose hooks in react-scroll-to to allow even more flexibility.&lt;/p&gt;
&lt;p&gt;Check it out: &lt;a href=&quot;https://github.com/ganderzz/react-scroll-to&quot;&gt;react-scroll-to&lt;/a&gt;&lt;br /&gt;
Examples: &lt;a href=&quot;https://ganderzz.github.io/react-scroll-to/&quot;&gt;Click Here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>React: Controlling Rendering with Keys</title><link>https://dylanpaulus.com/posts/2018/react-controlling-rendering-with-keys/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/react-controlling-rendering-with-keys/</guid><pubDate>Thu, 18 Oct 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;code&gt;key&lt;/code&gt;, the property we throw some value into to suppress warnings. This property is used by React to determine when a component is deleted, updated, or created. We generally don&apos;t interact much with the &lt;code&gt;key&lt;/code&gt; prop--except in loops.&lt;/p&gt;
&lt;p&gt;My team recently ran into an issue lately--how do we rerender all child components when a state has changed? The simplest approach... you guessed it, &lt;code&gt;key&lt;/code&gt;!&lt;/p&gt;
&lt;p&gt;Let&apos;s take a look.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Parent extends Component {
  state = {
    key: true,
    count: 0,
  };

  handleChildUnmount = () =&amp;gt; {
    this.setState((prevProps) =&amp;gt; ({ count: prevProps.count + 1 }));
  };

  toggleKey = () =&amp;gt; {
    this.setState((prevProps) =&amp;gt; ({ key: !prevProps.key }));
  };

  render() {
    const { key, count } = this.state;

    return (
      &amp;lt;div&amp;gt;
        &amp;lt;button onClick={this.toggleKey}&amp;gt;Toggle Child Key&amp;lt;/button&amp;gt;
        &amp;lt;Child key={key} count={count} onUnmount={this.handleChildUnmount} /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

class Child extends Component {
  componentWillUnmount() {
    this.props.onUnmount();
  }

  render() {
    return &amp;lt;div&amp;gt;Total Renders: {this.props.count}&amp;lt;/div&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://codesandbox.io/s/48zl4zoyv0&quot;&gt;&lt;img src=&quot;https://codesandbox.io/static/img/play-codesandbox.svg&quot; alt=&quot;Edit react-scroll-to&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this example we are toggling the &lt;code&gt;key&lt;/code&gt; prop of our Child component between &lt;em&gt;true&lt;/em&gt; and &lt;em&gt;false&lt;/em&gt;. We then keep track every time the Child unmounts through a callback to increment the Parent&apos;s state. When we toggle the &lt;code&gt;key&lt;/code&gt; prop, we will see the counter increment each time. This is, because React uses the key to determine if a component has changed. Since we are changing the key each time React will see our component has updates, and rerender the Child component.&lt;/p&gt;
&lt;p&gt;This is the easiest way to cause a rerender of a child component (and all children of the child), and shows the power of understanding the&lt;code&gt;key&lt;/code&gt; prop!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; Even if a child component returns &lt;em&gt;false&lt;/em&gt; in a &lt;code&gt;shouldComponentUpdate&lt;/code&gt;, changing the key prop will cause it to rerender anyway (Try it in the CodeSandbox above!).&lt;/p&gt;
</content:encoded></item><item><title>Tips on Improving FabricJS Speed</title><link>https://dylanpaulus.com/posts/2018/tips-on-improving-fabricjs-speed/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/tips-on-improving-fabricjs-speed/</guid><pubDate>Thu, 11 Oct 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;http://fabricjs.com/&quot;&gt;FabricJS&lt;/a&gt; is an awesome library that handles &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API&quot;&gt;Canvas&lt;/a&gt; interactions and rendering. Inherently it is a pretty performant library, but recently we ran into an issue where we needed to render ~8mb of json data (10k objects). Given any framework, it is no easy task to render this much data. The biggest culprit while rendering a lot of objects is renders (or rerenders). When the canvas has to show any change, it renders the &lt;em&gt;entire&lt;/em&gt; canvas. This includes clearing the canvas, looping through each object, and drawing it. In this post I&apos;ll go through some of the techniques we used to improve interaction and rendering speed.&lt;/p&gt;
&lt;h4&gt;Cut out the basics&lt;/h4&gt;
&lt;p&gt;FabricJS has a &lt;a href=&quot;https://github.com/fabricjs/fabric.js/wiki/Optimizing-performance&quot;&gt;small post about optimizing performance&lt;/a&gt;. All great tips, but the one to look at is setting &lt;code&gt;renderOnAddRemove&lt;/code&gt; to false. Adding this property to the canvas will prevent Fabric from re-rendering if a shape is added or deleted. This gives huge speed improvements on initial loads while adding a lot of shapes to the canvas.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const canvas = new fabric.Canvas(&quot;myId&quot;, { renderOnAddRemove: false });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Caution:&lt;/em&gt; &lt;code&gt;canvas.renderAll();&lt;/code&gt; will have to be called whenever we want a change to show on the canvas&lt;/p&gt;
&lt;h4&gt;Enliven over loadFromJSON&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;loadFromJSON&lt;/code&gt; is a really helpful function when we want to deserialize JSON to the canvas, but it comes with some draw-backs. First, &lt;code&gt;loadFromJSON&lt;/code&gt; will clear the canvas before it loads the JSON objects. This can be bad if we added shapes to the canvas before loading then JSON. Second, it will call &lt;code&gt;renderAll&lt;/code&gt; once the JSON is finished. This is bad when we have additional operations to perform after our JSON object is loaded (ie. adding more shapes or selecting then).&lt;/p&gt;
&lt;p&gt;Alternatively we can use a function called &lt;code&gt;enlivenObjects&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const canvas = new fabric.Canvas(&quot;myId&quot;, { renderOnAddRemove: false }););
// enlivenObjects([array of json objects], [callback])
fabric.util.enlivenObjects([{}, {}, {}], (objs) =&amp;gt; {
    objs.forEach((item) =&amp;gt; {
        canvas.add(item);
    });
    canvas.renderAll(); // Make sure to call once we&apos;re ready!
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;enlivenObjects&lt;/code&gt; takes in an array of the serialized FabricJS JSON (found in: [json].objects), and returns the Fabric object representation of it. We use a callback to get the parsed objects. This is similar to how &lt;code&gt;loadFromJSON&lt;/code&gt; handles &lt;a href=&quot;https://github.com/fabricjs/fabric.js/blob/464708aafccc0d5a4e3a7b6604db2d00ad3bc475/src/mixins/canvas_serialization.mixin.js#L55&quot;&gt;loading behind the scenes&lt;/a&gt;! The bonus here is there are no unneeded renders and canvas clearing. We can control when the canvas gets rendered!&lt;/p&gt;
&lt;h4&gt;Don&apos;t Canvas Everything&lt;/h4&gt;
&lt;p&gt;The more shapes on the canvas, the more work Fabric has to do on a render. One way around this is to take out any shapes that don&apos;t need to be manipulated or animated. We achieve this by converting those un-interactive layers to an image &lt;code&gt;canvas.toDataURL(&quot;png&quot;);&lt;/code&gt; and rendering it as an HTML &lt;code&gt;&amp;lt;img /&amp;gt;&lt;/code&gt; tag. Then, overlay the canvas on top of the image; only using the canvas for the interactive bits while showing everything.&lt;/p&gt;
</content:encoded></item><item><title>React: Not Everything is State</title><link>https://dylanpaulus.com/posts/2018/not-everything-is-state/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/not-everything-is-state/</guid><pubDate>Fri, 05 Oct 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When working with React we get introduced to state as a way if storing component&apos;s data. There is another way that generally gets overlooked: class properties.&lt;/p&gt;
&lt;h4&gt;Example&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;class AnnoyingButton extends React.Component {
  intervalId = null; // Here!
  id = generateUniqueId(); // Here!

  state = {
    isDisabled: false,
  };

  componentDidMount() {
    this.intervalId = setInterval(() =&amp;gt; {
      this.setState(({ isDisabled }) =&amp;gt; ({
        isDisabled: !isDisabled,
      }));
    }, 100);
  }

  componentWillUnmount() {
    console.log(`Unmounting ID: ${this.id}`);
    clearInterval(this.intervalId);
  }

  render() {
    return &amp;lt;button disabled={this.state.isDisabled} /&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing special about the component; the interesting bits are the &lt;code&gt;id&lt;/code&gt; and &lt;code&gt;intervalId&lt;/code&gt; variables. We need some way of preventing memory leaks when the component unmounts. In componentDidMount we save the interval&apos;s ID to a class property. Then, use the property to clear the interval and &lt;code&gt;console.log&lt;/code&gt; the component&apos;s unique ID.&lt;/p&gt;
&lt;p&gt;You might be thinking, &quot;Why chouldn&apos;t we just store this information in the component&apos;s state?&quot; React re-renders the component, and any child components, when the state changes. If the render method never uses a piece of the state it could be causing unwanted renders--making your application slower!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When to use class properties:&lt;/strong&gt; If state needs to be stored, but is never used as a part of the view/render of a component.&lt;/p&gt;
</content:encoded></item><item><title>Write Software that Evolves</title><link>https://dylanpaulus.com/posts/2018/write-software-that-evolves/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/write-software-that-evolves/</guid><pubDate>Sun, 29 Jul 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In software development, we can easily get trapped in &lt;a href=&quot;https://en.wikipedia.org/wiki/Analysis_paralysis&quot;&gt;analysis paralysis&lt;/a&gt;. Having the foresight to make all the correct decisions is hard. We make hundreds, if not thousands, of decisions during the lifetime of our software, and we&apos;re likely to get something wrong. Instead of trying to get every minutia correct before starting a project, we should aim to write software that can evolve.&lt;/p&gt;
&lt;h3&gt;Continuous Minimum Viable Product Development&lt;/h3&gt;
&lt;p&gt;One approach to combat the constant changing of requirements is to strive for continuous minimum viable product (MVP) development. An MVP is the most basic version of a feature or application that satisfies a need. For example, let&apos;s say our client wants the ability to view some information. We may only design a page with a table that holds the data (We wouldn&apos;t add additional features like filtering or graphs). Notice how I said &lt;em&gt;continuous&lt;/em&gt;. This process shouldn&apos;t end after the application/feature is released. Keeping improvements incremental and small allows us to be flexible in our requirements. Do no more or less than what&apos;s being asked.&lt;/p&gt;
&lt;h3&gt;Lazy Evaluation&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;“I’m sure the user would need this feature. It’s easy, I’ll just add it”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This kind of thinking is a killer to flexible software. First, every line of code has a cost. Not only are there time, money, and energy in initially writing the code, but also the maintenance and surface area for bugs create its own cost. Second, the feature added could never be used by the user or just wrong! In the best scenario, this doubles the amount of work adding the feature.&lt;/p&gt;
&lt;p&gt;Instead of eagerly evaluating requirements, flexible software works best through lazy evaluation. Wait for the client/stakeholder/user to ask for a feature before implementing it (even on improvements you know they&apos;ll ask for). Lazy evaluation has a few benefits. It reduces adding features the user won&apos;t use--they asked for it. It also allows us to really understand what the user is really asking for. Instead of creating something then asking, &quot;is this what you want?&quot; we&apos;re able to get upfront the ideal process.&lt;/p&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Instead of picking a target and firing--hoping we hit something, combining continuous MVP and lazy evaluation keeps us agile. It allows firing in a direction and incrementally changing course as the target moves. Of course, do your homework and gather requirements beforehand, but aim for software that can evolve over time instead of trying to get it right from the start.&lt;/p&gt;
</content:encoded></item><item><title>Part Two: Using Typescript with Redux</title><link>https://dylanpaulus.com/posts/2018/using-typescript-with-redux-part-two/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/using-typescript-with-redux-part-two/</guid><pubDate>Sun, 15 Jul 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://codesandbox.io/s/5w70j1916l&quot;&gt;&lt;img src=&quot;https://codesandbox.io/static/img/play-codesandbox.svg&quot; alt=&quot;Click Here&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Last time we went through using Typescript with React, and setup a small counter application. A lot of applications out there use Redux. A common pain-point for me was how to setup Typescript with Redux--it&apos;s a common hurdle with my team also. Though Redux is a totally different library, it holds a big share of the state management market in React applications. In part two we&apos;ll take a detour from base React, and look at converting our counter to using Redux!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: Same with part one, I&apos;m going to assume Typescript, and now Redux, is setup and compiles. This is a write-up on integrating types, and less on how to setup a project.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Actions&lt;/h3&gt;
&lt;p&gt;We&apos;ll start out creating a few actions for our counter.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Action Types
export const INCREMENT = &quot;INCREMENT&quot;;
export const DECREMENT = &quot;DECREMENT&quot;;

export type ActionTypes = typeof INCREMENT | typeof DECREMENT;

export interface IAction {
  type: ActionTypes;
  payload: IPayload;
}

export interface IPayload {
  amount: number;
}

// Action Creators
export function increment(amount: number): IAction {
  return {
    type: INCREMENT,
    payload: {
      amount,
    },
  };
}

export function decrement(amount: number): IAction {
  return {
    type: DECREMENT,
    payload: {
      amount,
    },
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Going from top to bottom. We start out creating a few action types: &lt;em&gt;INCREMENT&lt;/em&gt; and &lt;em&gt;DECREMENT&lt;/em&gt;. This will allow us to reuse these strings as types, and get rid of any &apos;magic strings&apos;. Creating action types improves our code so we only have one place to update this value if our type should change. Additionally, reduces bugs that can occur due to human error (eg. we accidently put &apos;inCREMENT&apos; or &apos;increment&apos; instead of &apos;INCREMENT&apos;).&lt;/p&gt;
&lt;p&gt;Moving on, we hit a Typescript type and a few interfaces. In &lt;em&gt;ActionTypes&lt;/em&gt; we use a union type to say, &quot;we can use any of these types&quot;. This will come in handy later. Next, we define a general interface for our action creators. We provide the required Redux &lt;em&gt;type&lt;/em&gt; property that reuses &lt;em&gt;ActionTypes&lt;/em&gt;. To keep different actions similar, we&apos;ll use payload to deliver a &apos;value&apos; we want our reducer to work on. For the counter, we&apos;ll use &lt;strong&gt;IPayload&lt;/strong&gt; which has one property &lt;em&gt;amount&lt;/em&gt; which is a number. We&apos;ll use this to set the amount we&apos;ll either increment or decrement the count.&lt;/p&gt;
&lt;p&gt;Finally, we&apos;ll create an action creator for both increment and decrementing our counter. These functions are pretty straightforward. They are both functions that take a number, &lt;em&gt;amount&lt;/em&gt;, and returns an &lt;em&gt;IAction&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;Reducer&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;export const defaultState = {
  count: 0,
};

export function rootReducer(state = defaultState, action: IAction) {
  switch (action.type) {
    case INCREMENT:
      return {
        count: state.count + action.payload.amount,
      };

    case DECREMENT:
      return {
        count: state.count - action.payload.amount,
      };

    default:
      return state;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I won&apos;t spend too much time on the reducer as Typescript doesn&apos;t play much role here (in this example). We&apos;ll export our &lt;em&gt;defaultState&lt;/em&gt; to use later!&lt;/p&gt;
&lt;h3&gt;Component&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;interface IStateToProps {
  count: number;
}

interface IDispatchToProps {
  increment: typeof increment;
  decrement: typeof decrement;
}

type AllProps = IStateToProps &amp;amp; IDispatchToProps;

class App extends React.Component&amp;lt;AllProps&amp;gt; {
  private handleClick = (event: React.MouseEvent&amp;lt;HTMLButtonElement&amp;gt;) =&amp;gt; {
    const type: string = event.currentTarget.title;

    if (type === &quot;decrement&quot;) {
      this.props.decrement(1);
    } else {
      this.props.increment(2);
    }
  };

  public render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;button title=&quot;decrement&quot; onClick={this.handleClick}&amp;gt;
          -
        &amp;lt;/button&amp;gt;
        {this.props.count}
        &amp;lt;button title=&quot;increment&quot; onClick={this.handleClick}&amp;gt;
          +
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export const ConnectedApp = connect&amp;lt;IStateToProps, IDispatchToProps&amp;gt;(
  (state: typeof defaultState) =&amp;gt; ({
    count: state.count
  }),
  {
    increment,
    decrement
  }
)(App);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example we&apos;re using a library &lt;em&gt;react-redux&lt;/em&gt;--making it easier to connect React components to Redux. Starting out, we create two interfaces that we&apos;ll use both as &lt;strong&gt;App&lt;/strong&gt;&apos;s props and in the &lt;code&gt;connect()&lt;/code&gt; function at the bottom of the code.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;IStateToProps&lt;/strong&gt; we tell Typescript what the mapped state will be named. In our case we&apos;ll keep the name &lt;em&gt;count&lt;/em&gt;.&lt;br /&gt;
&lt;strong&gt;IDispatchToProps&lt;/strong&gt; we define what actions our component will get. Using &lt;code&gt;typeof&lt;/code&gt; we can easily tell Typescript to reuse the implied type definition of &lt;em&gt;increment&lt;/em&gt; and &lt;em&gt;decrement&lt;/em&gt; (our actions).&lt;/p&gt;
&lt;p&gt;Next, we create a new type that combines both &lt;em&gt;IStateToProps&lt;/em&gt; and &lt;em&gt;IDispatchToProps&lt;/em&gt;. This is more for convenience as we see in &lt;strong&gt;App&lt;/strong&gt;&apos;s prop definition. We could of also used &lt;code&gt;class App extends React.Component&amp;lt;IStateToProps &amp;amp; IDispatchToProps&amp;gt;&lt;/code&gt; and avoided the need for &lt;em&gt;AllProps&lt;/em&gt;. Combining all the props to a type becomes valuable when using multiple lifecycle hooks (&lt;code&gt;shouldComponentUpdate(nextProps: AllProps)&lt;/code&gt;), or multiple functions that work off the props!&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;App&lt;/strong&gt; component is pretty similar to our part one example, so we&apos;ll skip this and look at the &lt;code&gt;connect()&lt;/code&gt; function.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;connect()&lt;/code&gt; is a generic type that can take three types &lt;code&gt;connect&amp;lt;IStateToProps, IDispatchToProps, IProps&amp;gt;()&lt;/code&gt;. Going from left to right--first is the type definition for stateToProps. This is the connecting component&apos;s props we&apos;re mapping the Redux &lt;strong&gt;state&lt;/strong&gt; to. Second, the type definition for dispatchToProps. This is the connecting component&apos;s props we&apos;re mapping Redux &lt;strong&gt;actions&lt;/strong&gt; to. Lastly, we&apos;re not using it in this example, but we can provide the props of our component we&apos;re connecting.&lt;/p&gt;
&lt;p&gt;We&apos;ve successfully converted our counter to Redux, and provided useful types also!&lt;/p&gt;
</content:encoded></item><item><title>Generic Type Arguments in JSX Elements</title><link>https://dylanpaulus.com/posts/2018/generic-jsx-type-argument/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/generic-jsx-type-argument/</guid><pubDate>Sat, 02 Jun 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Typescript recently released generic type arguments for JSX in their 2.9 release. It&apos;s a mouthfull, but what does that mean for us? A common use-case I&apos;m excited for is allowing consumers of libraries to extend a component&apos;s props. Using [dynamic components]({% post_url 2017-07-26-injecting-react-tag-types %}) we&apos;ll look at allowing our components to be extended even more.&lt;/p&gt;
&lt;h3&gt;What Are Generic Type Arguments?&lt;/h3&gt;
&lt;p&gt;As shown in the &lt;a href=&quot;https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#generic-type-arguments-in-jsx-elements&quot;&gt;Typescript release notes&lt;/a&gt;, generic type arguments are a way to create components using Typescript&apos;s generics syntax. Below is a side-by-side comparison of the old way vs. using generic type arguments.&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;The Old Way:&lt;/strong&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;// Notice color isn&apos;t defined as a prop, and will error out normally
function Div(props: { value: string }) {
  const { value, ...rest } = this.props;

  return &amp;lt;div {...rest} /&amp;gt;;
}

// Using spread, we can trick Typescript into ignoring that color will be a prop
// on Div
function App() {
  return &amp;lt;Div {...{ color: &quot;red&quot; }} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;&lt;strong&gt;Generic Type Arguments:&lt;/strong&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;// Notice our new generic on the component
function Div&amp;lt;T extends object&amp;gt;(props: { value: string } &amp;amp; T) {
    const { value, ...rest } = props as any; // spreading on generics not yet supported

    return &amp;lt;div {...rest} /&amp;gt;
}

interface IAdditionalProps {
    color: string;
}

// We can tell typescript our Div element has additional properties!
function App() {
    // Generic Type Arguments!
    return &amp;lt;Div&amp;lt;IAdditionalProps&amp;gt; color=&quot;red&quot; value=&quot;TEXT!!!&quot; /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the same can be used with class components:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Notice our new generic on the component
class Div&amp;lt;T extends object&amp;gt; extends React.Component&amp;lt;{ value: string } &amp;amp; T&amp;gt; {
    public render() {
        const { value, ...rest } = this.props as any;

        return &amp;lt;div {...rest} /&amp;gt;
    }
}

interface IAdditionalProps {
    color: string;
}

// We can tell typescript our Div element has additional properties!
function App() {
    return &amp;lt;Div&amp;lt;IAdditionalProps&amp;gt; color=&quot;red&quot; value=&quot;TEXT!!&quot; /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Dynamic Elements&lt;/h3&gt;
&lt;p&gt;Let&apos;s say we have a &lt;strong&gt;MenuItem&lt;/strong&gt; component that could be overloaded with either a Router link component, or a html &lt;em&gt;a&lt;/em&gt; tag. One way we might write this...&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;interface IProps {
  tag: React.ReactNode;
  children: React.ReactNode;
}

function MenuItem({ tag, children, ...rest }: IProps) {
  const Tag: React.ReactType = tag || &quot;a&quot;;

  return &amp;lt;Tag {...rest}&amp;gt;{children}&amp;lt;/Tag&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;MenuItem&lt;/strong&gt; works perfect fine as a component, but when it&apos;s time to add additional properties, Typescript will yell. For example, the &lt;em&gt;a&lt;/em&gt; tag needs a &lt;em&gt;href&lt;/em&gt; prop. We don&apos;t want to hardcode &lt;em&gt;href&lt;/em&gt;, because we can inject any type of element through the &lt;em&gt;tag&lt;/em&gt; prop (React Router, button, etc).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;MenuItem tag=&quot;a&quot; href=&quot;http://google.com&quot;&amp;gt;Click Me!&amp;lt;/MenuItem&amp;gt; // Error because href isn&apos;t defined in IProps!
&amp;lt;MenuItem tag={Link} to=&quot;/home&quot;&amp;gt;Home&amp;lt;/MenuItem&amp;gt; // Error because to isn&apos;t defined in IProps!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can fix our errors using generic type arguments.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;interface IProps {
  tag: React.ReactNode;
  children: React.ReactNode;
}

function MenuItem&amp;lt;T extends object&amp;gt;(props: IProps &amp;amp; T) {
  const { tag, children, ...rest } = props as any;
  const Tag: React.ReactType = tag || &quot;a&quot;;

  return (
      &amp;lt;Tag {...rest}&amp;gt;
          {children}
      &amp;lt;/Tag&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the consumer of our &lt;strong&gt;MenuItem&lt;/strong&gt; component can tell us what additional properties are needed!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;MenuItem&amp;lt;{ href: string }&amp;gt; tag=&quot;a&quot; href=&quot;http://google.com&quot;&amp;gt;Click Me!&amp;lt;/MenuItem&amp;gt; // Success!
&amp;lt;MenuItem&amp;lt;{ to: string }&amp;gt; tag={Link} to=&quot;/home&quot;&amp;gt;Home&amp;lt;/MenuItem&amp;gt; // Success!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Through generic type arguments for JSX, we are able to make our component more reusable. Users can extend components to allow additional props. Great!&lt;/p&gt;
</content:encoded></item><item><title>Part One: Using Typescript with React</title><link>https://dylanpaulus.com/posts/2018/using-typescript-with-react-part-one/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/using-typescript-with-react-part-one/</guid><pubDate>Wed, 16 May 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Finished Example: &lt;a href=&quot;https://codesandbox.io/s/n3138x65p0?hidenavigation=1&quot;&gt;Click Here&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Learning Typescript with React can be challenging, and in my case, cursing Microsoft and throwing &lt;code&gt;any&lt;/code&gt; on every variable. The goal of this series is to document what I&apos;ve learned while developing applications in React, and trying hard to shove in Typescript. Like many things, the initial learning curve may be staggering, but adding a type-checker repays dividends once the gears start turning. &lt;em&gt;One thing to note:&lt;/em&gt; this isn&apos;t a post about setting up Typescript. We&apos;ll assume a &lt;strong&gt;tsconfig.json&lt;/strong&gt; exists, and compiles our code to valid JavaScript.&lt;/p&gt;
&lt;p&gt;We&apos;ll go through part one by creating a counter, and adding types where needed.&lt;/p&gt;
&lt;h3&gt;App&lt;/h3&gt;
&lt;p&gt;Starting out, we have a scaffolding of our application.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Note, Typescript requires the whole React package to be imported.
// More information can be found: https://stackoverflow.com/a/37491916
import * as React from &quot;react&quot;;

class App extends React.Component {
  public render() {
    return (
      &amp;lt;div&amp;gt;
        test
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looks like a valid React class component, but a few Typescript differences stand out right away. First, because React lib doesn&apos;t have a default export, Typescript requires us to import the whole package (&lt;code&gt;import * as React from &quot;react&quot;;&lt;/code&gt;). Second, all React methods are defined as &lt;code&gt;public&lt;/code&gt; (&lt;em&gt;private or protected&lt;/em&gt; will not work), as seen in the &lt;strong&gt;render&lt;/strong&gt; method. &lt;em&gt;We can remove the &lt;strong&gt;public&lt;/strong&gt; keyboard, and the component will work the same.&lt;/em&gt; I like to explicitly define scope of my methods to help differentiate between my methods and React&apos;s. Generally, I define my methods as &lt;code&gt;private&lt;/code&gt; unless otherwise needed. This enforces the scope of the method to just the component, and prevents unwanted side-effects.&lt;/p&gt;
&lt;h3&gt;State&lt;/h3&gt;
&lt;p&gt;We&apos;ll need a way of storing the state of the counter. Let&apos;s implement this.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Note, Typescript requires the whole React package to be imported.
// More information can be found: https://stackoverflow.com/a/37491916
import * as React from &quot;react&quot;;

interface IState {
  count: number;
}

class App extends React.Component&amp;lt;{}, IState&amp;gt; {
  public readonly state = {
    count: 0
  };

  public render() {
    return (
      &amp;lt;div&amp;gt;
        {this.state.count}
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A lot is happening here, so we&apos;ll break it down change-by-change.&lt;/p&gt;
&lt;h5&gt;Interface&lt;/h5&gt;
&lt;pre&gt;&lt;code&gt;interface IState {
  count: number;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First, we create a new &lt;a href=&quot;https://www.typescriptlang.org/docs/handbook/interfaces.html&quot;&gt;interface&lt;/a&gt; that defines the &lt;em&gt;shape&lt;/em&gt; of our component&apos;s state.&lt;/p&gt;
&lt;p&gt;Notice that as a practice we start the interface name with an uppercase &lt;strong&gt;&quot;I&quot;&lt;/strong&gt;. This is borrowed from OOP languages, like C#, to allow us to better identify a variable &lt;em&gt;vs&lt;/em&gt; type &lt;em&gt;vs&lt;/em&gt; interface.&lt;/p&gt;
&lt;p&gt;Another practice I&apos;ve adopted: define Typescript types in PascalCase, and Javascript variables in camelCase. Yet another helpful naming scheme to prevent trying use a type definition as executable code!&lt;/p&gt;
&lt;p&gt;Moving on, we define our component&apos;s state as having one field, count. In Typescript there is no difference between a float &lt;code&gt;0.0001&lt;/code&gt; and an int &lt;code&gt;10&lt;/code&gt;. To say something is &apos;number-like&apos;, we give it the type &lt;code&gt;number&lt;/code&gt;.&lt;/p&gt;
&lt;h5&gt;Class Definition&lt;/h5&gt;
&lt;pre&gt;&lt;code&gt;class App extends React.Component&amp;lt;{}, IState&amp;gt; {
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;React.Component&lt;/code&gt; (also &lt;code&gt;React.PureComponent&lt;/code&gt;) are generic types allowing us to provide the &lt;em&gt;shape&lt;/em&gt; of the component&apos;s props and state. Component comes with a couple predefined properties (&lt;code&gt;children&lt;/code&gt; and &lt;code&gt;ref&lt;/code&gt; to name a few). Because App doesn&apos;t have any props, we&apos;ll use an empty object. The React Typescript definition combines the type we pass in with the default Component type, so even with an empty object, the inherited component props will still be available (eg. children and ref). For our component&apos;s state, we&apos;ll tell Typescript we want to use our state shape defined in IState.&lt;/p&gt;
&lt;p&gt;To break it apart:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Define a component with just state: &lt;code&gt;React.Component&amp;lt;{}, IState&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Define a component with just props: &lt;code&gt;React.Component&amp;lt;IProps&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Define both state and props: &lt;code&gt;React.Component&amp;lt;IProps, IState&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h5&gt;Defining State&lt;/h5&gt;
&lt;pre&gt;&lt;code&gt;public readonly state = {
  count: 0
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally, we define the state for the component. Remember, so far we&apos;ve only told Typescript what the &lt;em&gt;shape&lt;/em&gt; of our state is. This is where we define its actual value in React. Because state is needed by React, we define it as &lt;code&gt;public&lt;/code&gt;. Also, since we don&apos;t want anyone mutating the state directly, we then add &lt;code&gt;readonly&lt;/code&gt;. This will throw a Typescript error whenever we try to reassign state directly to a value (eg. &lt;code&gt;this.state.count = this.state.count + 1; // Error!&lt;/code&gt;). Next, we define our public readonly variable to have the name &lt;em&gt;state&lt;/em&gt;, and assign it an object that matches the shape we defined in &lt;strong&gt;IState&lt;/strong&gt;. Since we defined &lt;code&gt;React.Component&lt;/code&gt; with &lt;strong&gt;IState&lt;/strong&gt; as our state shape, Typescript knows that the state should have a &lt;strong&gt;count&lt;/strong&gt; field with a number value.&lt;/p&gt;
&lt;h3&gt;Adding Events&lt;/h3&gt;
&lt;p&gt;Let&apos;s finish our counter by adding some buttons, and a click event that either decrements or increments the count.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Note, Typescript requires the whole React package to be imported.
// More information can be found: https://stackoverflow.com/a/37491916
import * as React from &quot;react&quot;;

interface IState {
  count: number;
}

class App extends React.Component&amp;lt;{}, IState&amp;gt; {
  public readonly state = {
    count: 0
  };

  private handleClick = (event: React.MouseEvent&amp;lt;HTMLButtonElement&amp;gt;) =&amp;gt; {
    const type: string = event.currentTarget.title;

    this.setState(({ count }) =&amp;gt; ({
      count: type === &quot;decrement&quot; ? count - 1 : count + 1
    }));
  };

  public render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;button title=&quot;decrement&quot; onClick={this.handleClick}&amp;gt;
          -
        &amp;lt;/button&amp;gt;
        {this.state.count}
        &amp;lt;button title=&quot;increment&quot; onClick={this.handleClick}&amp;gt;
          +
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The big change is the addition of a new method.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;private handleClick = (event: React.MouseEvent&amp;lt;HTMLButtonElement&amp;gt;) =&amp;gt; {&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;We create a new private method called &lt;code&gt;handleClick&lt;/code&gt; that will take care of our button click events. Notice that since React uses synthetic events--we have to use one of React&apos;s types. The event was triggered by a click of the mouse, so we&apos;ll use &lt;code&gt;React.MouseEvent&lt;/code&gt;. &lt;strong&gt;React.MouseEvent&lt;/strong&gt; is a generic type that takes the type of element the event is triggered from. In our case, it&apos;s the default HTML button element (defined as &lt;code&gt;HTMLButtonElement&lt;/code&gt;). We finish off by incrementing or decrementing the count based on the title of the button.&lt;/p&gt;
&lt;p&gt;Our counter is now complete with TypeScript types!&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;/posts/using-typescript-with-redux-part-two&quot;&gt;To be continued in part two...&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Reusable Components: Factory Components</title><link>https://dylanpaulus.com/posts/2018/reusable-components-factory-component/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2018/reusable-components-factory-component/</guid><pubDate>Tue, 10 Apr 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Beware the &lt;strong&gt;mega&lt;/strong&gt; component. Mega components contain around 50 props--when the stars align, only certain values produce specialized output. For example, let&apos;s assume we have a &lt;code&gt;&amp;lt;IdentityInput /&amp;gt;&lt;/code&gt; component which provides user login using only a fingerprint. Nifty, eh?&lt;br /&gt;
Our component has a few properties: &lt;code&gt;&amp;lt;IdentityInput onSuccess={login} onFail={showError} fingerprint={value} humanOnly /&amp;gt;&lt;/code&gt; allowing for only human fingerprints, and provides a few callbacks for onSuccess and onFail.&lt;/p&gt;
&lt;p&gt;A few months go by and our company, Component Co., finds out there are a lot of humans out there trying to login, but are missing fingerprints! Great, we&apos;ll update our component to allow for eyeball scans.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IdentityInput onSuccess={login} onFail={showError} value={value} isEyeballEnabled isFingerprintEnabled humanOnly /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After many failed attempts to login to our system the boss of Component Co., a cyborg without eyeballs or fingerprints, demands that we provide a password input field. Once again, the IndentityInput component gets updated to have the request.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IdentityInput
  onSuccess={login}
  onFail={showError}
  value={value}
  isEyeballEnabled
  isFingerprintEnabled
  showPasswordField={this.state.isCyborg}
  humanOnly={!this.state.isCyborg}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Just from this contrived example, we can see that allowing for ever-growing mega components can start to be a problem. For one, we lose single-responsibility. Over time our component does multiple things which causes a barrier of entry penalty when new developers start using the component. Second, it provides weird combinations of secret password props in components. &quot;If I have these props, it does this one thing. But, don&apos;t set that string prop there or everything breaks!&quot; Third, we&apos;ll have to write our class/function in a way to handle all the edge cases and props--probably requiring way too many if-statements.&lt;/p&gt;
&lt;p&gt;One solution to this problem is to have a factory component, very much like the factory design pattern. We&apos;ll keep individual components small, performing a single function, but then create a parent component that then decides what component we should render.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function FingerPrint(props) {
  return &amp;lt;div {...props}&amp;gt;Super Awesome Fingerprint Scanner&amp;lt;/div&amp;gt;;
}

function EyeballScanner(props) {
  return &amp;lt;div {...props}&amp;gt;Super Ok Eyeball Scanner&amp;lt;/div&amp;gt;;
}

function PasswordInput(props) {
  return &amp;lt;div {...props}&amp;gt;Super Lame Password Input&amp;lt;/div&amp;gt;;
}

/**
 * Factory Component
 */
function IdentityFactory(props) {
  const { type, ...rest } = props;

  switch (type) {
    case &quot;finger&quot;:
      return &amp;lt;FingerPrint {...rest} /&amp;gt;;

    case &quot;eyeball&quot;:
      return &amp;lt;EyeballScanner {...rest} /&amp;gt;;

    case &quot;password&quot;:
      return &amp;lt;PasswordInput {...rest} /&amp;gt;;

    default:
      console.warn(`Invalid Indentity type &quot;${type}&quot;. Abort!`);
      return null;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, when we want to use the IdentityFactory component we can switch between the different input types, but also provide props relevant to just that component. It&apos;ll allow us to modify single-responsibility components with ease.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;render() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;IdentityFactory type=&quot;finger&quot; humanOnly /&amp;gt;
      &amp;lt;IdentityFactory type=&quot;eyeball&quot; humanOnly /&amp;gt;
      &amp;lt;IdentityFactory type=&quot;password&quot; /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Global Component Registration</title><link>https://dylanpaulus.com/posts/2017/global-component-registration/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2017/global-component-registration/</guid><pubDate>Fri, 08 Dec 2017 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;Often, I find myself looking through open-source projects to see how they solve issues. Not bugs, but problems in code that cause repetition or excessive boilerplate. &lt;a href=&quot;https://ux.stackexchange.com/questions/12045/what-is-a-modal-dialog-window#12046&quot;&gt;Modals&lt;/a&gt; have given me problems, specifically when having to create a specialized modal for different workflows. They are awkward. Modals, in the DOM, live outside of the scope of the current workflow. And, part of their state usually lives outside of the modal itself (hide/show). I came accross an interesting solution to the modal problem while looking through &lt;a href=&quot;https://github.com/getinsomnia/insomnia&quot;&gt;Insomnia&apos;s&lt;/a&gt; code. This is a different post than what I normally do. I&apos;ll just be posting code as an example, and filling in the explaination through comments. Hopefully this will work as a reference, and starting point to play around with the idea.&lt;/p&gt;
&lt;h3&gt;Code&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;// ModalHandler.js
const modals = {};

/*
 * This function takes in a component, and then adds a
 * reference to it through a friendly named key-&amp;gt;value.
 */
export function registerModal(component) {
  if (!component) {
    return;
  }

  modals[component.name] = component;
}

/*
 * show() takes the component we want to show, and some additional
 * arguments. We&apos;ll then call the &apos;show&apos; function on the component.
 * This allows us to &apos;activate&apos; a component anywhere, but invert
 * control to the relative component.
 */
export function show(component, ...args) {
  const elem = modals[component.name];
  if (elem.show &amp;amp;&amp;amp; typeof elem.show === &quot;function&quot;) {
    return elem.show(...args);
  }

  console.warn(`show() function is missing from ${component.name}.`);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// App.jsx
import React, { Component } from &quot;react&quot;;
import { registerModal } from &quot;./ModalHandler&quot;;

class Base extends Component {
  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;MyApp /&amp;gt;
        {/*
          This component is pretty regular except for this next bit.
          We&apos;ll pass in registerModal() to the component&apos;s ref we&apos;ll
          show later on
        */}
        &amp;lt;Modal ref={registerModal} /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import React, { Component } from &quot;react&quot;;
import { show } from &quot;./ModalHandler&quot;;
import Modal from &quot;./Modal&quot;;

class MyApp extends Component {
  showModal = () =&amp;gt; {
    // Will call the .show() function
    // on the Modal component
    show(Modal);
  };

  render() {
    return &amp;lt;button onClick={this.showModal}&amp;gt;Show Modal&amp;lt;/button&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// Modal.jsx
import React, { Component } from &quot;react&quot;;

class Modal extends Component {
  state = {
    isOpen: false,
  };

  // This is the show() function that&apos;ll be invoked
  // when this component is passed to ModalHandler.js&apos; show() function
  show = () =&amp;gt; {
    this.setState({ isOpen: true });
  };

  render() {
    if (!this.state.isOpen) {
      return null;
    }

    return (
      &amp;lt;div&amp;gt;
        Modal!
        &amp;lt;button onClick={() =&amp;gt; this.setState({ isOpen: false })}&amp;gt;Close&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Encapsulating State with Functional Children</title><link>https://dylanpaulus.com/posts/2017/encapsulating-state-with-functional-children/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2017/encapsulating-state-with-functional-children/</guid><pubDate>Thu, 14 Sep 2017 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;import Alert from &quot;../../../../components/Alert.astro&quot;;&lt;/p&gt;

  Update (3/20/2023): Since writing this post the community has called this
  technique &quot;Render Props&quot;.

&lt;p&gt;There is a technique for creating reusable components that got missed in my last post, &lt;a href=&quot;/posts/tips-on-creating-reusable-components/&quot;&gt;Tips on Creating Reusable Components&lt;/a&gt;, that I&apos;d like to talk about. That is, components that have functions as children. This is a great tool that mirrors higher order components, in that it lets us abstract away reusable states. We&apos;ll start out with an example.&lt;/p&gt;
&lt;h3&gt;Breaking down functional children&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import React from &quot;react&quot;;

class Booer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      test: &quot;...&quot;,
    };
  }

  componentDidMount() {
    setTimeout(() =&amp;gt; {
      this.setState({
        test: &quot;BOO!&quot;,
      });
    }, 1000);
  }

  render() {
    // Using children as a function!
    return this.props.children(this.state.test);
  }
}

function Timer(props) {
  return &amp;lt;Booer&amp;gt;{(test) =&amp;gt; &amp;lt;div&amp;gt;{test}&amp;lt;/div&amp;gt;}&amp;lt;/Booer&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Booer&lt;/em&gt; is a component that after 1000ms, updates its state to say &quot;Boo!&quot;. Nothing special. The power in functional children comes in play in the render method. Instead of treating &lt;code&gt;this.props.children&lt;/code&gt; as a variable, we pass a long some state which gets injected into the children prop. Moving to the &lt;em&gt;Timer&lt;/em&gt; component, we see something a little odd. The &lt;em&gt;Booer&lt;/em&gt; component takes a function with an argument, &lt;code&gt;test&lt;/code&gt;, being that state we passed into &lt;code&gt;this.props.children&lt;/code&gt;. We are then free to return any valid React children in the function. This let&apos;s us reuse state for different visual components! In the case of the &lt;em&gt;Timer&lt;/em&gt; component, it will show a &lt;em&gt;div&lt;/em&gt; with &quot;...&quot;. Once 1000ms is complete, the contents will be replaced with &quot;Boo!&quot;.&lt;/p&gt;
&lt;h3&gt;Toggle Component&lt;/h3&gt;
&lt;p&gt;The first example is a nice way to show functional children, but let&apos;s make something a little more practical. Like the title suggestions, how about a component that keeps track of a toggle! This may look something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React from &quot;react&quot;;

class Toggle extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isToggled: false,
    };

    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState((prevState) =&amp;gt; ({
      isToggled: !prevState.isToggled,
    }));
  }

  render() {
    const { isToggled } = this.state;

    return this.props.children(isToggled, this.toggle);
  }
}

function ToggleButton() {
  return (
    &amp;lt;Toggle&amp;gt;
      {(isToggled, toggle) =&amp;gt; (
        &amp;lt;button onClick={toggle}&amp;gt;{isToggled ? &quot;ON&quot; : &quot;off&quot;}&amp;lt;/button&amp;gt;
      )}
    &amp;lt;/Toggle&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looking at it, the &lt;em&gt;Booer&lt;/em&gt; component is pretty similar to out new &lt;em&gt;Toggle&lt;/em&gt; component. They both handle some state, then pass it to &lt;code&gt;this.props.children()&lt;/code&gt; as function argument. In the case of &lt;em&gt;Toggle&lt;/em&gt;, we are now passing two arguments. First, our &lt;em&gt;isToggled&lt;/em&gt; state. Second, a class method that will toggle the &lt;em&gt;isToggled&lt;/em&gt; state. &lt;code&gt;this.toggle&lt;/code&gt; will be useful for a consumer to control events.&lt;br /&gt;
Looking at the &lt;em&gt;ToggleButton&lt;/em&gt; component, it&apos;s pretty simple to wire out a button that has toggle ability, while making its state reusable! What if we want a toggle checkbox? We can just swap out the &lt;code&gt;&amp;lt;button&amp;gt;&lt;/code&gt; JSX tags for &lt;code&gt;&amp;lt;input type=&quot;checkbox&quot;&amp;gt;&lt;/code&gt;!&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Functional children is yet another technique for creating reusable components. It helps us move presentational components away from stateful logic (ie. Dumb/Smart components or Containers/Components).&lt;/p&gt;
</content:encoded></item><item><title>Tips on Creating Reusable Components</title><link>https://dylanpaulus.com/posts/2017/tips-on-creating-reusable-components/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2017/tips-on-creating-reusable-components/</guid><pubDate>Fri, 08 Sep 2017 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;A huge selling point of React is its use of composable, reusable components. Everything is built off the idea of &lt;code&gt;V = F(d)&lt;/code&gt;, or view/UI is created by some function acting on data/state. How do we create more advanced user interface? Well, just add more functions to the party (For example &lt;code&gt;V = G(F(E(S(d))))&lt;/code&gt;). That&apos;s cute, why does this matter? Thinking of our components as functions, even if we use &lt;em&gt;class&lt;/em&gt;, will help us create more reusable components. It even helps us write super helpful utility functions called &lt;a href=&quot;/posts/higher-order-components/&quot;&gt;Higher Order Components&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We&apos;ll look at ways to improve our reusability and composition of components by using an example component a long the way. For this article, we&apos;ll use a component that adds an Icon to a button.&lt;/p&gt;
&lt;p&gt;For example,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IconButton extends React.Component {
  render() {
    &amp;lt;Button onClick={this.props.onClick}&amp;gt;
      &amp;lt;Icon /&amp;gt; {this.props.text}
    &amp;lt;/Button&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And to consume the button,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IconButton text=&quot;Click Me!&quot; onClick={() =&amp;gt; alert(&quot;Click!&quot;)} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Not bad.. easy to use, and to the point. But, some part of me thinks this could be better. Let&apos;s walk through a few suggestions on making this component more reusable.&lt;/p&gt;
&lt;h3&gt;Keep it Simple, Jack&lt;/h3&gt;
&lt;p&gt;Continuing on the topic of thinking of components as functions, keep components simple. Components that do too many things are dangerous. They are easy to break, and a pain to maintain. Instead, split functionality into separate components, then compose those components to make something functional. This makes it really easy to maintain features, and to swap out functionality when requirements change.&lt;/p&gt;
&lt;p&gt;Going to the IconButton example, we really don&apos;t need an IconButton component. What if tomorrow we need an IconInput button? We not only have two separate, but pretty similar components to maintain! We can fix this by using composition. What we really want is something that &apos;adds an icon&apos; to a component. Let&apos;s make a new component called IconAdder.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IconAdder extends React.Component {
  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;Icon /&amp;gt; {this.props.component}
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to consume it&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IconAdder
  component={&amp;lt;Button onClick={() =&amp;gt; alert(&quot;Click!&quot;)}&amp;gt;Click Me!&amp;lt;/Button&amp;gt;}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;IconAdder allows us to throw any ol&apos; component we want into it, and it&apos;ll add an Icon to it. Nice.&lt;/p&gt;
&lt;h3&gt;Hello There, Children!&lt;/h3&gt;
&lt;p&gt;One thing I come across a lot is the overuse of component properties. Components should almost never be used as properties. It ends up making components hard to use, and in the end, we are fighting with React. In React, every component has a property called children (&lt;code&gt;props.children&lt;/code&gt;). This says, whatever we pass between this component&apos;s tags, we&apos;ll insert here. Let&apos;s see an example &lt;code&gt;props.children&lt;/code&gt; in the IconAdder component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IconAdder extends React.Component {
  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;Icon /&amp;gt; {this.props.children}
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to consume it&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IconAdder&amp;gt;
  &amp;lt;Button onClick={() =&amp;gt; alert(&quot;Click!&quot;)}&amp;gt;Click Me!&amp;lt;/Button&amp;gt;
&amp;lt;/IconAdder&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;&amp;lt;Button&amp;gt;&lt;/code&gt; component will be inserted in IconAdder&apos;s &lt;code&gt;{this.props.children}&lt;/code&gt;! Much better!&lt;/p&gt;
&lt;h3&gt;Injecting HTML Types&lt;/h3&gt;
&lt;p&gt;I wrote an article on this &lt;a href=&quot;/posts/injecting-react-tag-types/&quot;&gt;subject here&lt;/a&gt; already so I&apos;ll be brief.&lt;/p&gt;
&lt;p&gt;As someone consuming a component, I want as little pollution of my code as possible. Pollution in this case could be anything: event handlers, code size, or even HTML elements. In the case of our IconAdder component, a parent &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; wrapper gets added to every component using it. It would be great if we could get rid of the div, and just make it our child component. Well... we&apos;re in luck. We can specify a tag property, and then use that property. This lets the end-user be in control of their DOM structure.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IconAdder extends React.Component {
  render() {
    const { tag, onClick, children } = this.props;
    const Tag = tag;

    return (
      &amp;lt;Tag onClick={onClick}&amp;gt;
        &amp;lt;Icon /&amp;gt; {children}
      &amp;lt;/Tag&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to consume it&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IconAdder tag={Button} onClick={() =&amp;gt; alert(&quot;Click!&quot;)}&amp;gt;
  Click Me!
&amp;lt;/IconAdder&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Another benefit of using a &apos;tag&apos; property, is let&apos;s say that we want to support React Router&apos;s &lt;code&gt;&amp;lt;Link&amp;gt;&lt;/code&gt; component, but we also need to support the classic HTML &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt; tag. We can easily swap these two out by just changing the &apos;tag&apos; prop!&lt;/p&gt;
&lt;h3&gt;Allow Extension&lt;/h3&gt;
&lt;p&gt;Nothing grinds my gears like getting a fresh new component, but realizing I want to make the font bold. So, I add a quick &lt;code&gt;style={ { fontWeight: 800 } }&lt;/code&gt; to the component, refresh, and nothing changes. (Warning: what is about to be shown requires a transpiler).&lt;/p&gt;
&lt;p&gt;We should allow our components to be reasonably editable, while protecting what we need to. This can be done by the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Rest_in_Object_Destructuring&quot;&gt;rest operator&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Right now, our IconAdder component won&apos;t accept a style, className, or title prop. Oh yeah, and what about in the future if we need to use IconAdder on a &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt; tag. We&apos;ll need to support href also. Let&apos;s use the rest operator to support all of these properties!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class IconAdder extends React.Component {
  render() {
    const { tag, onClick, children, ...rest } = this.props;
    const Tag = tag;

    return (
      &amp;lt;Tag onClick={onClick} {...rest}&amp;gt;
        &amp;lt;Icon /&amp;gt; {children}
      &amp;lt;/Tag&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to consume it&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;IconAdder
  tag={Button}
  onClick={() =&amp;gt; alert(&quot;Click!&quot;)}
  style={{ fontWeight: &quot;800&quot; }}
  title=&quot;A button for clicking&quot;&amp;gt;
  Click Me!
&amp;lt;/IconAdder&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;...rest&lt;/code&gt; will grab whatever properties we haven&apos;t taken off in the destructuring (&lt;code&gt;const { a, b, c} = this.props;&lt;/code&gt;), and assign it, in this case, to a variable called &lt;code&gt;rest&lt;/code&gt;. We then apply all those properties to our &lt;code&gt;&amp;lt;Tag&amp;gt;&lt;/code&gt; component by destructuring the &lt;code&gt;rest&lt;/code&gt; object into the individual props. As shown in the consumption of IconAdder, we can now add whatever other properties we want!&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;These are a few tips I use when creating components to keep them easier to consume, and extend. In summary, think of every component as a function. It will consume some input, and produce an output. The children property is your friend, use it when it makes sense! Dynamically injecting the component type can turn multiple similar components, into one highly reusable component. Finally, allow components to receive extra props, and have the properties/styles override the base implementation when possible.&lt;/p&gt;
</content:encoded></item><item><title>Introduction to Higher Order Components</title><link>https://dylanpaulus.com/posts/2017/higher-order-components/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2017/higher-order-components/</guid><pubDate>Thu, 17 Aug 2017 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;Think of Higher Order Components (HOC) like Pacman. As Pacman consumes his smaller looking dot counterparts, Pacman gains superpower abilities. Like ghost eating! HOC&apos;s work similarly... minus ghosts.&lt;br /&gt;
A HOC consumes a base component, applies some new ability or super power, then spits out a new modified base component. To help show the power of HOC&apos;s, lets create one that does a simple check. If a component doesn&apos;t have children, show an empty component. When children are present, we&apos;ll display them.&lt;/p&gt;
&lt;h3&gt;withEmptyState()&lt;/h3&gt;
&lt;p&gt;First, lets define our base component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Hello(props) {
  return &amp;lt;div&amp;gt;Hello, {props.children}!&amp;lt;/div&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Before jumping straight into the HOC, what are we trying to achieve? We want to pass our &lt;code&gt;&amp;lt;Hello /&amp;gt;&lt;/code&gt; component into some function, lets call it withEmptyState(), which creates and returns a new component. This new component will either: show &lt;code&gt;&amp;lt;Hello /&amp;gt;&lt;/code&gt; if the new component has children, or will return null.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function withEmptyState(component) {
  return function (props) {
    // Start new stateless functional component
    if (props.children) {
      return component(props);
    }

    return null;
  };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pretty simple, but extremely powerful! All this function does is take a component, then returns a new stateless functional component. Inside, we check the props. Does this component have children? If yes, return our originally passed in component using our new component&apos;s props (We&apos;ll see how this ties in soon). If no children exist, don&apos;t render anything.&lt;/p&gt;
&lt;p&gt;But how would I use withEmptyState?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const HOC = withEmptyState(Hello);

class MyContainer extends React.Component {
  render() {
    return (
      &amp;lt;div&amp;gt;
        HOC 1: &amp;lt;HOC /&amp;gt;
        &amp;lt;hr /&amp;gt;
        HOC 2: &amp;lt;HOC&amp;gt;WORLD!&amp;lt;/HOC&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our first instance of &lt;code&gt;&amp;lt;HOC /&amp;gt;&lt;/code&gt; wouldn&apos;t render anything, as we haven&apos;t gave it children.&lt;/p&gt;
&lt;p&gt;The second &lt;code&gt;&amp;lt;HOC&amp;gt;WORLD!&amp;lt;/HOC&amp;gt;&lt;/code&gt; would render our &lt;code&gt;&amp;lt;Hello&amp;gt;&lt;/code&gt; component; we would see &quot;Hello, WORLD!&quot;.&lt;/p&gt;
&lt;aside&gt;
&lt;img alt=&quot;Image showing off Higher Order Component results&quot; /&gt;
&lt;/aside&gt;
&lt;h3&gt;The End&lt;/h3&gt;
&lt;p&gt;Higher Order Components allow us to separate common functionality into their own functions, so we don&apos;t have to add duplication between components. They also allow us to decouple functionality!&lt;/p&gt;
</content:encoded></item><item><title>Injecting Dynamic Elements to Components</title><link>https://dylanpaulus.com/posts/2017/injecting-react-tag-types/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2017/injecting-react-tag-types/</guid><pubDate>Wed, 26 Jul 2017 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;Let&apos;s say we&apos;re working on an UI component library using React JS. We make a super awesome looking button, maybe even the best button in the world. But suddenly, our computer shuts off without saving our component!&lt;br /&gt;
Like Tenacious D, we create a tribute to the button which looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButton extends Component {
  render() {
    const { children, ...other } = this.props;

    return &amp;lt;button {...other}&amp;gt;{children}&amp;lt;/button&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything is working great. We create buttons all over the place &lt;code&gt;&amp;lt;AwesomeButton onClick={doStuff}&amp;gt;Click ME&amp;lt;/AwesomeButton&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The next day, the boss comes over, &quot;This button is amazing, let&apos;s make a button link to Google!&quot;&lt;br /&gt;
Easy enough, we create a new component that instead uses an anchor tag.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButtonLink extends Component {
  render() {
    const { children, ...other } = this.props;

    return &amp;lt;a {...other}&amp;gt;{children}&amp;lt;/a&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Weeks later, another programmer walks over, &quot;Hey, we&apos;re converting to using React Router. Can we get a button that can use the Link component?&quot;&lt;br /&gt;
Mumbling under your breath, we create yet another Awesome component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButtonReactRouterLink extends Component {
  render() {
    const { children, ...other } = this.props;

    return &amp;lt;Link {...other}&amp;gt;{children}&amp;lt;/Link&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We have ourselves a problem. Every time there is a new request we have to create new components that are very similar, just using slightly different render elements. What if the company decides to re-brand. Instead of blue, we are a red company now. Little changes to the visuals of these AwesomeButton components need to be updated individually. Think DRY! Is there a better way of doing this? Stay tuned.&lt;/p&gt;
&lt;h3&gt;Dynamically Injecting Elements&lt;/h3&gt;
&lt;p&gt;What if the consumer of a component could define its base element? Let&apos;s look at the example below:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButton extends React.Component {
  render() {
    const { children, tag = &quot;button&quot;, ...other } = this.props;
    const Tag = tag;

    return &amp;lt;Tag {...other}&amp;gt;{children}&amp;lt;/Tag&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So we have this new property called tag. Tag will be our way of passing in an element/component into AwesomeButton. If the es6 destructing looks different, let me explain. We will pull out the &lt;code&gt;tag&lt;/code&gt; prop from &lt;code&gt;this.props&lt;/code&gt;. If no value is defined for tag, we will set its default value to be &lt;code&gt;&quot;button&quot;&lt;/code&gt; (A Button HTML element).&lt;br /&gt;
The next line, &lt;code&gt;const Tag = tag;&lt;/code&gt; is so we can fulfill what React&apos;s JSX considers a component. All components must be uppercase, where html elements need to be lowercase. Since we are using then variable &lt;code&gt;tag&lt;/code&gt;, JSX will always treat the incoming values as a component. So, we have to uppercase our variable.&lt;br /&gt;
We now render the prop &lt;code&gt;Tag&lt;/code&gt; as our element. Whatever &lt;code&gt;tag&lt;/code&gt; equals, that will be our element!&lt;/p&gt;
&lt;p&gt;A few examples:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;AwesomeButton onClick={doSomething}&amp;gt;Click Me!&amp;lt;AwesomeButton&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Will render the default button. &lt;code&gt;&amp;lt;button onClick={doSomething}&amp;gt;Click Me!&amp;lt;/button&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;AwesomeButton tag=&quot;a&quot; href={`/myPage`}&amp;gt;Click Me!&amp;lt;AwesomeButton&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Will render using an anchor tag &lt;code&gt;&amp;lt;a href={&apos;/myPage&apos;}&amp;gt;Click Me!&amp;lt;/a&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;AwesomeButton tag={Link} to={`/myPage`}&amp;gt;Click Me!&amp;lt;AwesomeButton&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Will render using a React Router Link component &lt;code&gt;&amp;lt;Link to={&apos;/myPage&apos;}&amp;gt;Click Me!&amp;lt;/Link&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Neat! But why is this happening?&lt;/p&gt;
&lt;h3&gt;JSX Transformations&lt;/h3&gt;
&lt;p&gt;Our JSX, in the render function, gets transformed into plain jsx functions that the browsers can use. With this in mind, our AwesomeButton&apos;s JSX gets transformed into a &lt;code&gt;React.createElement()&lt;/code&gt; function with the element name as the first argument.&lt;br /&gt;
With the help of our good friend Babel, let&apos;s see what different components compile to!&lt;/p&gt;
&lt;p&gt;First, let&apos;s look at a simple component that just renders a div with the text &quot;test&quot;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButton extends React.Component {
  render() {
    return &amp;lt;div&amp;gt;test&amp;lt;/div&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://babeljs.io/repl/#?babili=false&amp;amp;evaluate=true&amp;amp;lineWrap=false&amp;amp;presets=es2015%2Creact%2Cstage-2&amp;amp;targets=&amp;amp;browsers=&amp;amp;builtIns=false&amp;amp;debug=false&amp;amp;code_lz=MYGwhgzhAECCDuBTCB7AtogQgVwC65QDtpEAPXRQgExgCVExhcA6AYXQAcjLdoBvALAAoaKOgAnSlUTiAFAEp-wsSomJc2ccVnLVqgDxUAlgDcAfBQi59AemPnouvfIDcT6AF9hHoA&quot;&gt;Compiled Example - Click Me!&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If we look in the render method, we can see what our JSX actually compiles to.&lt;/p&gt;
&lt;p&gt;&lt;img alt=&quot;div Compiled Code&quot; title=&quot;div Compiled Code&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Well that&apos;s cool. So our div element just gets defined as the first parameter of &lt;code&gt;React.createElement&lt;/code&gt;. I wonder what happens if we try this with our element injecting AwesomeButton?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class AwesomeButton extends React.Component {
  render() {
    const { children, tag = &quot;button&quot;, ...other } = this.props;
    const Tag = tag;

    return &amp;lt;Tag {...other}&amp;gt;{children}&amp;lt;/Tag&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://babeljs.io/repl/#?babili=false&amp;amp;evaluate=true&amp;amp;lineWrap=false&amp;amp;presets=es2015%2Creact%2Cstage-2&amp;amp;targets=&amp;amp;browsers=&amp;amp;builtIns=false&amp;amp;debug=false&amp;amp;code_lz=MYGwhgzhAECCDuBTCB7AtogQgVwC65QDtpEAPXRQgExgCVExhcA6AYXQAcjLdoBvALAAoaKOgAnSlUTiAFAEp-wsSujAiEXnzUALAJYgqkwgBpouMAHNoAXmgAiAEZ4Che2eaeUuHTOgBfW3N9CGYOcRQOCABuZVVRdUJNaAAVKyCLS1ihOPjJXGxxYllc-NEAHjTrPk9mb19xfwA-PmB9Q2N_coB6KqboUpV5bJV_YX8gA&quot;&gt;&amp;lt;AwesomeButton&amp;gt;Click Me!&amp;lt;/AwesomeButton&amp;gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Looking at the render method in AwesomeButton:&lt;/p&gt;
&lt;p&gt;&lt;img alt=&quot;AwesomeButton Compiled Code&quot; title=&quot;AwesomeButton Compiled Code&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Woah, our Tag variable just gets put where the element is! This is exactly the same to how components are treated in JSX. They get ploped straight into the first argument of &lt;code&gt;React.createElement&lt;/code&gt;. Now, when the boss asks for a new feature in &lt;code&gt;AwesomeButton&lt;/code&gt;, we only have to change this one implementation of the component. All consumers of the component might use it vastly differently, but we are able to keep our code DRY and highly reusable!&lt;/p&gt;
</content:encoded></item><item><title>Intro to FlightJS</title><link>https://dylanpaulus.com/posts/2015/intro-to-flight-js/</link><guid isPermaLink="true">https://dylanpaulus.com/posts/2015/intro-to-flight-js/</guid><pubDate>Tue, 17 Nov 2015 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;This post is part of the archive. These are mainly random posts that were written throughout the years in no coherent order.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;FlightJS&lt;/h3&gt;
&lt;p&gt;FlightJs isn’t the new kid on the block. This little framework has gone unnoticed in Github-land for years. Taken from the FlightJS Github: “Flight is a lightweight, component-based JavaScript framework that maps behavior to DOM nodes.” Reworded, we use reusable components that listen for event calls. These events then in turn perform actions on the DOM or manipulate pieces of our code. Today we will get started with FlightJs, and show how simple it is to use. Though this is an introduction guide, I will assume that we have a fair proficiency with HTML, CSS, and JavaScript.&lt;br /&gt;
Getting Started&lt;/p&gt;
&lt;p&gt;In this Intro to FlightJS guide we will do what many intro framework guides do, make a counter. Let’s get to work.&lt;br /&gt;
Head over to the FlightJS Github, and install FlightJS using your favorite method.&lt;br /&gt;
HTML code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;h1&amp;gt;FlightJS Counter&amp;lt;/h1&amp;gt;
&amp;lt;div class=&quot;”counter”&quot;&amp;gt;
  &amp;lt;h2 class=&quot;”counter-total”&quot;&amp;gt;0&amp;lt;/h2&amp;gt;
  &amp;lt;div class=&quot;”counter-function”&quot;&amp;gt;
    &amp;lt;a href=&quot;”#subtract”&quot; class=&quot;”counter-subtract”&quot;&amp;gt;-&amp;lt;/a&amp;gt;
    &amp;lt;a href=&quot;”#add”&quot; class=&quot;”counter-add”&quot;&amp;gt;+&amp;lt;/a&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Counter&lt;/h3&gt;
&lt;p&gt;To get started, let us create a FlightJS component. Since we will be creating a counter, we’ll create a Counter component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var Counter = flight.component(function() {
   this.defaultAttrs({});
   this.after(“initialize”, function() {
   });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We did a few things in the example above. First, we created a new Flight component called Counter. Next, we defined that we have no default attributes to the Counter component (this will change soon). Attributes provide two big benefits: Component attributes create private variables for a component.&lt;/p&gt;
&lt;p&gt;Secondly, attributes give us a way to assign unique data to each instance of a component. Lastly, we have this weird &lt;code&gt;this.after(“initialize”)&lt;/code&gt; thing going on at the end. This is where a lot of the power comes from. Flight will execute the function we provide, as the second argument, after the initialize function has ran (initialize is an internal flight function) . Basically we’re telling Flight that once it gets itself in order, let us do what we need to.&lt;/p&gt;
&lt;p&gt;So what does a counter need? We need a total number that will be counted on. Oh yeah, and some buttons, that when clicked, either add or subtract one from the total. Let’s add this to our JavaScript.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var Counter = flight.component(function() {
   this.defaultAttrs({
      &quot;subtractSelector&quot;: &quot;.counter-subtract&quot;,
      &quot;additionSelector&quot;: &quot;.counter-add&quot;,
      &quot;count&quot;: 0
   });
   this.subtract(function() {});
   this.add(function() {});
   this.after(“initialize”, function() {
     this.on(&quot;click&quot;, {
        &quot;subtractSelector&quot;: this.subtract,
        &quot;additionSelector&quot;: this.add
     });
   });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First we added some attributes. These attributes provide us a DOM element for our subtract and add buttons—named subtractSelector and additionSelector respectively—and defines our starting number count. We then created some stubbed functions for once the selector’s event is triggered. Finally, an event handler is created. &lt;code&gt;this.on(“”)&lt;/code&gt; creates an event binding it to whatever we define within the quotes. In this case, we are waiting on a click event to be performed on our DOM selectors subtractSelector and additionSelector. Once a click is recognized, the corresponding function is called. (&lt;code&gt;this.subtract()&lt;/code&gt; or &lt;code&gt;this.add()&lt;/code&gt;)&lt;/p&gt;
&lt;p&gt;Continuing, here is our finished code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var Counter = flight.component(function() {
   this.defaultAttrs({
      &quot;subtractSelector&quot;: &quot;.counter-subtract&quot;,
      &quot;additionSelector&quot;: &quot;.counter-add&quot;,
      &quot;count&quot;: 0
   });
   this.subtract = function() {
      this.attr.count--;
   }

   this.add = function() {
      this.attr.count++;
   }

   this.uiDisplayCount = function() {
      this.$node.find(“h2.counter-total”).html( this.attr.count );
   }

   this.after(&quot;add subtract&quot;, function() {
      this.uiDisplayCount();
   });
   this.after(“initialize”, function() {
     this.uiDisplayCount();
     this.on(&quot;click&quot;, {
        &quot;subtractSelector&quot;: this.subtract,
        &quot;additionSelector&quot;: this.add
     });
   });
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finally we get functionality. The subtract and add function perform a -1 or +1 on the total count depending on which event is triggered. Once we perform these actions on our count, we have no way of displaying the new information. This is where &lt;code&gt;this.uiDisplayCount&lt;/code&gt; plays its role. From any jQuery enthusiast, this function is straight forward. Take our count attribute, and insert it into the html of .counter-total. But, what is &lt;code&gt;this.$node&lt;/code&gt;? This.$node is a property given to us from Flight that grabs a jQuery object of the DOM this component is attached to. Later on we will attach the Counter component to the DOM, and see how this plays out. Going to the next function, we tell our component to execute the uiDisplayCount function after the add or subtract functions are done being executed.&lt;/p&gt;
&lt;p&gt;Now there is one thing missing, how do we actually attach this to the DOM?&lt;br /&gt;
&lt;code&gt;Counter.attachTo(“.counter”, { count: 100 });&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Going back to before, our &lt;code&gt;this.$node&lt;/code&gt; property would return a jQuery object of our .counter, &lt;code&gt;$(“.counter”)&lt;/code&gt;. As we can see by the second parameter, we can also change what our default attributes are once we attach the component. This helps enforce the modular code Flight preaches. We can change the attributes to fit whatever the situation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Counter.attachTo(“.counter”, { count: 100 });
Counter.attachTo(“.counter-new”, {
                   count: 0,
                   subtractSelector: &quot;.new-subtract&quot;
                });
Counter.attachTo(&quot;.counter-new-new&quot;, {
                   subtractSelector: &quot;.s&quot;,
                   additionSelector: &quot;.a&quot;
                });
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;We Did It&lt;/h3&gt;
&lt;p&gt;And that is it, we completed our counter! We can see from this little example, Flight gives us some powerful tools in creating modulated code without the need to learn new paradigms. As always, there is much more Flight can do. For additional information on Flight check out their Github.&lt;/p&gt;
&lt;h4&gt;Counter Example&lt;/h4&gt;
&lt;p&gt;Here is our finished product: &lt;a href=&quot;http://codepen.io/ganderzz/pen/pjNdNq&quot;&gt;http://codepen.io/ganderzz/pen/pjNdNq&lt;/a&gt;&lt;/p&gt;
</content:encoded></item></channel></rss>