import { WarningMessage } from '../types/transformer'; import { DEPRECATION_WARNING_TEMPLATE, DOM_WARNING_TEMPLATE, UNSUPPORTED_WARNING_TEMPLATE, USAGE_PLACEHOLDER, WARN_MESSAGE_TEMPLATE, } from '../constants'; import { APIRule } from '../types/runner'; /** * Generates an unique 22 characters alphanumeric identifier * @returns {string} */ export const generateUID = (): string => { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); }; /** * Performs a deep merge of `source` into `target`. * Mutates `target` only but not its objects and arrays. * @param target Target object into which the source object is merged * @param source Source object that is merged into the target object * @author inspired by [jhildenbiddle](https://stackoverflow.com/a/48218209). */ export const merge = (target: T, source: T): T => { const isObject = (obj: T) => obj && typeof obj === 'object'; if (!isObject(target) || !isObject(source)) { return source; } Object.keys(source as Record).forEach((key) => { const targetValue = (target as Record)[key]; const sourceValue = (source as Record)[key]; if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { (target as Record)[key] = targetValue.concat(sourceValue); } else if (isObject(targetValue) && isObject(sourceValue)) { (target as Record)[key] = merge({ ...targetValue }, sourceValue); } else { (target as Record)[key] = sourceValue; } }); return target; }; /** * Returns the warning text message for a given type * @param type DOM / Deprecation type of warning message * @param usage Code snippet for which the warning message is displayed * @returns Warning message */ export const getWarningText = (type: WarningMessage, usage: string): string => { switch (type) { case WarningMessage.Dom: return DOM_WARNING_TEMPLATE.replace(USAGE_PLACEHOLDER, usage); case WarningMessage.Deprecation: return DEPRECATION_WARNING_TEMPLATE.replace(USAGE_PLACEHOLDER, usage); case WarningMessage.Unsupported: return UNSUPPORTED_WARNING_TEMPLATE.replace(USAGE_PLACEHOLDER, usage); case WarningMessage.Warning: return WARN_MESSAGE_TEMPLATE.replace(USAGE_PLACEHOLDER, usage); default: return ''; } }; /** * Filter and split API Compatibility rules based on type * @param rules List of API Compatibility rules * @param type Type of rule */ export const filterAPIRules = (rules: APIRule[] = [], type: string): APIRule[][] => { return rules.reduce( (acc: APIRule[][], rule: APIRule) => { if (rule.type === type) { acc[0].push(rule); } else { acc[1].push(rule); } return acc; }, [[], []], ); };