Write A Reduce Function From Scratch

JavaScript's Array object has a built-in reduce method. This is a handy,
yet underutilized method. Let's take a closer look at what reduce does and
see if we can implement it from scratch.

Reduce?

Here is what
MDN
has to say about reduce:

The reduce() method executes a reducer function (that you provide) on each
member of the array resulting in a single output value.

So, we can take an array of things and turn it into something else using a
function that we get to define.

const sum = list => list.reduce((total, val) => total + val, 0);

sum([1,2,3,4]) // => 10

The reduce method can seem pretty limiting at first when we read that it
produces "a single output value." That makes it sound like all it is good
for

Continue reading “Write A Reduce Function From Scratch”

How To Quit Vim

A lot of people would have you believe that Vim is near impossible to quit.
I'm here to dispel the rumors and show that there are quite a few ways to
quit Vim.

The Basic Quit

First thing if you start up a new Vim session with just vim, you'll see a
sort of splash screen. Below the title and copyright information is this
line:

type  :q<Enter>               to exit

This is a good place to start because it is perhaps the most straightforward
way to quit a Vim session — the :q or :quit command. It does come with
some minor caveats.

Here is the first caveat. If the current file (or some other file open in
another buffer) has been edited, but not yet saved, then Vim will stop you
from quitting. It wants to make sure you don't accidentally lose your
changes.

If you're sure you want

Continue reading “How To Quit Vim”

SQL: Inner Join vs. Outer Join

A standard join in SQL is implicitly an inner join. This means that only
records that can be matched on both sides of the join will be included in
the result set.

Here is an example of that:

> select * from table_a join table_b on table_a.letter = table_b.letter;
 name  | letter |  name  | letter
-------+--------+--------+--------
 Brian | A      | Dunn   | A
 Derek | C      | Parker | C

That same query could be written with inner join.

We can alternatively write an outer join which will ensure that the
subject of the join has all of it's rows included even if there isn't a
matching row from the other table.

So, which table is the subject of the join? If it is a left outer join,
then it is the table on the left of the join. If it is a right outer

Continue reading "SQL: Inner Join vs. Outer Join"

5 JavaScript Object Destructuring Tricks

The ES6 destructuring syntax is quite flexible. It allows us to do a lot of
nice things with objects and arrays that in the past would have taken many
distracting lines of code.

Let's look at five handy destructuring tricks for objects.

Trick #1

Remove an item from an object

// const data = { a: 1, b: 2, thingToRemove: "bye" };

const { thingToRemove, ...rest } = data;

console.log(rest); // { a: 1, b: 2 }

This is a concise way of getting a new copy of an object with a specific
key/value pair removed. Note that it is immutable and you are free to
specify as many keys as you'd like separated from the ...rest object.

Trick #2

Rename things in a destructuring

// const data = { coordinates: { x: 5, y: 6 }};

