addon-sdk/source/lib/sdk/util/dispatcher.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/util/dispatcher.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,55 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/.
     1.7 + */
     1.8 +"use strict";
     1.9 +
    1.10 +module.metadata = {
    1.11 +  "stability": "experimental"
    1.12 +};
    1.13 +
    1.14 +const method = require("method/core");
    1.15 +
    1.16 +// Utility function that is just an enhancement over `method` to
    1.17 +// allow predicate based dispatch in addition to polymorphic
    1.18 +// dispatch. Unfortunately polymorphic dispatch does not quite
    1.19 +// cuts it in the world of XPCOM where no types / classes exist
    1.20 +// and all the XUL nodes share same type / prototype.
    1.21 +// Probably this is more generic and belongs some place else, but
    1.22 +// we can move it later once this will be relevant.
    1.23 +let dispatcher = hint => {
    1.24 +  const base = method(hint);
    1.25 +  // Make a map for storing predicate, implementation mappings.
    1.26 +  let implementations = new Map();
    1.27 +
    1.28 +  // Dispatcher function goes through `predicate, implementation`
    1.29 +  // pairs to find predicate that matches first argument and
    1.30 +  // returns application of arguments on the associated
    1.31 +  // `implementation`. If no matching predicate is found delegates
    1.32 +  // to a `base` polymorphic function.
    1.33 +  let dispatch = (value, ...rest) => {
    1.34 +    for (let [predicate, implementation] of implementations) {
    1.35 +      if (predicate(value))
    1.36 +        return implementation(value, ...rest);
    1.37 +    }
    1.38 +
    1.39 +    return base(value, ...rest);
    1.40 +  };
    1.41 +
    1.42 +  // Expose base API.
    1.43 +  dispatch.define = base.define;
    1.44 +  dispatch.implement = base.implement;
    1.45 +  dispatch.toString = base.toString;
    1.46 +
    1.47 +  // Add a `when` function to allow extending function via
    1.48 +  // predicates.
    1.49 +  dispatch.when = (predicate, implementation) => {
    1.50 +    if (implementations.has(predicate))
    1.51 +      throw TypeError("Already implemented for the given predicate");
    1.52 +    implementations.set(predicate, implementation);
    1.53 +  };
    1.54 +
    1.55 +  return dispatch;
    1.56 +};
    1.57 +
    1.58 +exports.dispatcher = dispatcher;

mercurial