// initialize (TOAFactory is delivered from script (see document source))
const {
IS, /* the main type checking function */
maybe, /* a try/catch wrapper utility function */
$Wrap, /* wrapper method for any variable */
isNothing, /* special function for empty stuff (null, NaN etc) */
isOnly, /* special function to only check the current type
of a value (not up the prototype chain) */
proxyWrapper, /* A function to wrap a Proxy instance to make
detection of a Proxy 'type' possible */
} = TOAFactory({useSymbolicExtensions: true});
// After the browser script is loaded, [Object] has a static
// symbolic property [Symbol.for("toa.symbols")] containing some Symbols used
const TOASymbols = Object[Symbol.for("toa.symbols")];
// Now some symbolic Object properties/extensions are available:
// assign the symbols locally (they are set because the parameter useSymbolicExtensions
// was set to true)
const TOASymbols = Object[Symbol.for("toa.symbols")];
const [is, type, justME, proxy] = [
TOASymbols.is,
TOASymbols.type,
TOASymbols.justME,
TOASymbols.proxy
];
// definitions used in the following examples
const [tru, flse, zero, not_a_nr, nil, undef, div, div2, nonDiv, proxyEx] =
[ true, false, 0, +("NaN"), null, undefined,
Object.assign(document.createElement("div"), {textContent: "I am div"}),
Object.assign(document.createElement("div"), {textContent: "I am div 2"}),
document.createElement("unknown"),
someProxy() ];
// a Classfree Object Oriented constructor
const IntArray = FixedLenIntArrayFactory(); // this creates the IntArray 'type'
const max5Ints = IntArray(5).setValues(1, 2, 2.5, 42, `hello`);
function FixedLenIntArrayFactory() {
function restrain(values, maxLen) {
return values.filter(v =>
typeof v !== `string` && !Number.isNaN(+v) && +v % 1 === 0).slice(0, maxLen);
}
return function CTOR(maxLen) {
let values = [];
const instance = {};
Object.defineProperties(instance, {
maxLen: { value: maxLen },
length: { get() { return values.length; } },
rawValues: { get() { return values; } },
values: { get() { return restrain(values, instance.maxLen); } },
setValues: { value: function(...values2Set) { values = values2Set; return instance; } },
valueOf: { get() { return restrain(values, instance.maxLen); } },
constructor: { get() { return CTOR; } },
toString: { value() { return `[${restrain(values, instance.maxLen)}]`; } },
});
Object.setPrototypeOf(instance, Array.prototype);
return Object.freeze(instance);
}
}
// a constructor
function SomeCTOR(something) {
this.something = something;
}
// a proxy
function someProxy() {
return new Proxy(new String("hello"), {
get(obj, key) { return key === 'world' ? (obj += " world") && obj : obj[key] }
});
}