### Unit Arithmetic Examples in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Illustrates various unit arithmetic operations including multiplication for area, division for pressure, and comparisons. It shows how to use predefined units like meters, kilograms, and bars, along with prefixes like 'milli'. This example requires importing relevant units and `Measure` from 'safe-units'. ```typescript import { bars, kilograms, Measure, meters, milli, seconds } from "safe-units"; const width = Measure.of(3, meters); const height = Measure.of(4, meters); const area = width.times(height).scale(0.5); const mass = Measure.of(30, kilograms); const mps2 = meters.per(seconds.squared()); const acceleration = Measure.of(9.8, mps2); const force = mass.times(acceleration); // 294 N const pressure = force.over(area); // 49 Pa const maxPressure = Measure.of(0.5, milli(bars)); // 0.5 mbar pressure.lt(maxPressure); // true ``` -------------------------------- ### Built-in Prefixes for SI and Binary Units in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/docs/builtin.md This example demonstrates the usage of built-in prefix functions provided by the Safe Units library. These functions allow for the creation of new measures with corresponding symbols by operating on existing measures, covering both SI and binary prefixes. ```typescript import { builtinPrefixes } from "safe-units"; // Example using SI prefix 'kilo' const kiloMeters = builtinPrefixes.kilo(new Meters(1000)); console.log(kiloMeters.toString()); // Output: "1 km" // Example using binary prefix 'kibi' for memory const kibiBytes = builtinPrefixes.kibi(new Bytes(1024)); console.log(kibiBytes.toString()); // Output: "1 KiB" ``` -------------------------------- ### Measure Representation Example (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Demonstrates the basic representation of measures using base SI units in TypeScript. This example illustrates how values with different units are internally represented using a consistent set of base units. ```typescript console.log('measuresRepresentationIntro.ts'); ``` -------------------------------- ### Perform Unit Conversion in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Explains how to convert measurements between compatible units and define custom units. This example demonstrates converting between Imperial and SI units, as well as creating custom units like 'furlong' and 'fortnight'. It uses methods like `.in()` for conversion and `.valueIn()` to retrieve the numeric value in a target unit. Dependencies include various length units from 'safe-units'. ```typescript import { Measure, meters, feet, inches, miles, kilometers } from "safe-units"; // Define custom units const furlong = Measure.of(220, yards, "fur"); const fortnight = Measure.of(14, days, "ftn"); // Convert between units const distance1 = Measure.of(8, furlong); console.log(distance1.in(miles)); // "1 mi" const distance2 = Measure.of(1, miles); console.log(distance2.in(furlong)); // "8 fur" // Convert metric to imperial const height = Measure.of(1.8, meters); console.log(height.in(feet)); // "5.905511811023622 ft" console.log(height.in(inches)); // "70.86614173228346 in" // Use valueIn to get numeric value const km = Measure.of(5, kilometers); const metersValue = km.valueIn(meters); // 5000 ``` -------------------------------- ### Derived Measure Representation Example (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Shows how derived values maintain their representation in base SI units, even after operations. This highlights the library's approach to avoiding explicit unit conversions by using a consistent internal representation. ```typescript console.log('measuresRepresentationDerived.ts'); ``` -------------------------------- ### Wrapping Unary Functions for Measures (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Provides an example of using `wrapUnaryFn` to adapt a standard unary function (like absolute value) to operate on measures. The wrapper ensures that the function preserves the unit of the input measure. ```typescript import { wrapUnaryFn } from "safe-units/functionWrappers"; // Assume a simple absolute value function for numbers const abs = (n: number): number => Math.abs(n); // Wrap the absolute value function to work with measures const measureAbs = wrapUnaryFn(abs); // Example usage (assuming 'meters' is a defined unit type) // const length = 5 * meters; // const absLength = measureAbs(length); // console.log(absLength); // Would output the absolute value with the same unit ``` -------------------------------- ### Ensure Type Safety with Unit Operations in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Highlights how TypeScript's type system, enforced by Safe Units, prevents incompatible unit operations at compile time. It shows examples of operations that would fail type checking, such as adding different units or comparing dissimilar units, and demonstrates correct usage with matching types. This snippet requires types like `Force`, `Length`, `Time`, and `Velocity` in addition to base measurement constructs. ```typescript import { Force, Length, Measure, meters, seconds, Time, Velocity } from "safe-units"; const length = Measure.of(10, meters); const time = Measure.of(5, seconds); // These will produce TypeScript errors: // @ts-expect-error - Cannot add different units const error1 = length.plus(time); // @ts-expect-error - Cannot compare different units const error2 = length.eq(time); // Velocity is m/s, not m*s const velocity: Velocity = length.over(time); // OK // @ts-expect-error - m*s is not assignable to Velocity (m/s) const error3: Velocity = length.times(time); // @ts-expect-error - Cannot convert length to time const error4 = length.in(time); // Correct usage with matching types const length1: Length = Measure.of(10, meters); const length2: Length = Measure.of(5, meters); const sum: Length = length1.plus(length2); // OK ``` -------------------------------- ### Create a generic measure type for custom number types Source: https://github.com/jscheiny/safe-units/blob/master/docs/generic-measures.md This example shows how to create a custom measure type, 'WrappedMeasure', using 'createMeasureType'. It leverages the 'WrappedNumber' type and provides necessary arithmetic operations and the multiplicative identity ('one') for the custom number system. ```typescript import { createMeasureType, Unit } from "safe-units"; // Assume WrappedNumber, compareWrappedNumbers, and wrappedNumberOne are defined as in the previous example. type WrappedMeasure> = GenericMeasure; const WrappedMeasure = createMeasureType( { one: () => wrappedNumberOne, compare: compareWrappedNumbers, }, // Add other arithmetic operations like plus, times, divide, etc. here if needed, // by providing functions that operate on WrappedNumber instances. // For simplicity, if your WrappedNumber class has methods like plus() and times(), // createMeasureType might be able to infer them or you might need to explicitly map them. ); // Example usage: // const distance = WrappedMeasure.of(new WrappedNumber(10), "m"); // const time = WrappedMeasure.of(new WrappedNumber(5), "s"); // const speed = distance.divide(time); // console.log(speed.toString()); // Should represent speed in m/s with WrappedNumber ``` -------------------------------- ### Perform Unit Arithmetic Operations in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Illustrates performing arithmetic operations like multiplication, division, addition, and subtraction with measurements. The library automatically handles unit composition and type checking to ensure dimensional correctness. This example uses `Measure.of`, `meters`, `seconds`, `kilograms`, and unit-specific methods like `times`, `over`, `plus`, and `squared`. ```typescript import { Measure, meters, seconds, kilograms } from "safe-units"; // Multiplication and division const length = Measure.of(30, meters); const width = Measure.of(20, meters); const area = length.times(width); console.log(area.toString()); // "600 m²" // Calculate velocity const distance = Measure.of(100, meters); const time = Measure.of(5, seconds); const velocity = distance.over(time); console.log(velocity.toString()); // "20 m * s^-1" // Calculate force (F = ma) const mass = Measure.of(10, kilograms); const mps2 = meters.per(seconds.squared()); const acceleration = Measure.of(9.8, mps2); const force = mass.times(acceleration); console.log(force.toString()); // "98 kg * m * s^-2" // Addition and subtraction (same units only) const distance1 = Measure.of(100, meters); const distance2 = Measure.of(50, meters); const total = distance1.plus(distance2); console.log(total.toString()); // "150 m" ``` -------------------------------- ### Define a custom number type for generic measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/generic-measures.md This example demonstrates defining a custom number type, 'WrappedNumber', which can be used as the underlying numeric representation for a generic measure. It includes basic arithmetic operations and comparison methods required by 'createMeasureType'. ```typescript class WrappedNumber { constructor(public value: number) {} plus(other: WrappedNumber): WrappedNumber { return new WrappedNumber(this.value + other.value); } times(other: WrappedNumber): WrappedNumber { return new WrappedNumber(this.value * other.value); } } function compareWrappedNumbers(a: WrappedNumber, b: WrappedNumber): number { if (a.value < b.value) { return -1; } else if (a.value > b.value) { return 1; } else { return 0; } } const wrappedNumberOne = new WrappedNumber(1); ``` -------------------------------- ### Add static methods to a generic measure type Source: https://github.com/jscheiny/safe-units/blob/master/docs/generic-measures.md This example demonstrates how to extend a generic measure type, 'WrappedMeasure', by adding custom static methods. It shows how to pass an object of static methods as the second argument to 'createMeasureType' to augment the measure's functionality. ```typescript import { createMeasureType, Unit, GenericMeasure } from "safe-units"; // Assume WrappedNumber, compareWrappedNumbers, and wrappedNumberOne are defined. type WrappedMeasure> = GenericMeasure; // Define static methods for WrappedMeasure const wrappedMeasureStaticMethods = { doubleMeasure: >(measure: WrappedMeasure): WrappedMeasure => { // Example: Doubles the value of the measure using WrappedNumber's times method const doubledValue = measure.value.times(new WrappedNumber(2)); return WrappedMeasure.of(doubledValue, measure.unit); }, // Add other static methods as needed }; const WrappedMeasureWithStatics = createMeasureType( { one: () => wrappedNumberOne, compare: compareWrappedNumbers, // Add other required operations for WrappedNumber }, wrappedMeasureStaticMethods // Pass the static methods object here ) as unknown as { // This type assertion helps ensure the static methods are recognized // You might need to adjust this based on how createMeasureType is typed new >(value: WrappedNumber, unit: U): WrappedMeasure; of>(value: WrappedNumber, unit: U): WrappedMeasure; dimensions>(): B; doubleMeasure>(measure: WrappedMeasure): WrappedMeasure; }; // Example usage: // const initialMeasure = WrappedMeasureWithStatics.of(new WrappedNumber(5), "m"); // const doubled = WrappedMeasureWithStatics.doubleMeasure(initialMeasure); // console.log(doubled.toString()); // Should show 10 m ``` -------------------------------- ### Create Simplified Game Engine Unit System (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md A simplified approach to creating a custom unit system, omitting the interface for type intellisense. This is useful when clean type hints are not a priority. ```typescript import { UnitSystem } from "@safe-units/utils"; const GameUnitSystem = UnitSystem.from({ length: Unit.of("eu"), time: Unit.of("ms"), frames: Unit.of("fr") }); type GameUnitSystem = typeof GameUnitSystem; ``` -------------------------------- ### Create Game Engine Unit System (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md Defines a custom unit system for a game engine with dimensions for length, time, and frames. It includes defining the basis and using an interface for cleaner type intellisense. ```typescript import { UnitSystem, Unit } from "@safe-units/utils"; interface GameUnitSystemBasis { length: Unit<"eu">, time: Unit<"ms">, frames: Unit<"fr">; } const GameUnitSystem = UnitSystem.from({ length: Unit.of("eu"), time: Unit.of("ms"), frames: Unit.of("fr") }); type GameUnitSystem = typeof GameUnitSystem; ``` -------------------------------- ### Create Custom Unit Systems in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Explains how to define custom unit systems for domain-specific applications, allowing for independent or interoperable unit definitions. This includes creating base units, derived units with symbols, and performing calculations within the custom system. ```typescript import { Measure, UnitSystem } from "safe-units"; // Define a game unit system const GameUnitSystem = UnitSystem.from({ frames: "fr", time: "s", health: "hp", }); // Create base units const frames = Measure.dimension(GameUnitSystem, "frames"); const seconds = Measure.dimension(GameUnitSystem, "time"); const healthPoints = Measure.dimension(GameUnitSystem, "health"); // Define types const Frames = frames; type Frames = typeof frames; const Time = seconds; type Time = typeof seconds; const FrameRate = Frames.over(Time); type FrameRate = typeof FrameRate; // Create derived unit with symbol const fps: FrameRate = frames.per(seconds).withSymbol("fps"); // Use in calculations const minFrameRate = Measure.of(60, fps); const measuredFrames = Measure.of(8000, frames); const elapsedTime = Measure.of(120, seconds); const measuredFps: FrameRate = measuredFrames.over(elapsedTime); if (measuredFps.lt(minFrameRate)) { console.log("Frame rate below minimum"); // Check performance } console.log(measuredFps.in(fps)); // "66.66666666666667 fps" ``` -------------------------------- ### Derive Quantities for Game Engine (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md Derives more complex quantities like frame rate and velocity from the base units defined for the game engine. It showcases how to combine base measures to create expressive quantity types. ```typescript import { Measure } from "@safe-units/utils"; // Assuming Length, Time, and Frames are defined as in the previous example const FrameRate = Measure.dimension("fr/ms"); type FrameRate = typeof FrameRate; const Velocity = Measure.dimension("eu/ms"); type Velocity = typeof Velocity; ``` -------------------------------- ### Define Base Units for Game Engine (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md Establishes the base units for the game engine's unit system, specifically for length, time, and frames. It demonstrates creating measures and assigning them to quantity types for expressive code. ```typescript import { Measure } from "@safe-units/utils"; const engineUnits = Measure.dimension("eu"); const milliseconds = Measure.dimension("ms"); const frames = Measure.dimension("fr"); const Length = engineUnits; type Length = typeof Length; const Time = milliseconds; type Time = typeof Time; const Frames = frames; type Frames = typeof Frames; ``` -------------------------------- ### Create Generic Velocity Quantity (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md Demonstrates creating a generic quantity type, 'Velocity', that can operate on different numeric types like standard numbers or arbitrary-precision numbers (BigNumber). This is achieved using the LiftMeasure type. ```typescript import { Measure, LiftMeasure } from "@safe-units/utils"; // Assume BigNumber is a custom arbitrary-precision number type // declare class BigNumber { ... } const milliseconds = Measure.dimension("ms"); const engineUnits = Measure.dimension("eu"); // Generic Velocity quantity using LiftMeasure const Velocity = LiftMeasure.dimension<"eu", "ms", number, BigNumber>("eu/ms"); type Velocity = typeof Velocity; // Example usage: const speed: Velocity = Measure.of(10, engineUnits.per(milliseconds)); // speed is of type Velocity // const bigSpeed: Velocity = Measure.of(new BigNumber(100), engineUnits.per(milliseconds)); // bigSpeed is of type Velocity ``` -------------------------------- ### Create Basic Measurements in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Demonstrates creating basic measurements using `Measure.of()` by combining numeric values with unit definitions. It shows how to log the string representation and extract the numeric value from a measurement. Dependencies include `Measure`, `meters`, `seconds`, and `kilograms` from the 'safe-units' library. ```typescript import { Measure, meters, seconds, kilograms } from "safe-units"; // Create basic measurements const distance = Measure.of(100, meters); const time = Measure.of(10, seconds); const mass = Measure.of(50, kilograms); console.log(distance.toString()); // "100 m" console.log(time.toString()); // "10 s" console.log(mass.toString()); // "50 kg" // Extract numeric values console.log(distance.value); // 100 console.log(time.value); // 10 ``` -------------------------------- ### Compare Measurements with Same Units in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Illustrates how to compare measurements that share the same unit using standard comparison operators like less than, greater than, and equal to. It also shows unit conversion for comparison and the `compare` method for ordered results. ```typescript import { Measure, meters, pascals, bars, milli } from "safe-units"; // Length comparison const height1 = Measure.of(10, meters); const height2 = Measure.of(15, meters); console.log(height1.lt(height2)); // true (less than) console.log(height1.lte(height2)); // true (less than or equal) console.log(height1.eq(height2)); // false (equal) console.log(height1.neq(height2)); // true (not equal) console.log(height1.gte(height2)); // false (greater than or equal) console.log(height1.gt(height2)); // false (greater than) // Pressure comparison with unit conversion const pressure1 = Measure.of(49, pascals); const pressure2 = Measure.of(0.5, milli(bars)); console.log(pressure1.lt(pressure2)); // true // Direct comparison const result = height1.compare(height2); // negative value (height1 < height2) ``` -------------------------------- ### Apply Metric Prefixes to Units in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Demonstrates how to apply metric prefixes (like kilo, milli, micro) to base units such as meters, grams, seconds, and watts using the Measure.of() function. It shows how to represent scaled measurements and convert them back to base units. ```typescript import { Measure, meters, grams, seconds, watts, mega, kilo, milli, micro } from "safe-units"; // Length with prefixes const distance1 = Measure.of(5, kilo(meters)); console.log(distance1.toString()); // "5 km" console.log(distance1.in(meters)); // "5000 m" const distance2 = Measure.of(500, milli(meters)); console.log(distance2.in(meters)); // "0.5 m" // Mass with prefixes const weight = Measure.of(250, micro(grams)); console.log(weight.toString()); // "250 µg" // Power with prefixes const power = Measure.of(2.5, mega(watts)); console.log(power.toString()); // "2.5 MW" console.log(power.in(watts)); // "2500000 W" // Combine prefixes with derived units const time = Measure.of(100, milli(seconds)); const speed = Measure.of(50, meters).over(time); console.log(speed.toString()); // "500 m * s^-1" ``` -------------------------------- ### Use Predefined SI Quantities in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Demonstrates the usage of extensive predefined physical quantities based on SI units, including Force, Pressure, Energy, and Power. It shows how to create measurements for these quantities and convert them to their standard SI units like Newtons, Pascals, Joules, and Watts. ```typescript import { Measure, Force, Pressure, Energy, Power, newtons, pascals, joules, watts, kilograms, meters, seconds } from "safe-units"; // Force (newtons) const mass = Measure.of(10, kilograms); const acceleration = Measure.of(9.8, meters.per(seconds.squared())); const force: Force = mass.times(acceleration); console.log(force.in(newtons)); // "98 N" // Pressure (pascals) const area = Measure.of(2, meters.squared()); const pressure: Pressure = force.over(area); console.log(pressure.in(pascals)); // "49 Pa" // Energy (joules) const distance = Measure.of(5, meters); const energy: Energy = force.times(distance); console.log(energy.in(joules)); // "490 J" // Power (watts) const time = Measure.of(2, seconds); const power: Power = energy.over(time); console.log(power.in(watts)); // "245 W" ``` -------------------------------- ### Defining Custom Unit Systems in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Illustrates how to define a completely new unit system (e.g., for game development with 'frames' and 'time') and create custom dimensions and measures within it. It shows defining a FrameRate quantity and comparing calculated frame rates against a minimum threshold. Requires importing `Measure` and `UnitSystem`. ```typescript import { Measure, UnitSystem } from "safe-units"; const GameUnitSystem = UnitSystem.from({ frames: "fr", time: "s", }); const frames = Measure.dimension(GameUnitSystem, "frames"); const seconds = Measure.dimension(GameUnitSystem, "time"); const Frames = frames; type Frames = typeof frames; const Time = seconds; type Time = typeof seconds; const FrameRate = Frames.over(Time); type FrameRate = typeof FrameRate; const fps: FrameRate = frames.per(seconds).withSymbol("fps"); const minFrameRate = Measure.of(60, fps); const measuredFrames = Measure.of(8000, frames); const elapsedTime = Measure.of(120, seconds); const measuredFps: FrameRate = measuredFrames.over(elapsedTime); if (measuredFps.lt(minFrameRate)) { // Optimize } ``` -------------------------------- ### Basic Unit Measurement and Arithmetic in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Demonstrates creating basic measurements for length and time, performing arithmetic operations like division to derive velocity, and showcasing type safety by preventing invalid unit combinations. It requires importing `Measure`, `meters`, `seconds`, `Length`, `Time`, and `Velocity` from 'safe-units'. ```typescript import { Length, Measure, meters, seconds, Time, Velocity } from "safe-units"; const length: Length = Measure.of(30, meters); const time: Time = Measure.of(15, seconds); const velocity: Velocity = length.over(time); console.log(length.toString()); // 30 m console.log(time.toString()); // 15 s console.log(velocity.toString()); // 2 m * s^-1 // @ts-expect-error ERROR: A measure of m*s isn't assignable to a measure of m/s. const error: Velocity = length.times(time); ``` -------------------------------- ### Derive Custom Quantity Types from Base Units in TypeScript Source: https://context7.com/jscheiny/safe-units/llms.txt Shows how to create custom derived quantity types, such as VolumeDensity, by combining base units using the `over` operator. It demonstrates calculating and using these custom types in further measurements and calculations. ```typescript import { kilograms, liters, Mass, Measure, Volume } from "safe-units"; // Define volume density type const VolumeDensity = Mass.over(Volume); type VolumeDensity = typeof VolumeDensity; // Calculate density const mass = Measure.of(30, kilograms); const volume = Measure.of(3, liters); const density: VolumeDensity = mass.over(volume); console.log(density.toString()); // "10 kg * m^-3" // Use derived quantity in calculations const newVolume = Measure.of(5, liters); const expectedMass = density.times(newVolume); console.log(expectedMass.toString()); // Type is Mass // Create named derived unit const kgPerLiter = kilograms.per(liters).withSymbol("kg/L"); const density2 = Measure.of(1.2, kgPerLiter); console.log(density2.toString()); // "1.2 kg/L" ``` -------------------------------- ### Comparison Methods for Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Allows for comparison of two measures of the same unit. Methods include less than (`lt`), less than or equal to (`lte`), equal to (`eq`), not equal to (`neq`), greater than or equal to (`gte`), and greater than (`gt`). Comparing measures with different units results in a compile-time error. ```typescript Measure.lt(other: Measure): boolean; Measure.lte(other: Measure): boolean; Measure.eq(other: Measure): boolean; Measure.neq(other: Measure): boolean; Measure.gte(other: Measure): boolean; Measure.gt(other: Measure): boolean; ``` -------------------------------- ### Define Derived Units for Game Engine (TypeScript) Source: https://github.com/jscheiny/safe-units/blob/master/docs/unit-systems.md Defines specific units within the derived quantities for the game engine, such as kilometers per hour or miles per hour. This builds upon the previously derived quantities. ```typescript import { Unit } from "@safe-units/utils"; // Assuming FrameRate and Velocity are defined as in the previous example const Kph = Unit.of("kph"); const Mph = Unit.of("mph"); // Example of defining a unit for FrameRate (though less common) const Fps = Unit.of("fps"); ``` -------------------------------- ### Custom Unit Naming and Conversion in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Shows how to create custom unit names (aliases) and perform conversions between them, such as furlongs to miles and vice versa. It also demonstrates creating complex derived units with custom symbols and performing calculations with them, like speed of light. Requires importing `Measure` and specific units. ```typescript import { days, Measure, mega, micro, miles, speedOfLight, yards } from "safe-units"; const furlongs = Measure.of(220, yards, "fur"); Measure.of(8, furlongs).in(miles); // "1 mi" Measure.of(1, miles).in(furlongs); // "8 fur" const fortnights = Measure.of(14, days, "ftn"); const megafurlong = mega(furlongs); const microfortnight = micro(fortnights); const mfPerUFtn = megafurlong.per(microfortnight).withSymbol("Mfur/µftn"); speedOfLight.in(mfPerUFtn); // "1.8026174997852542 Mfur/µftn" ``` -------------------------------- ### Unsafe Value and Unit Mapping for Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Provides methods for mapping the value or both value and unit of a measure. `unsafeMap` with one argument maps only the value. With two arguments, it maps both value and unit. These methods are intended for internal use and should be avoided in favor of function wrappers. ```typescript Measure.unsafeMap(valueMap: (value: number) => number): Measure; Measure.unsafeMap( valueMap: (value: number) => number, unitMap: (unit: U) => V, ): Measure; ``` -------------------------------- ### Trigonometry Functions for Angle Conversions in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/docs/builtin.md This code snippet illustrates the trigonometry functions available in the `Trig` namespace of the Safe Units library. These functions are used for converting between plane angles and dimensionless values, including standard trigonometric operations and `atan2` for quadrant-aware angle calculation. ```typescript import { Trig } from "safe-units"; import { PlaneAngle, Dimensionless, Length, Meters } from "safe-units/dist/types"; // Example conversions const angle: PlaneAngle = new PlaneAngle(Math.PI / 4); // 45 degrees const dimensionlessValue: Dimensionless = Trig.sin(angle); console.log(dimensionlessValue.toString()); // Output: "0.707..." const anotherDimensionless: Dimensionless = new Dimensionless(0.5); const calculatedAngle: PlaneAngle = Trig.asin(anotherDimensionless); console.log(calculatedAngle.toString()); // Output: "0.523... rad" // Using atan2 for angle calculation const yLength: Length = new Meters(3); const xLength: Length = new Meters(4); const angleFromXY: PlaneAngle = Trig.atan2(yLength, xLength); console.log(angleFromXY.toString()); // Output: "0.643... rad" ``` -------------------------------- ### Deriving Quantities in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Demonstrates how to derive new quantities by defining their dimensional relationship, such as VolumeDensity derived from Mass and Volume. It shows creating a type alias for the derived quantity and then calculating an instance of it. Requires importing `Measure`, `Mass`, `Volume`, `kilograms`, and `liters`. ```typescript import { kilograms, liters, Mass, Measure, Volume } from "safe-units"; const VolumeDensity = Mass.over(Volume); type VolumeDensity = typeof VolumeDensity; const mass = Measure.of(30, kilograms); const volume = Measure.of(3, liters); const density: VolumeDensity = mass.over(volume); console.log(density.toString()); // 10 kg * m^-3 ``` -------------------------------- ### Applying Prefixes with Measure.prefix Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Generates a function that applies a unit prefix and a multiplier to a Measure. This is helpful for creating prefixed units like kilometers or milliseconds from base units. ```typescript Measure.prefix(prefix: string, multiplier: number): PrefixFn ``` -------------------------------- ### Converting Measures Between Units Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Allows displaying or representing a measure in terms of another measure of the same unit. The `in` method returns a formatted string with optional custom formatting, while `valueIn` returns only the numeric value, sacrificing type safety. ```typescript Measure.in(unit: Measure, formatter?: MeasureFormatter): string; Measure.valueIn(unit: Measure): number; ``` -------------------------------- ### Formatting Measures to Strings Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Converts a measure to its string representation, ignoring symbol information. Optionally accepts a `MeasureFormatter` object to customize value and unit formatting. The `formatUnit` function is used only if the target unit has no symbol during `Measure.in` calls. ```typescript Measure.toString(formatter?: MeasureFormatter): string; interface MeasureFormatter { formatValue?: (value: number) => string; formatUnit?: (unit: Unit, unitSystem: UnitSystem) => string; } ``` -------------------------------- ### TypeScript: Perform Advanced Unit Manipulations Source: https://context7.com/jscheiny/safe-units/llms.txt Execute advanced unit operations such as squaring, cubing, and calculating reciprocals or inverses of measurements. This enables calculations involving derived units like area, volume, and frequency. ```typescript import { Measure, meters, seconds, kilograms } from "safe-units"; // Squaring const side = Measure.of(5, meters); const area = side.squared(); console.log(area.toString()); // "25 m²" // Cubing const volume = side.cubed(); console.log(volume.toString()); // "125 m³" // Reciprocal const frequency = Measure.of(2, seconds).reciprocal(); console.log(frequency.toString()); // "0.5 s^-1" // Alternative reciprocal syntax const inverted = Measure.of(4, meters).inverse(); console.log(inverted.toString()); // "0.25 m^-1" // Complex unit construction const acceleration = meters.per(seconds.squared()); const force = kilograms.times(acceleration).withSymbol("N"); const work = force.times(meters).withSymbol("J"); console.log(work.toString()); // "1 J" ``` -------------------------------- ### Exponentiation: Squaring and Cubing Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Provides convenience methods to square and cube a measure. Squaring is equivalent to multiplying the unit by itself, and cubing likewise. These operations result in new units representing the squared or cubed form. ```typescript Measure.squared(): Measure> Measure.cubed(): Measure> ``` -------------------------------- ### Static Math Operations on Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Wraps JavaScript's `Math` object methods to operate on measures. Methods like `abs`, `ceil`, `floor`, `round`, `trunc` apply to the measure's value without changing the unit. `hypot` can take multiple measures of the same unit. ```typescript // Examples of static Math methods: // Measure.abs(measure: Measure): Measure // Measure.ceil(measure: Measure): Measure // Measure.floor(measure: Measure): Measure // Measure.fround(measure: Measure): Measure // Measure.round(measure: Measure): Measure // Measure.trunc(measure: Measure): Measure // Measure.hypot(...measures: Measure[]): Measure ``` -------------------------------- ### TypeScript: Create Measures with Custom Numeric Types (BigInt) Source: https://context7.com/jscheiny/safe-units/llms.txt Extend Safe Units to work with custom numeric types like BigInt by defining numeric operations. This allows for arbitrary precision in measurements, beyond standard JavaScript number limitations. ```typescript import { GenericMeasure, NumericOperations, createMeasureType, UnitSystem } from "safe-units"; // Define BigInt numeric operations const bigIntOps: NumericOperations = { one: () => 1n, neg: (x) => -x, add: (x, y) => x + y, sub: (x, y) => x - y, mult: (x, y) => x * y, div: (x, y) => x / y, reciprocal: (x) => 1n / x, compare: (x, y) => Number(x - y), format: (x) => x.toString(), }; // Create BigInt measure type const BigIntMeasure = createMeasureType(bigIntOps); // Define unit system const CustomSystem = UnitSystem.from({ length: "m", time: "s", }); // Create units const meters = BigIntMeasure.dimension(CustomSystem, "length"); const seconds = BigIntMeasure.dimension(CustomSystem, "time"); // Use with BigInt values const distance = BigIntMeasure.of(1000n, meters); const time = BigIntMeasure.of(10n, seconds); const velocity = distance.over(time); console.log(velocity.toString()); // "100 m * s^-1" ``` -------------------------------- ### Adding Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Adds two Measures together, returning a new Measure with the same unit. Measures can only be added if they share the same unit. `Measure.add` is an alias for the instance method `plus`. ```typescript // Instance method Measure.plus(other: Measure): Measure // Static functions Measure.add(left: Measure, right: Measure): Measure Measure.sum(first: Measure, ...rest: Array>): Measure ``` -------------------------------- ### TypeScript: Perform Math Operations on Measures Source: https://context7.com/jscheiny/safe-units/llms.txt Apply mathematical functions like absolute value, rounding (ceil, floor, round, trunc), hypotenuse, scaling, and negation to measurements while preserving their units. This ensures dimensional consistency in calculations. ```typescript import { Measure, meters, seconds } from "safe-units"; // Absolute value const velocity = Measure.of(-15, meters.per(seconds)); const speed = Measure.abs(velocity); console.log(speed.toString()); // "15 m * s^-1" // Rounding operations const length = Measure.of(10.7, meters); console.log(Measure.ceil(length).toString()); // "11 m" console.log(Measure.floor(length).toString()); // "10 m" console.log(Measure.round(length).toString()); // "11 m" console.log(Measure.trunc(length).toString()); // "10 m" // Hypotenuse calculation const width = Measure.of(3, meters); const height = Measure.of(4, meters); const diagonal = Measure.hypot(width, height); console.log(diagonal.toString()); // "5 m" // Scaling const distance = Measure.of(100, meters); const scaled = distance.scale(0.5); console.log(scaled.toString()); // "50 m" // Negation const negated = distance.negate(); console.log(negated.toString()); // "-100 m" ``` -------------------------------- ### Type Error Demonstrations in TypeScript Source: https://github.com/jscheiny/safe-units/blob/master/README.md Highlights compile-time type errors in Safe Units, demonstrating that measures of different units cannot be added, compared, or assigned to incompatible types. It shows expected error messages for operations involving incompatible units like length and time, or velocity and force. Requires importing relevant unit types and `Measure`. ```typescript import { Force, hours, Length, Measure, meters, seconds, Time } from "safe-units"; const length: Length = Measure.of(10, meters); const time: Time = Measure.of(10, seconds); // @ts-expect-error - Measures of different units cannot be added length.plus(time); // @ts-expect-error - Measures of different units cannot be compared length.eq(time); // @ts-expect-error - Measure of m/s is not assigneable to measure of kg*m/s^2 const force: Force = length.over(time); // @ts-expect-error - Cannot convert length measure to time measure length.in(hours); ``` -------------------------------- ### Reciprocal and Inverse Operations for Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Computes the reciprocal of a measure's value and unit. Both `reciprocal` and `inverse` methods are identical and return a measure with the unit inverted. ```typescript Measure.reciprocal(): Measure> Measure.inverse(): Measure> ``` -------------------------------- ### Constructing Measures with Measure.of Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Creates a new Measure instance that is a scalar multiple of a given Measure. An optional symbol can be provided for the resulting measure. This is useful for creating derived measures from existing ones. ```typescript Measure.of( value: number, quantity: Measure, symbol?: string, ): Measure ``` -------------------------------- ### Creating Dimensionless Measures with Measure.dimensionless Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Constructs a Measure representing a dimensionless value within a specified unit system. This is used for ratios or pure numbers that do not have a specific physical unit. ```typescript Measure.dimensionless( unitSystem: UnitSystem, value: number, ): Measure> ``` -------------------------------- ### Dividing Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Divides one Measure by another, returning a new Measure. The resulting unit is determined at compile time by dividing the units of the input Measures. Multiple methods are provided for readability. ```typescript // Instance methods Measure.div(other: Measure): Measure> Measure.over(other: Measure): Measure> Measure.per(other: Measure): Measure> // Static function Measure.divide( left: Measure, right: Measure, ): Measure> ``` -------------------------------- ### Constructing Dimension Measures with Measure.dimension Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Builds a Measure representing a single dimension within a unit system. The resulting measure is initialized to 1 of the base unit for that dimension, useful for defining base quantities. ```typescript Measure.dimension( unitSystem: UnitSystem, dimension: D, symbol?: string, ): Measure<...> ``` -------------------------------- ### Adding Symbols to Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Duplicates a measure and assigns it a specific symbol. This symbol is instance-specific and does not propagate through operations. It's equivalent to `Measure.of(1, measure, symbol)` and can be accessed via the `symbol` field. ```typescript Measure.withSymbol(symbol: string): Measure ``` -------------------------------- ### Multiplying Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Multiplies two Measures together, producing a new Measure. The unit of the resulting Measure is a compile-time computation based on the multiplication of the input units. ```typescript // Instance method Measure.times(other: Measure): Measure> // Static function Measure.multiply( left: Measure, right: Measure, ): Measure> ``` -------------------------------- ### Negating Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Returns a new Measure instance with the negated value of the original Measure. This operation does not change the unit of the Measure. ```typescript Measure.negate(): Measure ``` -------------------------------- ### Checking for Measure Instances with Measure.isMeasure Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md A utility function to safely determine if a given value is an instance of a Measure. Since Measure might not be a traditional class, `instanceof` checks may not work reliably. ```typescript Measure.isMeasure(value: any): value is Measure ``` -------------------------------- ### Scalar Multiplication for Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Scales a measure by multiplying its value with a dimensionless number. This is a convenience method for simple scaling operations. ```typescript Measure.scale(value: number): Measure ``` -------------------------------- ### Subtracting Measures Source: https://github.com/jscheiny/safe-units/blob/master/docs/measures.md Subtracts one Measure from another, returning a new Measure with the same unit. Similar to addition, subtraction is only allowed between Measures with identical units. ```typescript // Instance method Measure.minus(other: Measure): Measure // Static function Measure.subtract(left: Measure, right: Measure): Measure ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.