import { isNil, isNumber } from 'lodash';

export function Sanitize(context: string, html = true, unicode = true): string {
    if (isNil(context) || isNumber(context) || typeof context !== 'string') {
        return context;
    }

    if (html) {
        const tagsToReplace: { [tag: string]: string } = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;',
        };

        context = String(context).replace(/[<>"']/g, (tag) => {
            return tagsToReplace[tag] || tag;
        });
    }

    if (unicode) {
        const unicodeRegex = /[^\u0020-\u007E\u2014\u00A9\u00AE\u2122\n\r]/g;
        context = String(context).replace(unicodeRegex, '');
    }

    return context;
}
