all files / src/creator/ hex3-creator.js

100% Statements 62/62
100% Branches 20/20
100% Functions 14/14
100% Lines 16/16
9 statements, 8 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                       112× 21× 315× 315× 315× 315× 37×     21×       21× 21×        
import { Color } from "../color";
 
/**
 * 3桁の16進数表現の作成処理を提供します。
 */
class Hex3Creator {
    /**
     * 色表現を作成します。
     * @param {Color} color 生成元の色情報。
     * @return {String} 色表現。
     */
    create(color) {
        // 利用可能な近似値の算出
        const available = [...Array(16).keys()].map(x => x.toString(16)).map(x => parseInt(String(x).repeat(2), 16));
        const approximation = value => {
            let match = available[0];
            for (const v of available.slice(1)) {
                const currentDistance = Math.abs(match - value);
                const distance = Math.abs(v - value);
                if (currentDistance > distance) {
                    match = v;
                }
            }
            return match;
        };
 
        // 色表現を生成
        const hex = x => (Number(x).toString(16)).slice(0, 1);
        const rgb = [ color.r, color.g, color.b ].map(x => approximation(x)).map(x => hex(x));
        return `#${rgb.join("")}`;
    }
}
 
export { Hex3Creator };