Skip to content

Options

Eugene Lazutkin edited this page Aug 14, 2024 · 3 revisions

This module provides utilities that simplify working with options.

options.js

The following utilities are available:

Utility Return value Description
copyOptions(target, defaults, ...sources) target Copy options according to some defaults.

copyOptions() has the following arguments:

  • target — an object to copy options to.
  • defaults — an object with default options.
  • sources — an array of options to copy to target.

defaults is an object that defines named options with default values. If a value is not undefined, it is copied to target.

sources is an array of objects that contain options to copy to target. Only options defined in defaults are copied, the rest are ignored.

copyOptions() copies non-undefined values from the defaults, then copies values from the sources from left to right sequentially. Only top-level keys are used. The copied options can override the defaults and the other sources. No attempt to merge options is made.

Examples

The utility can support the following style:

import {copyOptions} from 'meta-toolkit/options.js';

const defaults = {
  foo: 'bar',
  bar: {a: 1},
  baz: undefined // expected, but no default value
};

class Foo {
  constructor(options) {
    copyOptions(this, defaults, options);
  }
  baz() { return 42; }
  quux() { return this.foo; }
}

const a = new Foo();
console.log(a.foo, a.bar, a.baz()); // bar, {a: 1}, 42

const b = new Foo({bar: {b: 2}});
console.log(b.foo, b.bar, b.baz()); // bar, {b: 2}, 42

const c = new Foo({baz: () => 33});
console.log(c.foo, c.bar, c.baz()); // bar, {a: 1}, 33

const d = new Foo(c); // copy options from `c`
console.log(d.foo, d.bar, d.baz()); // bar, {a: 1}, 33

const e = new Foo({abc: 'quux'}); // unknown options are ignored
console.log(e.foo, e.bar, e.baz()); // bar, {a: 1}, 42

const f = new Foo(e.foo === 'abc' && {foo: 'xyz'}); // non-objects are ignored
console.log(f.foo, f.bar, f.baz()); // bar, {a: 1}, 42

Exports

All functions are exported by their names. There is no default export.

Clone this wiki locally