Categories
Javascript

Bit operators

In the beginning, there was the bits, they were the 1s and the 0s. 1s were positive bits, they gave meaning to things, 0s were negative, but necessary. When working together, they could make wonderful things. Let’s look at this group of bits

0101

what are these 0s and 1s telling us? Basically this:

0(8) + 1(4) + 0(2) + 1(0) = 5

Each 0 or 1 represents a power of 2 value, starting from the right with 1, to the left with 8. If a 1 is present, we sum that value it represents. In this case, we get 4 + 1 = 5. 0101 is the binary representation of the number 5.

We dont count the 0s, but they hold an important role, without them, we couldnt make all of the numbers.

We don’t see the bits much today, but they still exist, and are as important as ever. Still, we can play with them even today, with the use of bit operators.

open up your JS console, let me introduce you to them

<< “Shift left”

x << y

shift x by y bits, to the left. same as x * 2**y

examples:

5 << 1 // "0101" << 1 => "1010" => 10 => 5 * 2**1
10 << 2 // "1010" << 2 => "101000" => 40 => 10 * 2**2 

>> “Shift right”

x >> y

shift x by y bits, to the right

examples:

10 >> 1 // "1010" >> 1 => "0101" => 5 => 10 // (2**1)
20 >> 2 // "10100" >> 2 => "00101" => 5 => 20 // (2**2)

& “Bitwise and”

x & y

Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it’s 0.

examples:

10 & 3 // "1010" & "0011" 
// the 1st bits for both are 1 and 0 so => 1 & 0 = 0
// the 2nd bits for both are 0 and 0 so -> 0 & 0 = 0
// the 3rd bits for both are 1 and 1 so => 1 & 1 = 1
// the 4th bits for both are 0 and 1 so -> 0 & 1 = 0
// output => "0010" => 2

| “Bitwise or”

x | y

Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it’s 1.

examples:

10 | 3 // "1010" | "0011"
// 1st bits 1 or 0 => 1 | 0 => 1
// 2nd bits 0 or 0 => 0 | 0 => 0
// 3rd bits 1 or 1 => 1 | 1 => 1
// 4th bits 0 or 1 => 0 | 1 => 1
// output => "1011" => 11

~ “Complement”

~ x

Returns the complement .A complement is the opposite of what bits you currently have, and is how you write negative numbers. The complement of 1010 is (11...)0101

This is the same as -x -1

examples:

~ 5 //  "(1...)1010" => -5 -1 => -6
~ 10 // "(1...)0101" => -10 -1 => -11

Why the (1…)? This is just me giving a notation to all the 1s present before the relevant bits. Becase when writing negative numbers in binary, you flip the 1s with 0s and the 0s with 1s. Imagine we are dealing with 8 bits. You treat patterns from “00000000” to “01111111” as the whole numbers from 0 to 127, and reserve “1xxxxxxx” for writing negative numbers.

A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). So -1 is complement(1 – 1) = complement(0) = “11111111”, and -10 is complement(10 – 1) = complement(9) = complement(“00001001”) = “11110110”. This means that negative numbers go all the way down to -128 (“10000000”).

BitwiseOperators – Python Wiki

Background image by:
https://pc-paramedix.com/the-matrix-binary-code-blue-wallpaper-1920×1080/

Categories
Javascript

React Hooks and Context to Replace Redux

Things have changed since I came back to React a couple of weeks ago. I had used React extensively for 2 years around 2015-2017. Back then, redux was the craze. People wanted to use it for every project, no matter the complexity. React Hooks and Context have come to change that.

Now that I come back, it’s the other way around. Using Redux is seen as overkill now, nobody wants to go near it

I understand why, it brings a lot of boilerplate and it forces you into an architecture you might not be comfortable with.

So what are people doing to replace redux? React Hooks and Context. This lets everyone share globlal variables easily, which was the main selling point of Redux in my opinion.

Context

