Push Weight with TypeScript

5 min read

Table of Contents:

Title Image for the Article

Introduction

With the new year, a lot of us have gone back into the gym. Now that the weights are getting stacked on the bars, it can become difficult to figure out how much of what you need to put on the bar. Learn a simple script to help you figure it out!

Interested to see how this project is written in another programming language? Check out the Python version here: Push Weight with Python

Setup

Since we are using TypeScript, you will need to have NodeJS installed. If you are not able to install Node you can follow along in JavaScript (even in the browser!) but you need to remove anything with "typing".

Don't have NodeJS? Install it here!

If you want to learn more about TypeScript click here.

If you want to learn more about NodeJS click here.

Navigate to where you want to project to live on your computer (the folder) and run these commands in your terminal:

npm init # Choose whatever options you want, default with hitting enter

This creates our main project (anything after the hash is a comment in the terminal). It creates a package.json that Node will use to keep track of the packages our project is using.

npm install typescript --save-dev

This will install TypeScript as a developer dependency. What that means is that it will only be used on the developer side. The end user will never see the TypeScript.

npx tsc --init

NPX is a special node command that allows special scripts to 'execute' commands. It is like running a program. The program tsc creates a basic tsconfig file that allows the TypeScript compiler to react to different conditions you want to set.

For this tutorial, we will leave all the options on the default.

This file controls how the TS compiler will react to certain ways you write your TypeScript code and how it will export it to JavaScript. You don't need to memorize it but understand what options it can give you.

Get the Values

The first thing we are going to do is use a tool offered by TypeScript. We are going to create a "type".

A type is a way to structure data and ensure that you're adhering to it.

The Typing System

The first, and only type for this project, will be the PlateResult.

type PlateResult =
{
    weight: number,
    count: number
};

This will help us make a piece of data that will store our results. This cannot be used in JavaScript if you are not using TypeScript!

We can see that it holds two values both of which are of type "number". Number means anything from an integer, float, double, etc. There are other types such as a string, null, classes, objects, and even other types!

Using the Process Module

If we want to calculate the weight, we need a way to get it from the user. The structure of running the program is:

node index.js 255 45

This will let our program know the weight we want to use and then an optional second argument (that is the barbell weight).

Let's look at the code that gets the variables for us:

if(parseInt(process.argv[2]) == NaN || process.argv[2] == null)
{
    console.log('Please enter a valid barbell weight');
    process.exit();
}
let barGoal = parseInt(process.argv[2]);
let barWeight = process.argv[3] ? parseInt(process.argv[3]) : 45;

We are going to check that the argument given is a number and not anything else. If it is not a number the program will let the user know and then tell the process module (its a core module in Node so we do not need to import it), to exit the program.

The bar weight will be an optional argument and we will check it with a ternary operator. It follows a format to check a value if its true then go with the first argument if not go with the other.

let variable = (condition of true or false) ? (if true) : (if false)

This is a way to short hand an "If" statement

The Logic

Now we will setup how the program will work with the information given.

barGoal -= barWeight; // Just subtract the barbell from the rest of the weight since we know how much it weighs
const WEIGHT_VALUES = [
    45,
    35,
    25,
    15,
    10,
    5
];
let results: PlateResult[] = [];

One array will hold the common weights a gym will have. If your gym has more or less feel free to alter the amounts.

The results array will hold the values once we run the rest of our program.

for(let i = 0; i < WEIGHT_VALUES.length; i++)
{
    let count = Math.floor(barGoal / (WEIGHT_VALUES[i] * 2));
    count *= 2;
    results.push({
        weight: WEIGHT_VALUES[i],
        count
    });
    barGoal -= WEIGHT_VALUES[i] * count;
}

We will use a for loop to go over all the plate weights and see how many each plate have with the weight.

We will subtract the weight in the heaviest to lightest order to get a right count. We will also multiply the value by two (since there needs to be a weight each side).

Math.floor

We ensure that the value is a whole number (since you can't have a partial plate). Math.floor rounds the value down no matter what the decimal is.

Once the value for the weight is figured it, it is stored in the array for later use.

We will then remove the weight amount from the barGoal so the next iteration does not factor in the original weight.

Once it reaches the end of the array, the for loop exits.

Map the Results

Now that we have our results, we will show the user in the console!

results.map(weight => {
    console.log(`You will need: ${weight.count} of ${weight.weight}.`);
});

This will show the results one by one using JavaScript's array.map function.

Execute It!

Now let us create a scrip that will run the code.

In our package.json we will change our "scripts" to:

"scripts": {
    "build": "tsc index.ts",
    "prestart": "tsc index.ts",
    "start": "node index.js"
  },

This will create a build script (if you just want to check the TypeScript to JavaScript conversion) and the "start" script will run the prestart then the start script. This will build the program and then run it.

Here is an example run script:

npm run start 225

What now?

The power of Node allows for this code to be ran almost anywhere. You can use this in a web app (React, Vue, Angular), make a desktop app with Electron, keep it in Node and send out the results through an API using Express or NestJS.

Recent Articles

Push Weight with Python

Create a simple terminal application that can let you know how much weight you need to put on the ba...

Validate Forms in TypeScript

Relying on HTML to validate your forms is just one step in ensuring visitors enter their information...

Automation with NodeJS

NodeJS can help you automate simple tasks. Being a web developer you can achieve the same goals as o...

Automation with Python

Python can take boring tasks away from you so you can continue to do other things. It is a scripting...

Speed With Cache in WordPress

Most WordPress sites use Apache as their server. Apache has a lot of tools built into it to speed up...

Social Media