All files / src/custom-element/helpers oneOf.ts

92.59% Statements 25/27
86.11% Branches 31/36
100% Functions 3/3
92.59% Lines 25/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 9016x   16x     83x         62x             62x       9x   9x   9x                 53x           50x   50x       20x               50x   30x     1x     29x     1x     28x       23x   2x     21x   1x     20x       16x   83x  
import getGlobalFunction from "./getGlobalFunction"
 
export class OneOf {
 
    constructor(
        public types: Function[]
    ) { }
 
    toProperty(value: any) {
 
        Iif (value === null &&
            this.types.includes(String)) { // When an attribute gets removed attributeChangedCallback gives the value of null
 
            return '';
        }
 
        // First try a function since that can create any of the objects below
        if (value !== null &&
            value[value.length - 2] === '(' && value[value.length - 1] === ')' // The function by convention must end in ()
            && this.types.includes(Function)) {
 
            var fcn = getGlobalFunction(value);
 
            Eif (fcn !== undefined) {
 
                return fcn;
            }
        }
 
        // if (this.types.includes(ElementNode)) {
 
        //     return createVirtualNode(value);
        // }
 
        if (this.types.includes(Object) ||
            this.types.includes(Array)
        ) {
 
            let o;
 
            try {
 
                o = JSON.parse(value);
            }
            catch (error) {
 
                Iif (!this.types.includes(String)) {
 
                    throw error; // Malformed JSON
                }
 
                // Try the other types below
            }
 
            if (o !== undefined) {
 
                if (!Array.isArray(o) &&
                    !this.types.includes(Object)) {
 
                    throw Error(`value: ${value} is not an array but there is no object type expected`);
                }
 
                if (Array.isArray(o) &&
                    !this.types.includes(Array)) {
 
                    throw Error(`value: ${value} is an array but there is no array type expected`);
                }
 
                return o;
            }
        }
 
        if (this.types.includes(Boolean)) {
 
            return value !== null && value !== 'false';
        }
 
        if (this.types.includes(Number)) {
 
            return value === null ? null : Number(value);
        }
 
        return value;
    }
}
 
export default function oneOf(...types) {
 
    return new OneOf(types);
}