The unfortunately-named median-cut.js is the library that powers ColorPal’s palette generation.

I say it’s unfortunately named because it doesn’t implement a pure median-cut algorithm. It’s identical, except that instead of cutting boxes at their median, they are instead cut at the mean. This results in more pleasing color palettes in most cases.

Here’s a comparison:

median-cut vs mean-cut comparison image

If you’re interested in median-cut vs mean-cut, see this post for a technical discussion.

The code is available on GitHub.