All files oneOf.ts

100% Statements 23/23
93.1% Branches 27/29
100% Functions 3/3
100% Lines 23/23

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  1x     1x     9x           9x     1x   1x   1x                 8x           5x   5x             5x   4x     1x     3x     1x     2x       4x   2x     2x   1x     1x       1x   9x  
//import { ElementNode } from "gclib-vdom";
import getGlobalFunction from "./getGlobalFunction"
//import createVirtualNode from "./createVirtualNode";
 
export class OneOf {
 
    constructor(
        public types: Function[]
    ) { }
 
    toProperty(value: any) {
 
        // First try a function since that can create any of the objects below
        if (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) {
 
                // 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);
}