UNPKG

tiny-types

Version:

A tiny library that brings Tiny Types to JavaScript and TypeScript

44 lines 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.deprecated = deprecated; /** * @desc A decorator to mark a class, method or function as deprecated and make it log a warning whenever it is used. * Please see the tests for examples of usage. * * @param {string} message - describes the alternative implementation that should be used instead * of the deprecated method/function/class * @param {Logger} log - a function that handles the printing of the message, * such as {@link console.warn} */ function deprecated(message = '', log = console.warn) { // eslint-disable-next-line unicorn/consistent-function-scoping,no-prototype-builtins const hasPrototype = (target) => target.hasOwnProperty('prototype'); return (target, propertyKey, descriptor) => { if (target && propertyKey && descriptor) { return deprecateMethod(message, target, propertyKey, descriptor, log); } else if (hasPrototype(target)) { return deprecateClass(message, target, log); } else { throw new Error(`Only a class, method or function can be marked as deprecated. ${typeof target} given.`); } }; } function deprecateClass(message, target, log) { return class extends target { constructor(...args) { log(`${target.name} has been deprecated. ${message}`.trim()); super(...args); } }; } function deprecateMethod(message, target, propertyKey, descriptor, log) { const originalMethod = descriptor.value; descriptor.value = function (...args) { log(`${target.constructor.name}#${propertyKey} has been deprecated. ${message}`.trim()); return originalMethod.apply(this, args); }; return descriptor; } //# sourceMappingURL=deprecated.js.map