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

@hazae41/box

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hazae41/box

Rust-like Box for TypeScript

  • 1.0.14
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.2K
increased by2.57%
Maintainers
1
Weekly downloads
 
Created
Source

Box

Rust-like Box for TypeScript

npm i @hazae41/box

Node Package 📦

Features

Current features

  • 100% TypeScript and ESM
  • No external dependencies
  • Similar to Rust
  • Can hold data
  • Unit-tested
  • Uses Result from @hazae41/result

Usage

The Box<T extends Disposable> will:

  • hold a disposable object T
  • only dispose the object if it still owns it
  • no longer own it if the box is moved
import { Box } from "@hazae41/box"

class D {
  [Symbol.dispose]() { 
    console.log("it should only happen once")
  }
}

/**
 * At the end of this block, D will only be disposed once
 */
{
  using box = new Box(new D())
  using box2 = box.move()
}

Rules

  1. You can't pass a disposable object without wrapping it in a Box
  2. You can't hold a disposable object without wrapping it in a Box
  3. You can't hold a Box without owning it and disposing it after
  4. You can't return a Box without unwrapping it

This means the typical object holding a Box looks like this

import { Box } from "@hazae41/box"

class MyWrapper<T extends Disposable> {

  private constructor(
    /**
     * Rule 2. hold as box
     **/
    readonly box: Box<T>
  ) {}

  [Symbol.dispose]() {
    /**
     * Rule 3. dispose any box you hold
     **/
    this.box[Symbol.dispose]()
  }

  static create<T extends Disposable>(box: Box<T>) {
    /**
     * Rule 3. own any box you want to hold
     **/
    return new MyWrapper(box.move())
  }

  use() {
    /**
     * Rule 1. only pass as box
     **/
    something(this.box)
  }

  export(): T {
    /**
     * Rule 4. unwrap on return
     **/
    return this.box.unwrap()
  }

}

Keywords

FAQs

Package last updated on 29 Nov 2023

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