Convert

repository·main·Indexed 42 days ago

https://github.com/jonahsnider/convert

A high-performance, type-safe unit conversion library for TypeScript and JavaScript. Version 8.0.2 supports complex conversions, BigInt, and automatic 'best unit' selection across categories such as length, mass, temperature, and time. Key features include the `convert()` function for basic transformations, `convertMany()` for parsing complex unit strings, and the `ms()` utility for millisecond and duration string conversions.

Tokens
4.5K
Snippets
19
Records
27
Agent score
51%

What's inside Convert

  1. Convert to the best unit with 'best'

    main

    When calling .to('best', kind), the library automatically selects the most appropriate unit for the given measurement kind based on the specified system ('metric' or 'imperial').

    • kind: Either 'metric' or 'imperial'.
    • Returns a BestConversion object which includes:
      • quantity: The converted numeric value.
      • unit: The selected unit string.
      • toString(toFixed?: number): A method to get a formatted string representation.
    import convert from 'convert';
    
    // Get the best imperial unit for a distance
    const result = convert(1, 'meter').to('best', 'imperial');
    console.log(result.toString(2)); // e.g., "3.28 ft"
  2. Convert values using convert()

    main

    The convert function is the primary entry point for performing unit conversions. It takes a quantity and a starting unit, returning a Converter object that allows you to transform that value into other units.

    • convert(quantity, from): Returns a Converter instance.
    • Converter.to(unit): Returns the converted value as a primitive (number or bigint).
    • Converter.to('best', kind): Returns a BestConversion object containing the quantity and the most appropriate unit for the specified system ('metric' or 'imperial').
    import convert from 'convert';
    
    // Basic conversion to a specific unit
    const meters = convert(5, 'feet').to('m');
    
    // Conversion to the 'best' unit for a specific system
    const bestMetric = convert(10, 'miles').to('best', 'metric');
    // bestMetric.unit will be the most appropriate metric unit
    // bestMetric.toString() returns a formatted string like "16.09344 km"
  3. Perform basic unit conversions with `convert()`

    main

    Use the convert function to transform a value from one unit to another. The API is type-safe and supports various unit types including length, data, volume, mass, temperature, and duration. It also supports bigint values.

    import convert from "convert";
    
    // Standard conversion
    convert(360, "seconds").to("minutes");
    // -> 6
    
    // BigInt support
    convert(20n, "hours").to("minutes");
    // -> 1200n
    
    // Various unit types
    convert(5, "kilometers").to("nautical miles");
    convert(8192, "bytes").to("KiB");
    convert(451, "fahrenheit").to("celsius");
    import convert from "convert";
    
    // 360 seconds into minutes
    convert(360, "seconds").to("minutes");
    // -> 6
    
    // BigInt support
    convert(20n, "hours").to("minutes");
    // -> 1200n
    
    // Format to the best unit automatically
    convert(5500, "meters").to("best");
    // -> { quantity: 5.5, unit: 'km', toString: () => '5.5 km' }
    
    // You can also do length, data, volume, mass, temperature, and more
    convert(5, "kilometers").to("nautical miles");
    convert(12, "pounds").to("ounces");
    convert(8192, "bytes").to("KiB");
    convert(10, "atmospheres").to("kPa");
    convert(451, "fahrenheit").to("celsius");
  4. Parse unit strings with convertMany()

    main

    Use convertMany(value) to parse a string representation of a quantity and unit into a Converter instance. This is useful for processing user input or data from external sources.

    import { convertMany } from 'convert';
    
    const converter = convertMany('100 km');
    const miles = converter.to('mi');
  5. Handle millisecond conversions with `ms()`

    main

    The ms utility provides a shorthand for converting duration strings to milliseconds or converting millisecond numbers back into human-readable duration strings.

    import { ms } from "convert";
    
    // Convert a duration string into milliseconds
    ms("1d 2h 30min"); // -> 95400000
    
    // Convert milliseconds to a human-readable string
    ms(86400000); // -> '1d'
    import { ms } from "convert";
    
    // Convert a duration into milliseconds
    ms("1d 2h 30min");
    // -> 95400000
    
    // Convert milliseconds to a string
    ms(86400000);
    // -> '1d'
  6. Identify the measurement kind of a unit

    main

    Use getMeasureKind(unit) to determine which category a unit belongs to (e.g., Length, Mass, Time, etc.). You can pass either a valid unit string or a Unit type.

    import { getMeasureKind, MeasureKind } from 'convert';
    
    const kind = getMeasureKind('kg');
    if (kind === MeasureKind.Mass) {
      // handle mass logic
    }
  7. Use `to("best")` to automatically find the most appropriate unit

    main

    When calling .to("best"), Convert returns an object containing the quantity, the unit, and a toString() method. You can optionally specify a unit system as the second argument to to(): either "metric" (default) or "imperial".

    import convert from "convert";
    
    // Convert into the best unit
    const duration = convert(36, "h").to("best");
    // -> { quantity: 1.5, unit: 'd', toString: () => '1.5 d' }
    
    // The toString() method allows automatic casting to string
    "duration is " + duration; 
    // -> "duration is 1.5 d"
    
    // Specify unit system
    convert(3.5, "km").to("best", "metric");   // -> { quantity: 3.5, unit: 'km', ... }
    convert(3.5, "km").to("best", "imperial"); // -> { quantity: 2.17, unit: 'mi', ... }
    import convert from "convert";
    
    // Convert into the best unit
    const duration = convert(36, "h").to("best");
    // -> { quantity: 1.5, unit: 'd', toString: () => '1.5 d' }
    
    // The toString() method means you can automatically cast the object to a string without any issues
    "duration is " + duration;
    // -> duration is 1.5d
    
    // You can also specify to use a specific kind of units (metric or imperial, metric is default)
    convert(3.5, "km").to("best"); // -> { quantity: 3.5, unit: 'km', toString: () => '3.5 km' }
    convert(3.5, "km").to("best", "metric"); // -> { quantity: 3.5, unit: 'km', toString: () => '3.5 km' }
    convert(3.5, "km").to("best", "imperial"); // -> { quantity: 2.17, unit: 'mi', toString: () => '3.5 mi' }
  8. Convert complex unit strings with `convertMany()`

    main

    Use convertMany to parse and convert strings containing multiple unit components (e.g., '1d8h').

    import { convertMany } from "convert";
    
    // Convert 1 day and 8 hours into ms
    convertMany("1d8h").to("ms");
  9. Use the ms shorthand for time

    main

    The ms function provides a convenient way to work with time. It can be used to create a formatted time string or to parse a string into a number of milliseconds.

    import { ms } from 'convert';
    
    // Create a formatted time string
    const timeStr = ms(1500); // "1.5s" (or similar best unit)
    
    // Parse a time string into milliseconds
    const milliseconds = ms('1s'); // 1000
  10. Reference: MeasureKind enum

    main

    The MeasureKind enum defines the different categories of measurements supported by the library.

    export enum MeasureKind {
        Angle = 0,
        Area = 1,
        Data = 2,
        Energy = 3,
        Force = 4,
        Frequency = 5,
        Illuminance = 6,
        Length = 7,
        Luminance = 8,
        LuminousIntensity = 9,
        Mass = 10,
        Power = 11,
        Pressure = 12,
        Temperature = 13,
        Time = 14,
        Volume = 15
    }
  11. Convert values with convert()

    main

    The primary API for converting a single value from one unit to another. It is exported as both convert and the default export.

    To use it, provide the value, the source unit, and the target unit. The function handles the underlying conversion logic based on the MeasureKind of the units provided.

    import convert from 'convert';
    
    // Example usage (assuming units like 'm' and 'ft' are supported)
    const result = convert(10, 'm', 'ft');