Skip to content

Instantly share code, notes, and snippets.

@gpiffault
Last active April 27, 2024 16:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpiffault/10556503 to your computer and use it in GitHub Desktop.
Save gpiffault/10556503 to your computer and use it in GitHub Desktop.
Javascript piecewise function factory
function Piecewise(xs, ys) {
return function(x) {
//bisect
var lo = 0, hi = xs.length - 1;
while (hi - lo > 1) {
var mid = (lo + hi) >> 1;
if (x < xs[mid]) hi = mid;
else lo = mid;
}
//project
return ys[lo] + (ys[hi] - ys[lo]) / (xs[hi] - xs[lo]) * (x - xs[lo]);
};
}
@gontard
Copy link

gontard commented Nov 16, 2017

Nice, It could be a small npm module.

@gpiffault
Copy link
Author

@gontard
Copy link

gontard commented Jun 1, 2018

Thanks, i will use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment