All files / ethers.js/src.ts/utils properties.ts

100% Statements 60/60
100% Branches 20/20
100% Functions 3/3
100% Lines 60/60

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 611x 1x 1x 1x 1x 1x 95447x 95447x 95447x 95447x 95447x 1x 95447x 95447x 95447x 95447x 95446x 95447x 95447x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12621x 12621x 12546x 25422x 25422x 12546x 12546x 1x 1x 1x 1x 1x 1x 1x 306335x 306335x 306335x 306335x 306335x 666065x 666065x 666065x 666065x 666064x 666064x 666064x 306334x  
/**
 *  Property helper functions.
 *
 *  @_subsection api/utils:Properties  [about-properties]
 */
 
function checkType(value: any, type: string, name: string): void {
    const types = type.split("|").map(t => t.trim());
    for (let i = 0; i < types.length; i++) {
        switch (type) {
            case "any":
                return;
            case "bigint":
            case "boolean":
            case "number":
            case "string":
                if (typeof(value) === type) { return; }
        }
    }
 
    const error: any = new Error(`invalid value for type ${ type }`);
    error.code = "INVALID_ARGUMENT";
    error.argument = `value.${ name }`;
    error.value = value;
 
    throw error;
}
 
/**
 *  Resolves to a new object that is a copy of %%value%%, but with all
 *  values resolved.
 */
export async function resolveProperties<T>(value: { [ P in keyof T ]: T[P] | Promise<T[P]>}): Promise<T> {
    const keys = Object.keys(value);
    const results = await Promise.all(keys.map((k) => Promise.resolve(value[<keyof T>k])));
    return results.reduce((accum: any, v, index) => {
        accum[keys[index]] = v;
        return accum;
    }, <{ [ P in keyof T]: T[P] }>{ });
}
 
/**
 *  Assigns the %%values%% to %%target%% as read-only values.
 *
 *  It %%types%% is specified, the values are checked.
 */
export function defineProperties<T>(
 target: T,
 values: { [ K in keyof T ]?: T[K] },
 types?: { [ K in keyof T ]?: string }): void {
 
    for (let key in values) {
        let value = values[key];
 
        const type = (types ? types[key]: null);
        if (type) { checkType(value, type, key); }
 
        Object.defineProperty(target, key, { enumerable: true, value, writable: false });
    }
}