const { x: xCoord, y
Continue reading "5 JavaScript Object Destructuring Tricks"

Managing React Router Pathnames

So, you've introduced
react-router into your
single page React app as a way of managing routing. The app has started to
grow. There are many top-level routes for rendering different "pages". Some
of those "pages" now have sub-routing within them for managing wizard
workflows and sections with multiple "sub-pages". This is great. The dream
of routing within your React SPA has been realized.

Fast-forward a few months, and your elegant routing solution has become a brittle, error-prone maintenance nightmare. What happened?

A Simplified Example

Early into the development of a large React SPA, I noticed the above
scenario beginning to emerge. Some of what I noticed can be summarized in
the following series of code snippets. Note: these code snippets are not
full, working examples. Only the instructive parts have been included.

/* App.js */
return (
  <Switch>
    <Route path="/" component={Home} />
    
Continue reading "Managing React Router Pathnames"

Where Am I: URL Assertions with Cypress

The URL that appears in the browser's URL bar is one of the first and
primary ways that users interact with our web apps. The URL tells the app
and the user of their location within the route hierarchy of the app. It
sometimes even contains state. The URL consequently serves as an excellent
first assertion when writing integration tests.

When writing Cypress integration tests, there are
several ways for us to assert about the current URL.

The cy.url() and
cy.location()
functions are the primary ways for us to gain access to information about
the current state of the URL. From there, we can perform a variety of
assertions.

We can assert about the entire URL:

// URL: http://localhost:8000/pokemon
cy.url().should('eq', 'http://localhost:8000/pokemon');
// ✅ passes

This is certain the most precise assertion. The tradeoff is that it requires
us to know something

Continue reading “Where Am I: URL Assertions with Cypress”

When To Use Redux

Have you had a conversation about Redux recently that has left you wondering — despite all of its praise and the assured recommendations — if you made a big mistake when you typed the words, yarn add redux?

Jani is being a bit facetious here. But if you’ve been following along on twitter, there has been a lot of discussion about redux. The crux of the conversation is aimed at whether most apps even call for the use of redux and consequently if we, as developers, are using it when we don’t need it.

Generate Dates in PostgreSQL

PostgreSQL has shipped with the generate_series() function for quite some
time. This function is often used to generate series of numeric data. For
instance, in my post, Understanding Common Table Expressions with
FizzBuzz
,
I used it to generate a series of integers from 1 to 100.

As of PostgreSQL 8.4, support for generating series of timestamp data was
added. I don't see this used often, so let's take a look at it.

We could take a peak at the online documentation to see the function
signature, or we could pull it up in psql using \df.

> \df generate_series()
                                                               List of functions
   Schema   |      Name       |         Result data type          |                        Argument data types                         |  Type
------------+-----------------+-----------------------------------+--------------------------------------------------------------------+--------
 pg_catalog | generate_series | SETOF bigint                      | bigint, bigint                                                     | normal
 pg_catalog | generate_series | SETOF bigint                      | bigint, bigint, bigint                                             | normal
 pg_catalog | generate_series | 
Continue reading "Generate Dates in PostgreSQL"

Swap Two Column Values in SQL: Part 2

In the first part of this post we looked at a technique for swapping two
column values for existing records in a single statement. It is a relatively
sound solution that takes advantage of subqueries and a case statement.
Unfortunately, it has a couple drawbacks which we will address in this post.

This post builds off of Part 1. If you haven't already, give it a
read.

The first drawback can be demonstrated by building on our existing example,
the pages table which has the following data.

select * from pages order by ordering;
 id |  name  | ordering
----+--------+----------
  3 | Green  |        1
  1 | Red    |        2
  4 | Yellow |        3
  2 | Blue   |        4

In the interest of maintaining data integrity, it is reasonable to expect
that a table like this would have a uniqueness constraint on ordering.
Let's add that to ensure

Continue reading “Swap Two Column Values in SQL: Part 2”

Swap Two Column Values in SQL: Part 1

I recently needed to write a PostgreSQL snippet that would massage some
data. More specifically, I needed to swap the ordering of two different
records in the pages table. These records are made up of an id, a
name, and an ordering.

Here is a snapshot of the data in pages.

select * from pages order by ordering;
 id |  name  | ordering
----+--------+----------
  3 | Green  |        1
  1 | Red    |        2
  4 | Yellow |        3
  2 | Blue   |        4

We've been informed that we need to swap the ordering of Red and Blue.
We can see here in this snapshot of the data that Red has an ordering of
2 and Blue has an ordering of 4.

Doing a swap based on the data that we have locally would be most easily
accomplished with a couple update statements.

update pages set ordering 
Continue reading "Swap Two Column Values in SQL: Part 1"

Advanced Queries with ActiveRecord’s From Method

For those of us that write database-backed Rails apps,
ActiveRecord is a
familiar beast. We know its various query building methods well: where,
order, limit, and even group. The most important SQL clause is
conspicuously missing from our repertoire: the from clause.

Chances are you can't think of many, if any, times that you've used
ActiveRecord's from method. This is to be expected. The from clause in
SQL specifies the target table of a query. In the context of ActiveRecord, the
target table is explicitly expressed by the model from which you query.

Consider the times you use one-liners such as Developer.first,
Developer.all, and Developer.count. With each of these, the developers
table as the target of the query is expressed by the use of the Developer
model.

So, where does the from method come into the picture?

The
docs
describe the

Continue reading "Advanced Queries with ActiveRecord’s From Method"