ivteplo / mixins

JavaScript library for mixins

Home Page:https://npmjs.com/package/@teplovs/mixins

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mixins

JavaScript library for mixins

Installation

npm install @teplovs/mixins
# or, if you prefer yarn:
yarn add @teplovs/mixins

Usage Example

import { createMixin } from "@teplovs/mixins"

class Animal {}

const canFly = createMixin(ParentClass =>
  class CanFly extends ParentClass {
    canFly = true
  }
)

const canRun = createMixin(ParentClass =>
  class CanRun extends ParentClass {
    canRun = true
  }
)

const canGreet = createMixin((ParentClass, sound) =>
  class CanGreet extends ParentClass {
    greet(name) {
      return `${sound} ${name}!`
    }
  }
)

class Dog extends canRun(canGreet(Animal, "Woof woof")) {
  // ...
}

class Cat extends canRun(canGreet(Animal, "Meow")) {
  // ...
}

class Parrot extends canFly(canGreet(Animal, "Chirp chirp. Hi")) {
  // ...
}

new Dog().greet("y'all") // "Woof woof y'all!"
new Cat().greet("y'all") // "Meow y'all!"
new Parrot().greet("y'all") // "Chirp chirp. Hi y'all!"

new Dog().canRun // true
new Cat().canRun // true
new Parrot().canFly // true

API

createMixin(createClass: (ParentClass, ...props) => Class): (...props) => Class

Function to create a new mixin.

Mixin without properties

class Animal {}

const canRun = createMixin(ParentClass =>
  class CanRun extends ParentClass {
    canRun = true
  }
)

const AnimalThatCanRun = canRun(Animal)
new AnimalThatCanRun().canRun // true

Mixin with properties

class Person {}

const hasHobby = createMixin((ParentClass, personsHobby) =>
  class HasHobby extends ParentClass {
    hobby = personsHobby
  }
)

const Artist = hasHobby(Person, "drawing")
new Artist().hobby // "drawing"

Development

Requirements

  • Node.js and npm

Setup

  1. Clone the repository
git clone https://github.com/teplovs/mixins
  1. Navigate to the project folder
cd mixins
  1. Install dependencies
npm install
# or, if you prefer yarn:
yarn install
  1. To run tests:
npm test
# or:
yarn test
  1. To build:
npm run build
# or:
yarn build
  1. Happy hacking! 🎉

About

JavaScript library for mixins

https://npmjs.com/package/@teplovs/mixins

License:Apache License 2.0


Languages

Language:TypeScript 94.5%Language:JavaScript 5.5%