

/** Extract preferences by prefix.
 *
 * This function returns a lambda which, given
 * a key or a prefix, extracts the relevant
 * preferences from the designated preferences
 * store.
 *
 * For instance, assume preferences = {
 *   "a.b.c.d": 1,
 *   "a.b.e.f": 2,
 *   "g.h": 3
 * }
 *
 * And λ = preferencesλ(preferences). Then:
 *
 * λ("a.b") → { "a.b.c.d": 1, "a.b.e.f": 2 }
 * λ("a.b.e.f") → { "a.b.e.f": 2 }
 * λ("g.x", {"g.x.": 99}) → { "g.x.": 99 }
 * λ("a.c", {"g.x.": 99}) → { "g.x.": 99 }
 *
 * Note from the last  two examples that a default value
 * may be provided and will be returned if a key does
 * not exist or is not searched for.
 */
function preferencesλ (preferences) {

  return function (key, defaults={}) {
    const keys = Object.keys(preferences).filter(str => str.startsWith(key+".") || str == key);

    const settings = {...defaults};
    for (const str of keys) {
      const k = str == key ? str : str.substring(key.length+1);
      const v = preferences[str];
      settings[k] = v;
    }

    return settings;
  }

}

module.exports = preferencesλ;
