Make min optional for _.clamp.

This commit is contained in:
John-David Dalton
2015-10-21 22:10:05 -07:00
parent 3ee2a15cde
commit 14c2747e80
2 changed files with 32 additions and 17 deletions

View File

@@ -10904,7 +10904,7 @@
* @memberOf _
* @category Number
* @param {number} number The number whose value is to be limited.
* @param {number} min The minimum possible value.
* @param {number} [min] The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} A number in the range [min, max].
* @example
@@ -10916,7 +10916,19 @@
* // => 5
*/
function clamp(number, min, max) {
return nativeMin(nativeMax(number, min), max);
if (max === undefined) {
max = min;
min = undefined;
}
if (max !== undefined) {
max = +max;
number = nativeMin(number, max === max ? max : 0);
}
if (min !== undefined) {
min = +min;
number = nativeMax(number, min === min ? min : 0);
}
return number;
}
/**

View File

@@ -2055,7 +2055,7 @@
assert.strictEqual(_.clamp(-5.5, -5.6, 5.6), -5.5);
});
QUnit.test('should not alter positive numbers in range`', function(assert) {
QUnit.test('should not alter positive numbers in range', function(assert) {
assert.expect(3);
assert.strictEqual(_.clamp(4, -5, 5), 4);
@@ -2063,38 +2063,41 @@
assert.strictEqual(_.clamp(4.5, -5.1, 5.2), 4.5);
});
QUnit.test('should not alter positive zero in range', function(assert) {
QUnit.test('should not alter `0` in range', function(assert) {
assert.expect(1);
assert.strictEqual(1 / _.clamp(0, -5, 5), 1 / 0);
assert.strictEqual(1 / _.clamp(0, -5, 5), Infinity);
});
QUnit.test('should clamp to positive zero', function(assert) {
QUnit.test('should clamp to `0`', function(assert) {
assert.expect(1);
assert.strictEqual(1 / _.clamp(-10, 0, 5), 1 / 0);
assert.strictEqual(1 / _.clamp(-10, 0, 5), Infinity);
});
QUnit.test('should not alter negative zero in range', function(assert) {
QUnit.test('should not alter `-0` in range', function(assert) {
assert.expect(1);
assert.strictEqual(1 / _.clamp(-0, -5, 5), 1 / -0);
assert.strictEqual(1 / _.clamp(-0, -5, 5), -Infinity);
});
QUnit.test('should clamp to negative zero', function(assert) {
QUnit.test('should clamp to `-0`', function(assert) {
assert.expect(1);
assert.strictEqual(1 / _.clamp(-10, -0, 5), 1 / -0);
assert.strictEqual(1 / _.clamp(-10, -0, 5), -Infinity);
});
QUnit.test('should return NaN if an argument is or is coerced to NaN', function(assert) {
assert.expect(5);
QUnit.test('should return `NaN` when `number` is `NaN`', function(assert) {
assert.expect(1);
assert.deepEqual(_.clamp(NaN, -5, 5), NaN);
assert.deepEqual(_.clamp(Infinity, -5, NaN), NaN);
assert.deepEqual(_.clamp(-Infinity, -5, NaN), NaN);
assert.deepEqual(_.clamp(Infinity, NaN, 5), NaN);
assert.deepEqual(_.clamp(-Infinity, NaN, 5), NaN);
});
QUnit.test('should coerce `min` and `max` of `NaN` to `0`', function(assert) {
assert.expect(2);
assert.deepEqual(_.clamp(1, -5, NaN), 0);
assert.deepEqual(_.clamp(-1, NaN, 5), 0);
});
}());