The context API was there before, yes, but it was cumbersome to use. React-Redux itself, alongside other libraries, used the old context API under the hood to share global variables. Things changed in React 16.3.

Context is easy to use now, and makes the data globally available anywhere in the component tree.

 If you need to update the context, then you can do that at the provider’s level, just pass in another user object. If you want to update the context from a nested component, you can pass a function through the context

Hooks

In the context code above, you may have seen this:

const { name } = useContext(UserContext)

That’s a hook. They are completely new to me, but they have quickly won my heart. If you’re not into them yet, just watch Dan Abramov introduce them:

When function components came around, I wanted to use them all over, they were nice and compact, and more javascript like (just functions).

I hated having to use class components just because I couldn’t handle state or lifecycle stuff in my function components. Now that hooks are here, there’s generally no reason not to use function components. Even the react team likes function components and want to get away from class components as you can see from the video

Do Hooks and Context replace Redux?

Not entirely. But they do provide you with what I think is Redux most important feature: Having global state easily available in any component. Like we saw before, if you have a context provider somewhere above your component’s tree, all you have to do in the component is

const { name } = useContext(UserContext)

and you can start using the user name in your component. But that’s pretty much all that Context gives us, Redux provides much more like handy dev tools, centralized app logic by using reducers, middleware to better handle async, powerful selectors to the state, and more. This stack overflow answer gives a nice and concise answer for React Hooks and Context vs Redux.

Example

Here’s a running example of the code used in this post. Try changing the name to yours!

Categories
Javascript Projects

Maze Generation in React

Play with it

A few months ago I read an article on maze generation and it sparked my interest. Since then I began working little by little on a project to create a maze generator.

I took the time to make it visually show the steps the algorithm takes. You can see it generating cell by cell, giving each cell a set value, then deciding which ones to merge horizontally, and later vertically. I also gave you the ability to choose how slow the maze is generated, to see better how it works. Other settings are also the width and height, so you can make the maze reaaaally big if you want. Finally, I give you the choice to decide the merge chance, a value between 0 and 1. It’s the chance to join cells horizontally. A high chance (like 0.9) tends to create horizontal mazes while a low chance creates more vertical ones.

If you’re wondering why there’s no entrance or exit, it’s because you can choose any two points in the maze’s outer walls to open up and there will always be a path between the two.

I chose React since it’s a pretty famous tool for web UI and I wanted to give the user the ability to manipulate the maze generation through some inputs

The maze generation algorithm is called Eller’s algorithm. One of the cool things about it is that it can continue building rows for the maze for a long time without running out of memory. This is because it only needs to know about 2 rows at any given time.

Sources:
https://weblog.jamisbuck.org/2010/12/29/maze-generation-eller-s-algorithm
http://www.neocomputer.org/projects/eller.html

Link to generator:
http://jpsierens.me/maze-generation/

The project is in github if you want to take a look.

Categories
Development Javascript

Angular Tutorial: Server Side Rendering

How do you go from a normal app to a server-rendered app? Let’s start with a normal app. Download  Tour of Heroes. This is the completed tutorial app they use over at angular.io.

Once downloaded, head over to the root of the app and npm i  to install the dependencies. Then do npm start and head over to http://localhost:4200  to check the app working. You should see something like:

Tour of Heroes main page

When you first go into the page, there is nothing. the HTML the server sends doesnt have anything in the body more than the script files. The browser has to first get the scripts and execute them before we can see something. This is how SPAs (Single Page Application) work.

With SSR (Server Side Rendering) we can change that so that when we navigate to a page, we get pre-rendered HTML like we did in the pre SPA days

To get this in Angular you do:

ng add @nguniversal/express-engine –clientProject angular-io-example

This modifies your app to support Server Side Rendering. It also generates files that are now needed for it to work. You should see the terminal output the new files generated and the ones modified in your project:

The generated and updated files

