tiny-essentials
Version:
Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.
241 lines (157 loc) โข 7.96 kB
Markdown
# ๐ข simpleMath.mjs
A collection of simple math utilities that make basic calculations a breeze.
## Overview
`simpleMath.mjs` offers a set of essential mathematical functions, from the classic Rule of Three (direct and inverse proportions) to calculating percentages and even determining age based on a birthdate. It's an easy-to-use module for anyone who needs to perform fundamental calculations in JavaScript.
---
## Functions
### ๐ข `ruleOfThree(val1, val2, val3, inverse)`
**Performs a Rule of Three calculation.**
This function calculates a proportional relationship between three values, which is commonly used in mathematical and real-world scenarios.
- **`val1`**: First reference value (numerator in direct proportion, denominator in inverse).
- **`val2`**: Second reference value (denominator in direct proportion, numerator in inverse).
- **`val3`**: Third value (numerator in direct proportion, denominator in inverse).
- **`inverse`**: Set to `true` for inverse proportion, or `false` for direct proportion.
#### Example - Direct Proportion:
```js
ruleOfThree(2, 6, 3, false); // โ 9
```
#### Example - Inverse Proportion:
```js
ruleOfThree(2, 6, 3, true); // โ 4
```
---
### ๐ฏ `getSimplePerc(price, percentage)`
**Calculates the actual value that corresponds to a percentage of a base number.**
Unlike `getPercentage`, which tells how much something represents in percent,
this function tells how much a given percentage *is worth* in actual value.
- **`price`**: The base number to apply the percentage to.
- **`percentage`**: The percentage to calculate from the base.
#### Example:
```js
getSimplePerc(200, 15); // โ 30
```
---
### ๐ `getPercentage(part, total)`
**Calculates how much percent a partial value represents of the total value.**
This function is useful when you want to know what fraction of the total a value is, in percentage form.
- **`part`**: The partial value to compare.
- **`total`**: The total or maximum value.
#### Example:
```js
getPercentage(5, 100); // โ 5
```
---
### ๐ `getAge(timeData, now)`
**Calculates the age based on a birthdate.**
- **`timeData`**: The birthdate. It can be a timestamp, an ISO string, or a `Date` object.
- **`now`**: The current date (`Date` object). If not provided, the current date will be used.
If the `timeData` is not provided or is invalid, the function returns `null`.
#### Example:
```js
getAge('1990-01-01'); // โ 35 (assuming the current year is 2025)
```
---
### ๐ฆ `formatBytes(bytes, decimals, maxUnit)`
Converts a byte value into a human-readable format with the unit and value separated. It allows you to set the number of decimal places and restricts the conversion to a specified maximum unit (optional). ๐
### Parameters:
- `bytes` (number) โก๏ธ **The number of bytes to format.**
Must be a non-negative number.
- `decimals` (number|null) โก๏ธ **The number of decimal places to include in the result.**
Defaults to `2`. If negative, it will be treated as `0`. If `null`, no rounding is applied and the full precision is used.
- `maxUnit` (string|null) โก๏ธ **Optional unit limit.**
If provided, restricts conversion to this unit at most (e.g., `'MB'` prevents conversion to `'GB'` or higher).
Must be one of:
`'Bytes'`, `'KB'`, `'MB'`, `'GB'`, `'TB'`, `'PB'`, `'EB'`, `'ZB'`, `'YB'`.
Defaults to `null`, meaning no restriction.
### Returns:
- **Object** with two properties:
- `unit`: (string|null) โก๏ธ **The unit of the value** (e.g., 'MB', 'GB', etc.).
- `value`: (number|null) โก๏ธ **The formatted byte value.**
If the input is invalid, returns `null` for both.
### Example Usage:
```js
formatBytes(123456789);
// Returns: { unit: 'MB', value: 117.74 }
```
```js
formatBytes(1073741824, 2, 'MB');
// Returns: { unit: 'MB', value: 1024 }
```
```js
formatBytes(10485760);
// Returns: { unit: 'MB', value: 10 }
formatBytes(1073741824);
// Returns: { unit: 'GB', value: 1 }
formatBytes(1073741824, 2, 'MB');
// Returns: { unit: 'MB', value: 1024 }
```
---
### Notes:
* **Formatting:** Converts bytes to the most appropriate unit (from 'Bytes' to 'YB') based on the byte value.
* **Max Unit:** The `maxUnit` parameter allows you to limit the highest unit for conversion. If not provided, it will convert all the way up to 'YB'.
* **Decimals:** The result can be customized with a specified number of decimal places for precision. If `decimals` is `null`, no rounding is applied, and the full precision value is returned.
---
### ๐ข `genFibonacciSeq()` โ Custom Fibonacci Sequence Generator
๐ Flexible, combinable, and vector-friendly!
Generates a customizable Fibonacci-like sequence. You can use simple numbers or even 2D/ND vectors by passing a custom `combiner` function.
```js
genFibonacciSeq({
baseValues: [[0, 1], [1, 1]],
length: 10,
combiner: ([x1, y1], [x2, y2]) => [x1 + x2, y1 + y2]
});
```
#### โ๏ธ Options
* `baseValues` ๐งฌ: Two starting values (default: `[0, 1]`)
* `length` ๐: How many items to generate (default: `10`)
* `combiner` ๐งช: Custom function to generate next value from the last two (default: `(a, b) => a + b`)
#### ๐ง Returns
An array representing the generated sequence.
> ๐ **Beta** โ Still experimental and fun to tweak!
---
### ๐ `compareMarketcap`
Calculates the price change of a stuff when its **market cap changes**.
#### ๐งฉ Function Signature
```js
compareMarketcap(originalMarketCap, circulatingSupply, newMarketCap)
```
#### ๐ฅ Parameters
| Parameter | Type | Description |
| ------------------- | -------- | --------------------------------------------------------------------------- |
| `originalMarketCap` | `number` | ๐ฐ The original market capitalization. Must be a valid, finite number. |
| `circulatingSupply` | `number` | ๐ The circulating supply of the coin. Must be a positive number. |
| `newMarketCap` | `number` | ๐ The new market capitalization. Optional. Must be a valid number if used. |
#### ๐ค Returns
An object with the following fields:
```js
{
originalPrice: number, // ๐ต Price before market cap changed
newPrice: number, // ๐ธ Price after market cap changed (NaN if not provided)
priceChangePercent: number // ๐ Percentage change in price (NaN if newMarketCap not provided)
}
```
#### โ ๏ธ Validation Rules
* Throws a `TypeError` if any of the numeric inputs are not finite numbers.
* Throws an `Error` if `circulatingSupply` is less than or equal to zero.
* If `newMarketCap` is omitted or not a number, `newPrice` and `priceChangePercent` will be `NaN`.
#### ๐ Notes
* Useful for estimating the effect of market cap fluctuations on token price.
* Ideal for financial dashboards, token simulations, or educational tools.
---
### ๐ `calculateMarketcap(originalMarketCap, circulatingSupply)`
Calculates the **unit price** of a coin or token based on its **market capitalization** and **circulating supply**.
This function is commonly used in financial applications to estimate the price per asset unit (e.g., per token or coin).
#### ๐งฎ Formula
```
price = originalMarketCap / circulatingSupply
```
#### ๐ฅ Parameters
| Name | Type | Description |
| ------------------- | -------- | ---------------------------------------------------------- |
| `originalMarketCap` | `number` | The total market capitalization (e.g., in USD) ๐ต. |
| `circulatingSupply` | `number` | The number of tokens or coins currently in circulation ๐ช. |
#### ๐ค Returns
* `number` โ The calculated **unit price** of the asset ๐ข.
#### โ ๏ธ Throws
* `TypeError` โ If either parameter is not a finite number โ.
* `Error` โ If `circulatingSupply` is less than or equal to zero ๐ซ.