npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pure-function-decorator

v2.0.1

Published

An implementation to create decorators in functions

Downloads

1,440

Readme

Pure Function decorator

What is this project?

I love typescript decorators <3, but we know that is impossible to use in pure functions, only in methods in class. But in Typescript we usually prefer to use just functions instead of classes and methods. This project is a "Hack" to use the same implementation of method decorators in pure functions (but without the sintax @myDecorator, I'm sorry). This happens because the Property Descriptors just work in classes.

Decorators is just a design pattern. This repo create a simple implementation to javascript and typescript to use this pattern in your project with functions.

Installation

$ npm i --save pure-function-decorator

Usage

In method decorator in Typescript receives 3 parameters. The target, the propertyKey and the descriptor. The target is the class, the propertyKey is the name of method and the descriptor is an instance of Property Descriptors. To keep the compatibility in pure functions, the target should be null and the property descriptor should be generate in instanciation. The propertyKey is the name of function.

You must import the function fnDecorator and pass two parameters. The first is the list of decorators (if is just one decorator you don't need to pass an array) and the second parameter is the function.

In the descriptor, exists the attribute called value. The value (in method decorator)

Sync way

Example: Log a synchronous function execution

import { fnDecorator } from 'pure-function-decorator';

const logger = (_target: any, _propertyKey: any, descriptor: PropertyDescriptor): void => {
  // descriptor.value is the original function
  const oldValue = descriptor.value; // save in aux

  // replace the value with another function
  // If you use `descriptor.value = () => {}` instead of function,
  //   you cannot access the `arguments`
  descriptor.value = function () {
    console.log('Start FN');
    const response = oldValue.apply(this, arguments);
    console.log('End FN');

    return response;
  };
};

const sum = (a: number, b: number): number => a + b;
const sumDecorated = fnDecorator(logger, sum);
console.log(sumDecorated(1, 2));
/*
Result:

Start FN
End FN
3
*/

PS: Is IMPORTANT to descriptor.value is a function instead of () => {}, because with function sintax you can get the attributes.

The greatest advantage is that you can use the same decorator in methods, like this:

// Same for decorator for a class works like a charm
class MyClass {
  @logger
  sum(a: number, b: number): number {
    return a + b;
  }
}

const math = new MyClass();
console.log(math.sum(1, 2));

Async way

Example: Log a time of request to api

import { fnDecorator } from '../src/decorator';
import axios from 'axios';

const measureTimeAsync = (
  _target: any,
  _propertyKey: string,
  descriptor: PropertyDescriptor,
): void => {
  const oldValue = descriptor.value;

  descriptor.value = async function () {
    console.time('Runner');
    console.log('Start request');
    const response = await oldValue.apply(this, arguments);
    console.timeEnd('Runner');

    return response;
  };
};

const getGithubUser = async (githubUsername: string): Promise<unknown> => {
  const user = await axios.get<unknown>(`https://api.github.com/users/${githubUsername}`);

  return user.data;
};

const getGithubUserDecorated = fnDecorator(measureTimeAsync, getGithubUser);

getGithubUserDecorated('renatocassino').then(console.log);

/*
Result:

Start request
Runner: 259.274ms
{
  login: 'renatocassino',
  ........
*/

There are multiple examples in folder examples;