Note: If you don’t see new the new files, bump up the TypeScript version to something like 3.2 and try again. Happened to me and found the answer in stack overflow. If you still can’t run the app, use my version.

That’s it. Now your app supports SSR. Don’t believe me? Run the following:

npm run build:ssr && npm run serve:ssr

That will build the app and start a node server on http://localhost:4000. Head over there to see for yourself. Check that you are on port 4000 and not 4200.

Note: You can still run the app in its normal non-SSR mode whenever you want with npm start

Proof that it Works

When you open the server rendered version you can check it works by heading over to the network tab in the chrome inspector. Take a look at the first document the browser receives, it’s always the HTML. Inside you will see there’s a bunch of content inside the body tag.

This means the browser does not have to wait for the Javascript to execute to paint something in the screen. It can do that immediately by parsing the HTML thanks to having stuff rendered in the server.

In the network tab, the first file to download is the document. This brings the HTML for the page. We can see that in the preview we already have a lot of elements ready to be rendered by the browser. No need to wait for the JS

If you were to run the normal app without SSR again. You could again check the network tab and inspect the document, you will see nothing in the preview since there is no pre-rendered content coming in from the server. Everything has to be built by the browser when it executes the Javascript.

A blank preview. Nothing inside the body tag since there’s no SSR

Limitations of Server Side Rendering

Server Rendering has its limitations. If you slow down the speed, you will notice that some functionality of the app is not working, even if a lot has already been painted to the browser. This is because it needs to wait for the Javascript to load to have full functionality. Some things work right away though, like navigation.

Navigation works right away because if the Javascript hasn’t loaded and a user clicks a link, that request is sent back to the server where it is handled. Once the Javascript is loaded, however, the navigation is handled by the browser with the use of Angular’s router. It’s quite awesome really, the user doesn’t perceive who’s handling the navigation or when the change of navigation ownership happens, it just works.

The few milliseconds you are left with only navigation capabilities is something you should take into consideration when developing with SSR. Do you want users to be able to do something right away when a component loads? Maybe you should put a loader on that component, so the users know that part is still loading. You can take off the loader once angular has been bootstrapped.

You can also use preboot to capture any actions the user has taken before the app fully loads and replay them.

Generated files: In-depth

Let’s go through the generated files and what they do.

main.server.ts

This is the bootstrapper for the server app. It exports the AppServerModule . 

app.server.module.ts

This is the main module when using server side rendering. It imports the AppModule , which contains all the app’s logic. This is good, the app shouldn’t know if it’s going to be server rendered or not.

Then we import the ServerModule  from the @angular/platform-server  package. This module probably has code that supports running Angular on the server, just like BrowserModule gives Angular support on the browser.

Lastly we import ModuleMapLoaderModule which comes from the universal package. This is used to load the modules instantly instead of lazily, we dont need lazy loading when loading modules in the server.

tsconfig.server.json

Pretty self-explanatory. It’s the compile config for TypeScript in the server. It actually extends the tsconfig.app.json file.

webpack.server.config.js

Webpack server configuration. This tells Webpack to compile the server server.ts (which is in TypeScript) and output in the dist folder.

server.ts

Our node express server. This server handles requests to the app, builds what it can on the server (SSR), and sends it to the browser.

How does it all tie in together?

So we saw the generated files and know what they do. Now we can look at how it all ties in together, the workings of this new app.

Build and Run

First of all, let’s go back to these commands:

npm run build:ssr && npm run serve:ssr

It builds the app in SSR mode and runs a server to support it. Let’s look at the first command build:ssr . This is an npm command which was generated when we made the app support Server Side Rendering. You can find it in the package.json. It does this:

npm run build:client-and-server-bundles && npm run compile:server

The first command build:client-and-server-bundles  will do the builds for both the app and server bundles:

ng build --prod && ng run angular.io-example:server:production

As you can see, it boils down to using angular-cli to build the prod version of the app and also this angular.io-example:server:production , which builds the server bundle. For the client app, the main.ts file is used as entry point. For the server, it’s main.server.ts

The second command  compile:server will compile the server with a direct command to Webpack. Since this is outside Angular, we can’t use the angular-cli. Also, we need to run this because the server source file is in TypeScript, so it needs to be compiled and sent to the dist folder from where it will be run.

webpack --config webpack.server.config.js --progress --colors

Let’s go back to the original commands and see the second command npm run serve:ssr . If we check the package.json we see this refers to this command: node dist/server . It starts a node server file located in dist/server, which is the compiled version of the server.ts file from before.

The last part is important. We now have a server. Whereas before we didn’t need one, now we do, and we can’t have SSR without it. Think about this when you design the architecture where your app will run. You could have a node express server running to handle page requests, and have another one in any tech you want that handles data requests.  Or you can use the node server as a proxy between your app and your data server too, or just have everything in node. Up to you!

Flow

We know how the app is built and run now. Let’s look at how it flows.

It all starts with navigating to the app. Upon entering a URL, say the default page, the request for that page is sent to the server. This is where server.ts comes in.

The first relevant code line we find in the server.ts is

const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

We are importing the server module, the one we export in main.server.ts. Remember this one has the three imports we discussed earlier: AppModule, ServerModule, ModuleMapLoaderModule.

After that we have this piece of code:

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

We are telling express that we will use the ngExpressEngine as the HTML engine, a handy tool to abstract Server Side Rendering stuff. We pass in the server module containing everything needed to run the app, and also the lazy module map to load modules instantly.

So when a request comes in, this is the part being fired:

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

the HTML engine we configured earlier will take care of handling the request by compiling angular and spitting out the HTML to the browser.

Once in the browser, the flow of the app is the same as a non-SSR app, with the exception that now the page renders faster.

Categories
Javascript

Webpack for connected set ups

For a long time, I had the notion that webpack could only be ran for set ups that are independent from the back end. For example SPAs that only communicate with AJAX.

I closed my mind into thinking that it had to be ran with a development server. You would make the webpack config file and use that to run the dev server. That would do all the cool things like Hot Module Replacement and having all the JS in RAM so changes would be blazing fast. Then, when you needed to actually use it for production, you would do a build and be done with it.

I blame the tutorials and webpack docs partly, because when I started looking into webpack around 2 years ago all the examples where like what I mentioned before, independent set ups.

So the only time I used webpack was for personal projects. But on my professional projects I would use gulp with require/browserify/jspm whatever was in flavor besides webpack. Until I came across a project that used it the way I wanted to.

You can use webpack to develop in a set up where you have the back end connected with the front, for example with a templating language. All you need to do is define an input file and output directory in your webpack config. Then you run webpack -w and that’s it. It will watch for changes, and then do what it does, and throw it to the output directory you specified. After that, you just point to the output file in your template like <script src="./build/index.js" />. This project does just that, as simple as possible.

You won’t benefit from HMR, but at least you CAN use webpack for these connected set ups which are much more common in the professional world.

Webpack can be simple too.

Example

I went ahead and created a very simple example for you. Click here to download it through github.

Install dependencies:

npm i

run webpack:

npm run webpack

this will bundle what’s in the entry file and its imports and output it in the /build directory.

Check out the changes by navigating to the index.html file, or start a server in the project’s root directory with:

python -m SimpleHTTPServer 3001

Some info on the project

The javascript is simple, it just imports a module and calls it. This is to demonstrate what the core of webpack is all about: bundling.

import sayHi from './sayHi';

sayHi();

So to get that code above to work, webpack needs to be set up:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, "build"),
    filename: 'index.js',
  },
};

This is all webpack needs to do its job. An entry place to your app, and where to output the generated bundle. That’s it.

All the other stuff, loaders, plugins, etc. are to enhance webpack, and accommodate to your needs of using babel, SASS, css modules, etc…