
linspace-generator
LinspaceGenerator is a dependency-less generator of a linearly spaced vector of numbers.
It is inspired by MATLAB's linspace.
Installing
npm install --save linspace-generator
yarn add linspace-generator
Typings
This package is written in TypeScript.
The following types are declared and exported:
export declare type LinspaceAsArray = (x1: number, x2: number, n?: number) => number[];
export declare function linspaceGenerator(x1: number, x2: number, n?: number): IterableIterator<number>;
export declare const linspaceAsArray: LinspaceAsArray;
How to import
Depending on your application, you might want to only either import the generator itself, or the
thin wrapper that converts the generator function into an array.
import { linspaceGenerator } from 'linspace-generator';
import { linspaceAsArray } from 'linspace-generator';
Usage
Just take a look at the signature of the method:
function* linspaceGenerator(x1: number, x2: number, n: number = 100): IterableIterator<number>;
const linspaceAsArray = (x1: number, x2: number, n?: number) => number[];
For a reminder of how Generator Functions work, please refer to the official documentation.
Example
Consider the case in which you need to create 6 equally spaced numbers in the interval [0,1].
The desired result will have the following shape (with indexes in the upper row, and values in the bottom row).
The situation above translates to the following code:
const arr: number[];
const getter = linspaceGenerator(0, 1, 6);
let result: IteratorResult<number>;
while (!(result = getter.next()).done) {
arr.push(result.value);
}
console.log(arr);
Or, if you need to utilize the array directly:
const arr: number[] = linspaceAsArray(0, 1, 6);
console.log(arr);
Note that if the number n of points to generate is 1, linspace returns the last point of the interval x2.
Also, if n <= 0, linspaceGenerator doesn't yield anything, and linspaceAsArray returns [].
Please take a look at the tests to check out every possible nuance and other example of using this package.
Related packages
- fixed-math: utility function that converts a decimal number using fixed-point notation,
without using the expensive Number.toFixed
- is-equally-spaced: utility function that given an array of numbers, evaluates wether or not every element is equally spaced, i.e. if every subsequent couple of numbers in the array has the same distance.
Contributing
Of course PRs are welcome! Before contributing, however, please be sure to run npm run test:ci or yarn test:ci,
in order to check if the code you wrote respects the linting conventions and if it doesn't break any test. Please
try to keep the unit test code coverage at 100%.