all files / src/color-expression-converter/parts/ hex.js

64.06% Statements 41/64
78.38% Branches 29/37
80% Functions 8/10
20.69% Lines 6/29
4 statements, 13 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                                                                                              
import { Color } from "./color";
import { ExpressionType } from "./expression-type";
 
/**
 * ヘックス表現に関連する処理を提供します。
 */
class Hex extends ExpressionType {
    toColor (expression) {
        try{
            let ret = new Color();
            ret.origin = expression;
 
            expression = expression.trim();
 
            if(expression.length == 4){
                expression = expression[0] +
                             expression[1] + expression[1] +
                             expression[2] + expression[2] +
                             expression[3] + expression[3];
            }
 
            ret.red   = parseInt(expression.substring(1, 3), 16);
            ret.green = parseInt(expression.substring(3, 5), 16);
            ret.blue  = parseInt(expression.substring(5, 7), 16);
            ret.alpha = 1;
            if(expression.length == 9){
                // TODO 要仕様確認
            }
 
            return ret;
        }catch(ex){
            throw ex;
        }
    }
 
    createColorExpression (color) {
        try{
            let red   = color.red.toString(16).padStart(2, "0");
            let green = color.green.toString(16).padStart(2, "0");
            let blue  = color.blue.toString(16).padStart(2, "0");
 
            let alpha = color.alpha;
            if(0 < alpha && alpah < 1){
                alpha = alpha.toString(16).padStart(2, "0");
            }else{
                alpha = "";
            }
 
            return `#${red}${green}${blue}${alpha}`;
        }catch(ex){
            throw ex;
        }
    }
}
 
// シングルトンとして提供
const instance = new Hex();
export { instance as Hex };