Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

extension-methods-js

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

extension-methods-js

Binds static methods to types.

  • 1.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3
Maintainers
1
Weekly downloads
 
Created
Source

extension-methods-js

This package is inspired by C#'s extension methods. This package provides a function that will bind an extension type to whatever target type you want those methods to be on.

Table of Contents

  1. Installation
  2. Basic Usage

Installation:

npm i extension-methods-js

Basic Usage:

import { bindExtensions } from 'extension-methods-js';

// For TypeScript, update the target type interfaces with extension methods.
// Be sure to OMIT the first argument (the target) and that methods are NOT static.
declare global {
  interface Array<T> {
    clear(): void;
  }

  interface Set<T> {
    pipe(action: (item: T) => void): void;
  }
}
 
// Define extension classes.
// Ensure each method is static and the first argument is the target type.
class ArrayExtensions {
  public static clear<TSource>(arr: TSource[]): void {
    arr.length = 0;
  }
}

class SetExtensions {
  public static pipe<TSource>(set: TSource[], action: (item: TSource) => void): void {
    for (const item of set) {
      action(item);
    }
  }
}

// Bind extension classes to targets.
bindExtensions([[ArrayExtensions, Array], [SetExtensions, Set]]);
// You can also use the other overload bindExtensions(ArrayExtensions, Array) if you only have one extension class.

const arr = [1, 2, 3];

// Arrays now have extension methods.
arr.clear();

// Will be []
console.log(arr);

const set = new Set([1, 2, 3]);

// Sets now have extension methods.
set.pipe(x => console.log(x));

Keywords

FAQs

Package last updated on 03 Sep 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc