Infer sign of range's step when only end is provided.

This commit is contained in:
John-David Dalton
2015-11-25 16:24:47 -07:00
parent 6289211910
commit 70c3d325a0
2 changed files with 17 additions and 5 deletions

View File

@@ -13220,9 +13220,10 @@
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. If `end` is not specified it's
* set to `start` with `start` then set to `0`. If `end` is less than `start`
* a zero-length range is created unless a negative `step` is specified.
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified
* it's set to `start` with `start` then set to `0`. If `end` is less than
* `start` a zero-length range is created unless a negative `step` is specified.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
@@ -13239,6 +13240,9 @@
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
@@ -13260,14 +13264,16 @@
}
start = toNumber(start);
start = start === start ? start : 0;
step = step === undefined ? 1 : (toNumber(step) || 0);
if (end === undefined) {
end = start;
start = 0;
step = step === undefined ? (start < end ? 1 : -1) : step;
} else {
end = toNumber(end) || 0;
}
step = step === undefined ? 1 : (toNumber(step) || 0);
var n = nativeMax(nativeCeil((end - start) / (step || 1)), 0);
return baseTimes(n, function(index) {
return index ? (start += step) : start;

View File

@@ -15555,12 +15555,18 @@
QUnit.module('lodash.range');
(function() {
QUnit.test('should work with an `end` argument', function(assert) {
QUnit.test('should work with only an `end` argument', function(assert) {
assert.expect(1);
assert.deepEqual(_.range(4), [0, 1, 2, 3]);
});
QUnit.test('should use a `step` of `-1` when provided only a negative `end` argument', function(assert) {
assert.expect(1);
assert.deepEqual(_.range(-4), [0, -1, -2, -3]);
});
QUnit.test('should work with `start` and `end` arguments', function(assert) {
assert.expect(1);