Giter Site home page Giter Site logo

developit / decko Goto Github PK

View Code? Open in Web Editor NEW
1.0K 15.0 36.0 51 KB

:dash: The 3 most useful ES7 decorators: bind, debounce and memoize

Home Page: https://developit.github.io/decko/

License: MIT License

JavaScript 96.24% TypeScript 3.76%
decorators debounce throttle-calls memoize memoization

decko's Introduction

decko NPM Version Build Status

A concise implementation of the three most useful decorators:

  • @bind: make the value of this constant within a method
  • @debounce: throttle calls to a method
  • @memoize: cache return values based on arguments

Decorators help simplify code by replacing the noise of common patterns with declarative annotations. Conversely, decorators can also be overused and create obscurity. Decko establishes 3 standard decorators that are immediately recognizable, so you can avoid creating decorators in your own codebase.

πŸ’‘ Tip: decko is particularly well-suited to Preact Classful Components.

πŸ’«Β Note:

Installation

Available on npm:

npm i -S decko

Usage

Each decorator method is available as a named import.

import { bind, memoize, debounce } from 'decko';

@bind

class Example {
	@bind
	foo() {
		// the value of `this` is always the object from which foo() was referenced.
		return this;
	}
}

let e = new Example();
assert.equal(e.foo.call(null), e);

@memoize

Cache values returned from the decorated function. Uses the first argument as a cache key. Cache keys are always converted to strings.

Options:

caseSensitive: false - Makes cache keys case-insensitive

cache: {} - Presupply cache storage, for seeding or sharing entries

class Example {
	@memoize
	expensive(key) {
		let start = Date.now();
		while (Date.now()-start < 500) key++;
		return key;
	}
}

let e = new Example();

// this takes 500ms
let one = e.expensive(1);

// this takes 0ms
let two = e.expensive(1);

// this takes 500ms
let three = e.expensive(2);

@debounce

Throttle calls to the decorated function. To debounce means "call this at most once per N ms". All outward function calls get collated into a single inward call, and only the latest (most recent) arguments as passed on to the debounced function.

Options:

delay: 0 - The number of milliseconds to buffer calls for.

class Example {
	@debounce
	foo() {
		return this;
	}
}

let e = new Example();

// this will only call foo() once:
for (let i=1000; i--) e.foo();

License

MIT

decko's People

Contributors

bryanjenningz avatar cronon avatar dalaidunc avatar danielruf avatar developit avatar hotell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

decko's Issues

[DOCS] Better options documentaion

These things are unclear from the current documentation about the options:

  • How to use options
  • What are the default values

It is possible to look them up in source code, but I think, it would be nice to have them in docs.

@bind() decorator not working in IE11

I have this small example:

import { Component, h, define } from 'skatejs';

import { bind } from 'decko';

export default class App extends Component<void> {
  static get is() { return 'my-app'; }

  @bind()
  handleClick() {
    console.log( 'clicked with this scope: ', this );
  }

  renderCallback() {
    return [
      <div onClick={this.handleClick}>Hello my lord!</div>,
    ];
  }
};

define(App);

When I try this in IE (11) I have this error:
image

In chrome it works properly...

You can try it in this repository which I created for this issue:
https://github.com/davidrus/skate-starter

@debounce is named improperly β€” should be @throttle

In the docs its says:

To debounce means "call this at most once per N ms". All outward function calls get collated into a single inward call, and only the latest (most recent) arguments as passed on to the debounced function.

What you're doing is throttling, not debouncing.
lodash.throttle:

Creates a throttled function that only invokes func at most once per every wait milliseconds.

lodash.debounce:

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.

And while on the topic, a (real) @debounce would be a great addition.

Issues with Typescript

Attempting to use bind throws this compilation error:

TS1241: Unable to resolve signature of method decorator when called as an expression.
      Type 'TypedPropertyDescriptor<unknown>' is not assignable to type 'void | TypedPropertyDescriptor<(userInfo: Readonly<UserInfo>) => void>'.
        Type 'TypedPropertyDescriptor<unknown>' is not assignable to type 'TypedPropertyDescriptor<(userInfo: Readonly<UserInfo>) => void>'.
          Types of property 'value' are incompatible.
            Type 'unknown' is not assignable to type '((userInfo: Readonly<UserInfo>) => void) | undefined'.
              Type 'unknown' is not assignable to type '(userInfo: Readonly<UserInfo>) => void'.

Non-primitive function parameters

The current implementation of memoize doesn't work correctly with non-primitive function parameters.

E.g. look at this test:

it('should not overwrite non-primitive arguments', next => {
  const cache = Object.create(null)
  let c = memoize((key => key), { cache })

  const key1 = { a: 1 }
  const key2 = { a: 2 }
  c(key1)
  c(key2)

  expect(Object.keys(cache)).to.have.length(2)
  // ... cache is { '[Object object]': { a: 2 } } now

  next()
});

Do you think it would make sense to print a corresponding error message when they try to pass any non-primitive ref as a parameter?

WeakMap could be a solution for this problem (for memory leak also).

cc @stryju

@bind decorator bug when super method is called

This snippet demonstrates that the bind decorator does not work correctly on second method call if that method invokes super method which in turn is also decorated:

class A {
    @bind
    f() {
        console.log('I\'m A.f');
    }
}

class B extends A {
    @bind
    f() {
        console.log('I\'m B.f BEGIN');
        super.f();
        console.log('I\'m B.f END');
    }
}

let b = new B();
console.log('call b.f() 1st time:');
b.f();
console.log('call b.f() 2nd time:');
b.f();

Output:

call b.f() 1st time:
I'm B.f BEGIN
I'm A.f
I'm B.f END
call b.f() 2nd time:
I'm A.f

TS definitions

hey Jason. Would you be open to add TS definitions for this project? If yes I'll sent PR.

thanks man!

Don't think @memorize fit any case.

I saw you use first argument as key of cache.
What if the first argument is an object, like this:

const a = {};
const b = {c: {}}
String(a) //"[object Object]"
String(b) //"[object Object]"

Besides, can you provide any benchmark tests?
I don't think it fit any case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.