https://github.com/mattphillips/trait-contract
Utility to build a Trait (Interface) for a given Type and supply an implementation which is validated against the Trait contract
https://github.com/mattphillips/trait-contract
contract interface trait
Last synced: 3 months ago
JSON representation
Utility to build a Trait (Interface) for a given Type and supply an implementation which is validated against the Trait contract
- Host: GitHub
- URL: https://github.com/mattphillips/trait-contract
- Owner: mattphillips
- License: mit
- Created: 2016-11-30T22:52:22.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2020-04-24T23:17:45.000Z (about 5 years ago)
- Last Synced: 2025-01-29T09:44:59.073Z (5 months ago)
- Topics: contract, interface, trait
- Language: JavaScript
- Homepage:
- Size: 14.6 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Trait Contract
[](https://travis-ci.org/mattphillips/trait-contract)
[](https://coveralls.io/github/mattphillips/trait-contract?branch=master)Utility to build a Trait (Interface) for a given Type. The Trait's contract is used to validate against the implementation, throwing an `Error` if the implementation is missing a property of the Trait.
If an implementation conforms to it's Trait then the given functions are validated for the number of arguments they are invoked with, throwing an `Error` if called with too few or too many arguments.
## Example
``` js
const Database = Trait({
create: ['x'],
read: [],
update: ['id', 'x'],
delete: ['id']
});const InMemoryDatabase = {
create: (x) => { ... },
read: () => { ... },
update: (id, x) => { ... },
delete: (id) => { ... }
};const PersistentDatabase = {
create: (x) => { ... },
read: () => { ... },
update: (id, x) => { ... }
};const app = (dbImpl) => {
const db = Database.impl(dbImpl);
// Calling create function with one argument conforms to Database Trait's
// contract and runs the implementation of create function with 'Hello, world!'.
db.create('Hello, world!');// Calling create function with two arguments does not conform to the Database
// Trait's contract so an Error is thrown because create function expects to
// receive one argument.
db.create('Hello,', 'world!');
}// InMemoryDatabase conforms to Database Trait's contract used by app so no Error is thrown.
app(InMemoryDatabase);// PersistentDatabase does not conform to Database Trait's contract used by app
// so an Error is thrown because the delete function is missing from the implementation.
app(PersistentDatabase);
```