-
-
Notifications
You must be signed in to change notification settings - Fork 0
Aliases
This module is based on descriptors.js and provides helpers to create aliases within an object. It is done by copying descriptors.
This micro-module is formulated in terms of descriptors.js utilities.
See src/aliases.js for details.
The following utilities are available:
| Function | Return value | Description |
|---|---|---|
addAlias(object, name, aliases, force) |
object |
Add an alias to an object. |
addAliases(object, dict, force) |
object |
Add aliases to an object. |
addProtoAlias(Class, name, aliases, force) |
Class.prototype |
Add an alias on a class's prototype. |
addProtoAliases(Class, dict, force) |
Class.prototype |
Add aliases on a class's prototype. |
addAlias() takes the following arguments:
-
object— The object to add the alias to. -
name— The name of the property to alias. It can be a string or a symbol. -
aliases— The alias(es) to add. It is used as thenamesargument ofaddDescriptor()of descriptors.js.- If it is a string it is treated as a comma-separated list of names.
- It can be a symbol.
- It can be an array of symbols or strings.
-
force— If truthy, then the alias will be added even if it is already there.
addAliases() differs from addDescriptors() in that it adds multiple aliases to an object using
the special dict argument. It is used as the names argument of copyDescriptors() of
descriptors.js. In this case, only the last form (a dictionary) makes sense:
- An object with keys as symbols or strings denoting a name of a descriptor from the object.
An associated value is a value suitable as the
namesargument ofaddDescriptor().
addProtoAlias() and addProtoAliases() are class-prototype-aware sugar —
addProtoAlias(Foo, 'method', 'mtd') is equivalent to addAlias(Foo.prototype, 'method', 'mtd').
Use these when targeting a class's prototype directly so the call site reads Foo instead of
Foo.prototype. Both delegate to their non-proto counterparts and return the prototype object.
import {addAlias, addAliases} from 'meta-toolkit/aliases.js';
class Foo {
constructor() {
this.value = 0;
}
get double() {
return this.value * 2;
}
line(a, b) {
return a * this.value + b;
}
}
addAliases(Foo.prototype, {
double: 'x2, duplicate',
line: 'linear'
});
const f = new Foo();
console.log(f.double); // 0
console.log(f.line(1, 2)); // 2
console.log(f.duplicate); // 0
console.log(f.linear(1, 2)); // 2
console.log(f.x2); // 0The same with addProtoAliases() (no .prototype at the call site):
import {addProtoAliases} from 'meta-toolkit/aliases.js';
class Bar {
greet() {
return 'hi';
}
size() {
return 0;
}
}
addProtoAliases(Bar, {
greet: 'hello, sayHi',
size: 'length, count'
});
const b = new Bar();
b.hello(); // 'hi'
b.length(); // 0All functions are exported by their names. There is no default export.
API
Reference