All files / utils template.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 2/2
100% Lines 15/15

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                                    4x   9x       9x   1x   1x     8x       8x         8x     7x   7x     6x     7x       1x       8x   8x  
export interface TemplateResult {
    /**
     * The text resulting from replacing the placeholders that match the name of the data members
     * with the value of those data members
     */
    text?: string;
 
    /**
     * The array with the name of the data members whose names did not match the ones in the placeholders
     */
    keysNotInData: string[];
}
 
/**
 * Replaces any placeholders "{{name}}" with the value of the data property that matches that name
 * @param text
 * @param data
 */
export default function template(text: string, data?: any): TemplateResult {
 
    const result: TemplateResult = {
        keysNotInData: []
    };
 
    if (!data) {
 
        result.text = text;
 
        return result; // Nothing to replace in the template, return the original text
    }
 
    result.keysNotInData = Object.keys(data); // Assume there hasn't been a match so far
 
    function processMatch(match: string, offset: number, str: string) {
 
        const key = match
            .replace('{{', '')
            .replace('}}', '')
            .trim(); // Remove the {{ }} around the match
 
        if (data.hasOwnProperty(key)) {
 
            // Remove the "non matched" data member key
            const index: number = result.keysNotInData.indexOf(key);
 
            if (index > -1) {
                // Not removed already
 
                result.keysNotInData.splice(index, 1);
            }
 
            return data[key];
        }
        else {
 
            return match;
        }
    }
 
    result.text = text.replace(/\{{\S+?\}}/g, processMatch);
 
    return result;
}