gka / chroma.js

JavaScript library for all kinds of color manipulations
https://gka.github.io/chroma.js/
Other
10.08k stars 543 forks source link

Constructor modifies input array? #239

Open cneumann opened 4 years ago

cneumann commented 4 years ago

In this snippet:

const inRGB = [140, 140, 140];
const c = new chroma(inRGB);

the input array inRGB is modified, a fourth element with value 1 is added as well as _clipped and _unclipped properties. I'm not sure if that is expected or intended, but I found it surprising and think a warning in the documentation would be good.

A workaround is to spread the input array:

const inRGB = [140, 140, 140];
const c = new chroma(...inRGB);
ryanlavers commented 2 years ago

This was a really annoying one to figure out. Please don't modify arguments unless you really need to (or at least document it) :slightly_smiling_face:

FYI the sneaky modification seems to be in src/io/rgb/index.js:

input.format.rgb = (...args) => {
    const rgba = unpack(args, 'rgba');
    if (rgba[3] === undefined) rgba[3] = 1;
    return rgba;
};

This code may be assuming the return from unpack() is a copy of the args and safe to modify, but in the case of an array it just returns it as-is.