From 32b18eeb991781472eab6a9f69e13bcd779fc9a5 Mon Sep 17 00:00:00 2001 From: David Zukowski Date: Mon, 23 Jan 2017 15:27:23 -0600 Subject: [PATCH] feat(clamp): add function --- .eslintrc | 2 +- src/bundles/index.js | 1 + src/clamp.js | 18 ++++++++++++++++++ tests/clamp.spec.js | 23 +++++++++++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/clamp.js create mode 100644 tests/clamp.spec.js diff --git a/.eslintrc b/.eslintrc index 5655a34..f0af67d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -107,7 +107,7 @@ "no-whitespace-before-property": 2, "no-with": 2, "one-var": 2, - "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }], + "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }], "padded-blocks": [2, "never"], "quotes": [2, "single", "avoid-escape"], "semi": [2, "never"], diff --git a/src/bundles/index.js b/src/bundles/index.js index 445f273..459583d 100644 --- a/src/bundles/index.js +++ b/src/bundles/index.js @@ -5,6 +5,7 @@ export { default as any } from '../any' export { default as append } from '../append' export { default as assoc } from '../assoc' export { default as chain } from '../chain' +export { default as clamp } from '../clamp' export { default as concat } from '../concat' export { default as cond } from '../cond' export { default as contains } from '../contains' diff --git a/src/clamp.js b/src/clamp.js new file mode 100644 index 0000000..fa9ed39 --- /dev/null +++ b/src/clamp.js @@ -0,0 +1,18 @@ +import _curry3 from './internal/_curry3' + +/** + * @name clamp + * @signature Number -> Number -> Number -> Number + * @since v0.18.0 + * @description + * Restricts a value to a given range (inclusive). + * @example + * clamp(1, 10, 5) // => 5 + * clamp(1, 10, -5) // => 1 + * clamp(1, 10, 15) // => 15 + */ +export default _curry3(function clamp (lower, upper, value) { + return value < lower ? lower : + value > upper ? upper : + value +}) diff --git a/tests/clamp.spec.js b/tests/clamp.spec.js new file mode 100644 index 0000000..8ea9148 --- /dev/null +++ b/tests/clamp.spec.js @@ -0,0 +1,23 @@ +const test = require('ava') + , { clamp } = require('../dist/redash') + +test('properly reports its arity (is ternary)', (t) => { + t.is(clamp.length, 3) +}) + +test('is curried', (t) => { + t.is(typeof clamp(1), 'function') + t.is(typeof clamp(1, 10), 'function') +}) + +test('restricts values to the lower bound', (t) => { + t.is(clamp(1, 10, -5), 1) +}) + +test('restricts values to the upper bound', (t) => { + t.is(clamp(1, 10, 15), 10) +}) + +test('allows values between the lower and upper bound', (t) => { + t.is(clamp(1, 10, 5), 5) +})