diff --git a/README.md b/README.md index 164fc72..434cfa2 100644 --- a/README.md +++ b/README.md @@ -223,3 +223,13 @@ Returns a uniform nonrational B-spline interpolator through the specified array # d3.interpolateBasisClosed(values) [<>](https://github.com/d3/d3-interpolate/blob/master/src/basisClosed.js "Source") Returns a uniform nonrational B-spline interpolator through the specified array of *values*, which must be numbers. The control points are implicitly repeated such that the resulting one-dimensional spline has cyclical C² continuity when repeated around *t* in [0,1]. See also [d3.curveBasisClosed](https://github.com/d3/d3-shape#curveBasisClosed). + +### Piecewise + +# d3.piecewise(interpolate, values) [<>](https://github.com/d3/d3-interpolate/blob/master/src/piecewise.js "Source") + +Returns a piecewise interpolator, composing interpolators for each adjacent pair of *values*. The returned interpolator maps *t* in [0, 1 / (*n* - 1)] to *interpolate*(*values*[0], *values*[1]), *t* in [1 / (*n* - 1), 2 / (*n* - 1)] to *interpolate*(*values*[1], *values*[2]), and so on, where *n* = *values*.length. In effect, this is a lightweight [linear scale](https://github.com/d3/d3-scale/blob/master/README.md#linear-scales). For example, to blend through red, green and blue: + +```js +var interpolate = d3.piecewise(d3.interpolateRgb.gamma(2.2), ["red", "green", "blue"]); +``` diff --git a/index.js b/index.js index f1d1687..d08cb77 100644 --- a/index.js +++ b/index.js @@ -14,4 +14,5 @@ export {default as interpolateHsl, hslLong as interpolateHslLong} from "./src/hs export {default as interpolateLab} from "./src/lab"; export {default as interpolateHcl, hclLong as interpolateHclLong} from "./src/hcl"; export {default as interpolateCubehelix, cubehelixLong as interpolateCubehelixLong} from "./src/cubehelix"; +export {default as piecewise} from "./src/piecewise"; export {default as quantize} from "./src/quantize"; diff --git a/src/piecewise.js b/src/piecewise.js new file mode 100644 index 0000000..41f76ae --- /dev/null +++ b/src/piecewise.js @@ -0,0 +1,8 @@ +export default function piecewise(interpolate, values) { + var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n); + while (i < n) I[i] = interpolate(v, v = values[++i]); + return function(t) { + var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n))); + return I[i](t - i); + }; +}