Josh Pitzalis

My software engineering learning log

Read this first

typescript

Variables

let apples = 5;
let speed: string = 'fast';
let hasName: boolean = true;
let nothingMuch: null = null;
let nothing: undefined = undefined;

Built in objects

let now: Date = new Date();

Arrays

let colors: string[] = ['red', 'green', 'blue'];
let myNumbers: number[] = [1, 2, 3];
let truths: boolean[] = [true, true, false];

Classes

class Car {}
let car: Car = new Car();

Object literals

let point: { x: number; y: number } = {
  x: 10,
  y: 20,
};

Functions

const logNumber: (i: number) => void = (i: number) => {
  console.log(i);
};

//or

const logNumber =  (i: number): void  => {
  console.log(i);
};

View →


Fakes, spies, stubs & mocks

I learned how to test code using Jest. Today I’m working on a codebase that doesn’t have Jest and I have to use Jasmine and Sinon instead.

The most confusing bit is going through the documentation and trying to understand what fakes, spies, stubs, and mocks are. In Jest, I just dealt with mocks. I thought everything was a mock.

I’ve learned that all of these things fall under the umbrella of test doubles. I think I’ve figured out what the difference between each type of test double is now…

Spies - Listen

So a spy is when you just listen to the implementation of a dependency. You run the original function, but you just want to test whether it was run, how many times it was run, and what parameters it was run with.

Mocks - Bypass

A mock is when you bypass a function altogether. If you have a dependency that’s coupled to your code that does important stuff but is unrelated to what...

Continue reading →


React Testing Library and Redux Observable

You can use the test scheduler to test sequences in epics but integration testing breakdown if you don’t include redux observable in your test redux wrapper.

Here is how I successfully managed to integrate redux observable with react testing library by mocking out the store. This wrapper replaces the default react-testing-library render method with a render method that gives components access to redux, react-router and redux observable in a test environment.

import React from 'react';
import { render as rtlRender } from '@testing-library/react';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { createEpicMiddleware } from 'redux-observable';
import { rootReducer, rootEpic, dependencies } from './store';

function configureStore(initialState) {
...

Continue reading →


Redux Observable Loops

You can make redux complicated but at the most fundamental level, you have a view layer that lets you fire actions that can update the state. There is middleware and actions hit reducers which update the store, but let’s consider those implementation details. Practically speaking, it’s a tiny action loop where View > Action > State.

Redux observable introduces a separate action loop that runs alongside the tiny loop. The view layer lets you fire actions that trigger epics, which can fire off more actions, that can update the state. So it’s View > Action > Epic > Action > State.

This diagram helped me put all this all together.

PNG image-0FBFB8DA8517-1.png

A few important details:

  1. All actions will run through the tiny loop before they run through the epic loop.
  2. All Epics must return an action or it’s doom.
  3. If your epic returns the same action it received, you will create an infinite loop of doom.
  4. If your...

Continue reading →


Using Redux Observable For Async Stuff

Redux doesn’t handle async work too well. Thunk is the go-to solution, but it’s not always great for testing.

Here is how to do a basic async data fetch with redux observable;

export const exampleEpic = (action$, state$, { later }) =>
  action$.pipe(
    ofType('projects/updateTitle'),
    debounceTime(1000),
    switchMap(({ payload }) =>
      from(later(2000, payload)).pipe(
        map(res => ({
          type: 'projects/fetchFulfilled',
          payload: res,
        }))
      )
    )
  );

Thunks are called epics in redux observable. All epics take three parameters (action$, state$, { dependancies }). The last two are optional.

The action$ parameter is a stream of all redux actions emitted over time. state$ is the state of your redux store. dependencies can contain any side effects that you want to use in your epic. Passing in side effects as dependencies is super handy...

Continue reading →


Setting Up Redux Observable

If you are adding redux observable to a new redux project, the first step is to install it along with RXJS

npm i redux-observable rxjs

The next step is to set up the middleware.

Create a middleware and pass it to the createStore function from Redux. Then you create a root epic that combines all your epics and call epicMiddleware.run() with the rootEpic.

import { createStore, compose, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { combineEpics } from 'redux-observable';
import  { epicA } from './epicA';
import  { epicB } from './epicB';

export const rootEpic = combineEpics(
  epicA,
  epicB
);

const epicMiddleware = createEpicMiddleware();

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default function configureStore() {
  const store = createStore(
    rootReducer,
    composeEnhancers(
...

Continue reading →


A Basic Smart Contract

pragma solidity ^0.4.24
contract Campaign {

    address public owner;
    uint public deadline;
    uint public goal;
    uint public fundsRaised;
    bool public refundsSent;

    event LogContribution(address sender, uint amount);
    event LogRefundsSent(address funder, uint amount);
    event LogWithdrawal(address beneficiary, uint amount);

    struct FunderStruct {
        address funder;
        uint amount;
    }

    FunderStruct[] public funderStructs;

    constructor ( uint _duration, uint _goal) public {
        owner = msg.sender;
        deadline = block.number + _duration;
        goal = _goal;
    }

    function isSuccess() public constant returns(bool isIndeed) {
        return (fundsRaised >= goal);
    }

    function hasFailed() public constant returns(bool hasIndeed) {
        return (fundsRaised < goal && block.number > deadline );
    }

    function
...

Continue reading →


Immutable Arrays

Copy an array…

clone = array => [...array]

Add something to the end of an array…

push = array => [...array, thing]

Remove the last item in an array…

pop = array => array.slice(0,1)

…or the first item…

shift = array => array.slice(1)

or an item at a specific index…

delete = i => array => [...array.slice(0,i), ...array.slice(i+1)]

If you are unsure whether a method mutates or not then checkout doesitmutate.xyz

Thank you Luke Jackson.

View →


Switching Between Staging and Production Firebase Deploys In A Create-React-App

When building web applications on firebase, it is always a good idea to push the final application to the brand new firebase project.

Go into your firebase console and setup a new firebase project. Explicitly name this project something-something-PRODUCTION so that there is never any confusion between your original project and this new production one.

Your original project becomes your staging server. A safe place for you to try out new features and test things before you push the changes to your production server.

Your production server is the one you connect your domain to and share with the world.

You can flip between the two by connecting both firebase projects to your web application.

In the command line navigate into your project and type:

firebase use --add

The command line will ask you which project you want to connect to, scroll through the available projects till you...

Continue reading →


Things To Learn Before Redux

With React’s new context API you can go a long way with a plain old react app before things become tedious. I encourage you to learn how to use the new context API before you reach for redux.

I also have tremendous respect for component setState. Learn how to use it before you start with redux. Did you know setState takes a callback? Did you know you can pass setState an updater function? Did you know that you can declare state changes outside of a component?

Using Redux before you understand how to use higher order components can also be a little confusing. Before you start using redux understand higher order components well enough to know when it’s better to use a render prop.

If you’re comfortable with context, you’ve mastered setState batching and you know what a prop-namespace-clash is, and you are still finding you app hard to manage then you are going to love redux.

Redux...

Continue reading →