Temperature Conversion

This example demonstrates a simple temperature converter from Celsius to Fahrenheit, using SMath.translate() to linearly interpolate between unit systems. The translation uses freezing and boiling points to fix the bounds of the linear interpolation.

Follow these steps to create a new project workspace and install the smath dependency to run this example.

# Create and open project folder
mkdir Temperature_Conversion_demo
cd Temperature_Conversion_demo
# Initialize project and install dependencies
npm init -y
npm i smath@1.12.0
# Create and open source file
touch "Temperature Conversion.mjs"
open "Temperature Conversion.mjs"

Copy and paste this source code into Temperature Conversion.mjs.

import { SMath } from 'smath';

// Water always freezes at the
// same temperature, but the
// units might be different.
// Define some constants to
// create two number ranges.
const C_Freeze = 0,
C_Boil = 100,
F_Freeze = 32,
F_Boil = 212;

// Use the `SMath` class to
// generate an array of five
// linearly spaced temperature
// values from 0 to 20.
const C = SMath.linspace(0, 20, 5);

// Use the `SMath` class to linearly
// interpolate the temperature in the
// C number range to a temperature
// in the F number range.
const F = C.map(c => SMath.translate(c, C_Freeze, C_Boil, F_Freeze, F_Boil));

// Print out each temperature
// in both units of C and F.
for (let i = 0; i < C.length; i++) {
console.log(C[i].toFixed() + 'C is ' + F[i].toFixed() + 'F')
}

In Temperature_Conversion_demo/, execute Temperature Conversion.mjs with NodeJS to generate an output.

node "Temperature Conversion.mjs"

You should expect to see an output similar to the one below.

0C is 32F
5C is 41F
10C is 50F
15C is 59F
20C is 68F
MMNEPVFCICPMFPCPTTAAATR