SkillAgentSearch skills...

Singleton

Singleton decorator. No constructor monkeypatching. Zero dependencies. Built with TypeScript.

Install / Use

/learn @fxlrnrpt/Singleton
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

singleton Build Status Coverage Status Tweet

Singleton decorator. No constructor monkeypatching. Zero dependencies. Built with TypeScript.

<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <!-- END doctoc generated TOC please keep comment here to allow auto update -->

Installation

  1. Run

    npm i @keenondrums/singleton
    
  2. (Optional) Enable decorators

    1. If you use TypeScript set in you tsconfig.json

      {
        "compilerOptions": {
          "experimentalDecorators": true
        }
      }
      
    2. If you use JavaScript configure your babel to support decorators and class properties

Quick start

import { singleton } from '@keenondrums/singleton'

@singleton
class Test {}

new Test() === new Test() // returns `true`

Usage without decorators

import { singleton } from '@keenondrums/singleton'

class Test {}
const TestSingleton = singleton(Test)

new TestSingleton() === new TestSingleton() // returns `true`

Inheritance

Any child of your singleton will not be a singleton.

import { singleton } from '@keenondrums/singleton'

@singleton
class Parent {}

class Child extends Parent {}

new Child() === new Child() // returns `false`

// If you want to make `Child` a singleton as well, apply `singleton` decorator directly to it
@singleton
class ChildSingleton extends Parent {}

new ChildSingleton() === new ChildSingleton() // returns `true`

In depth

singleton decorator wraps your class with a Proxy and a construct trap to override class' creation logic.

Your singleton instance is always available as a static property of a class by key SINGLETON_KEY.

import { singleton, SINGLETON_KEY } from '@keenondrums/singleton'

@singleton
class Test {}

const instance = new Test()
Test[SINGLETON_KEY] === instance // returns `true`
View on GitHub
GitHub Stars28
CategoryDevelopment
Updated1y ago
Forks2

Languages

TypeScript

Security Score

80/100

Audited on Jan 31, 2025

No findings