Provides a textual representation for unions.
This API is still experimental, so it may change or be removed in future versions. You should not rely on it for production applications.
Provides a textual representation for unions.
The debugRepresentation
serialisation bestows ES2015's Symbol.toStringTag
, used
for the native Object.prototype.toString
, along with a .toString()
method and Node's REPL .inspect()
method.
const { union, derivations } = require('folktale/adt/union');
const { Id } = union('Id', {
Id(value){ return { value } }
}).derive(derivations.debugRepresentation);
Object.prototype.toString.call(Id(1));
// => '[object Id.Id]'
Id(1).toString();
// ==> 'Id.Id({ value: 1 })'
Id(1).inspect();
// ==> 'Id.Id({ value: 1 })'
This derivation defines ES2015's ToStringTag
symbol, which is used
by Object.prototype.toString to construct a default textual
representation of the object.
This means that instead of getting '[object Object]'
, you'll get
a more helpful '[object <Type>.<Tag>]'
representation, where this
function is used.
This derivation defines a .toString()
method. .toString
is called
in many places to define how to represent an object, but also called
when JS operators want to convert an object to a String. This derivation
only cares about representation that's suitable for debugging.
The representation includes the type, tag, and key/value pairs of the data structure.
Node's REPL uses .inspect()
instead of the regular .toString()
.
This derivation also provides the .inspect()
method, but just as
an alias for the .toString()
method.
(variant, adt) => { // eslint-disable-line max-statements
const typeName = adt[typeSymbol];
const variantName = `${adt[typeSymbol]}.${variant.prototype[tagSymbol]}`;
// (for Object.prototype.toString)
adt[Symbol.toStringTag] = typeName;
variant.prototype[Symbol.toStringTag] = variantName;
// (regular JavaScript representations)
/*~
* stability: experimental
* module: null
* authors:
* - "@boris-marinov"
*
* type: |
* () => String
*/
adt.toString = () => typeName;
/*~
* stability: experimental
* mmodule: null
* authors:
* - "@boris-marinov"
*
* type: |
* () => String
*/
variant.toString = () => variantName;
/*~
* stability: experimental
* module: null
* authors:
* - "@boris-marinov"
*
* type: |
* (Union).() => String
*/
variant.prototype.toString = function() {
return `${variantName}(${plainObjectToString.call(this)})`;
};
// (Node REPL representations)
adt.inspect = adt.toString;
variant.inspect = variant.toString;
variant.prototype.inspect = variant.prototype.toString;
return variant;
}