Skip to content

Instantly share code, notes, and snippets.

@jquintozamora
Last active February 4, 2019 16:23
Show Gist options
  • Save jquintozamora/22c4881a63f7920e2d884e47bd25ae2e to your computer and use it in GitHub Desktop.
Save jquintozamora/22c4881a63f7920e2d884e47bd25ae2e to your computer and use it in GitHub Desktop.
/**
* Gives a numeric range
*
* @param {number} start - initial number
* @param {number} stop - final number
* @param {number} step - increment value
* @returns {Array} numeric range between start and stop by increments of step
*
* Example: numericRange(-2, 2, 1) = numericRange(-2, 2) => [-2, -1, 0, 1, 2]
*/
function getNumericRange(start, stop, step = 1) {
return Array.from({ length: Math.ceil((stop + 1 - start) / step) }, (_, i) => start + i * step);
}
/**
* TESTS
**/
describe('getNumericRange', () => {
it('should return array of 5 elements from -2 to 2', () => {
const newArray = helpers.getNumericRange(-2, 2);
const expectedArray = [-2, -1, 0, 1, 2];
expect(newArray).to.deep.equal(expectedArray);
});
it('should return array of 5 elements from -4 to 4 with step 2', () => {
const newArray = helpers.getNumericRange(-4, 4, 2);
const expectedArray = [-4, -2, 0, 2, 4];
expect(newArray).to.deep.equal(expectedArray);
});
it('should return array of 10 elements from 0 to 10', () => {
const newArray = helpers.getNumericRange(0, 10, 1);
const expectedArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
expect(newArray).to.deep.equal(expectedArray);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment