All files index.ts

99.42% Statements 170/171
92.71% Branches 89/96
100% Functions 23/23
100% Lines 143/143

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400    1x     3x       2x 2x 4x   4x   1x       14x   14x 34x 1x       14x       59x   59x 162x 53x       59x           18x 1x     17x 17x 17x 17x   17x   13x   12x 30x 30x 30x   30x   24x       12x                                     29x                       29x                   31x 31x 59x   59x   51x 51x 51x 147x   51x                         7x 1x     6x 2x     4x                       44x 44x 44x   44x   44x 83x   83x 1x 1x     82x   82x     67x   67x 2x 2x 2x     65x       43x 31x     43x   43x                         2x 2x 2x   2x 2x       2x                       2x 2x 2x   2x 30x   10x     2x                           3x 6x     3x 1x 1x     2x 2x 2x 2x 1x                 32x 32x   32x 1x       32x 1x 1x   31x                                 21x     21x   2x 2x   5x 5x   1x 1x   13x 13x 26x   13x     21x       12x 13x 13x     1x         6x 6x   6x 1x 1x     5x 6x   6x                     6x   4x 4x   1x 1x 2x   1x   1x 1x 1x     1x   1x   1x                     1x   2x   1x     29x     1x  
/// <reference path="../index.d.ts" />
 
import {find, findIndex, filter} from '@jaszhix/utils';
 
function storeError(method: string, key: State.DisconnectKey, message: string): void {
  console.warn('Warning: [store -> ' + method + ' -> ' + key + '] ' + message, new Error().stack);
}
 
function getByPath(key: string, object: State.Data): State.Data | null {
  const path = key.split('.');
  for (let i = 0; i < path.length; i++) {
    object = object[path[i]];
 
    if (!object) return null;
  }
  return object;
}
 
function differenceKeys(arr1: string[], arr2: string[]): string[] {
  let newKeys = [];
 
  for (let i = 0, len = arr1.length; i < len; i++) {
    if (arr2.indexOf(arr1[i]) === -1) {
      newKeys.push(arr1[i]);
    }
  }
 
  return newKeys;
}
 
function intersectKeys(arr1: string[], arr2: string[]): string[] {
  let newKeys = [];
 
  for (let i = 0, len = arr1.length; i < len; i++) {
    if (arr2.indexOf(arr1[i]) > -1) {
      newKeys.push(arr1[i]);
    }
  }
 
  return newKeys;
}
 
function isEqual(obj1: any, obj2: any): boolean {
  let keys1, keys2, len, matches;
 
  if (!obj1 || !obj2 || typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return obj1 === obj2;
  }
 
  keys1 = Object.keys(obj1);
  keys2 = Object.keys(obj2);
  len = keys1.length;
  matches = 0;
 
  if (keys1.length !== keys2.length) return false;
 
  if (differenceKeys(keys1, keys2).length) return false;
 
  for (let i = 0; i < len; i++) {
    let key = keys1[i];
    let value1 = obj1[key];
    let value2 = obj2[key];
 
    if ((value1 && typeof value1 === 'object' && isEqual(value1, value2) )
      || value1 === value2) {
      matches++;
    }
  }
 
  return matches === len;
}
 
/**
 * init
 * Initializes a store instance. It uses private scoping to prevent
 * its context from leaking.
 *
 * @param {object} [state={}]
 * @param {array} [listeners=[]] - Not intended to be set manually, but can be overriden.
 * See _connect.
 * @returns Initial state object with the public API.
 */
function init(
  state: Partial<State.Data>,
  listeners: State.Listener[] = [],
  mergeKeys: string[] = [],
  connections = 0
): State.Data {
  const publicAPI: State.API = Object.freeze({
    get,
    set,
    setMergeKeys,
    exclude,
    trigger,
    connect,
    disconnect,
    destroy
  });
 
  function getAPIWithObject(object: State.Data): State.Data {
    return Object.assign(object, publicAPI);
  }
 
  /**
   * dispatch
   * Responsible for triggering callbacks stored in the listeners queue from set.
   *
   * @param {object} object
   */
  function dispatch(object: Partial<State.Data>) {
    let keys = Object.keys(object);
    for (let i = 0; i < listeners.length; i++) {
      let commonKeys = intersectKeys(keys, listeners[i].keys);
 
      if (commonKeys.length === 0) continue;
 
      Eif (listeners[i].callback) {
        let partialState: Partial<State.Data> = {};
        for (let z = 0; z < keys.length; z++) {
          partialState[keys[z]] = state[keys[z]];
        }
        listeners[i].callback(partialState);
      }
    }
  }
 
  /**
   * get
   * Retrieves a cloned property from the state object.
   *
   * @param {string} [key=null]
   * @returns {object}
   */
  function get(key: string = ''): any {
    if (!key || key === '*') {
      return exclude();
    }
 
    if (key.indexOf('.') > -1) {
      return getByPath(key, <State.Data>state);
    }
 
    return state[key];
  }
 
  /**
   * set
   * Copies a keyed object back into state, and
   * calls dispatch to fire any connected callbacks.
   *
   * @param {object} object
   * @param {boolean} forceDispatch
   */
  function set(object: Partial<State.Data>, cb?: (() => void) | boolean, force?: boolean): State.API {
    let keys = Object.keys(object);
    let changed = false;
    let changedObject: Partial<State.Data> = {};
 
    force = cb === true || force;
 
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
 
      if (!(key in state)) {
        storeError('set', key, 'Property not found.');
        return publicAPI;
      }
 
      let isObject = object[key] && typeof object[key] === 'object';
 
      if (force
        || (isObject && !isEqual(state[key], object[key]))
        || (!isObject && state[key] !== object[key])) {
        changed = true;
 
        if (mergeKeys.indexOf(key) > -1) {
          Object.assign(state[key], object[key]);
          changedObject[key] = state[key];
          continue;
        }
 
        changedObject[key] = state[key] = object[key];
      }
    }
 
    if ((changed || force) && listeners.length > 0) {
      dispatch(changedObject);
    }
 
    if (typeof cb === 'function') setTimeout(cb, 0);
 
    return publicAPI;
  }
 
  /**
   * setMergeKeys
   * Adds a list of keys that should be merged into state child object instead of copied.
   * This allows being able to pass partial objects to set(). Since there is a performance
   * cost to this operation, it is not the default behavior.
   *
   * @param {array} keys
   * @returns Public API for chaining.
   */
  function setMergeKeys(keys: string[] = []): State.API {
    for (let i = 0, len = keys.length; i < len; i++) {
      const key = keys[i];
      const value = state[key];
 
      Eif (value && typeof value === 'object' && !Array.isArray(value)) {
        mergeKeys.push(key);
      }
    }
 
    return publicAPI;
  }
 
  /**
   * exclude
   * Excludes a string array of keys from the state object.
   *
   * @param {array} excludeKeys
   * @returns Partial or full state object with keys in
   * excludeKeys excluded, along with the public API for chaining.
   */
  function exclude(excludeKeys: string[] = []): Partial<State.Data> {
    let apiKeys = Object.keys(publicAPI);
    let stateKeys = Object.keys(state);
    let filteredState: Partial<State.Data> = {};
 
    for (let i = 0, len = stateKeys.length; i < len; i++) {
      if (apiKeys.indexOf(stateKeys[i]) === -1
        && excludeKeys.indexOf(stateKeys[i]) === -1) {
        filteredState[stateKeys[i]] = state[stateKeys[i]];
      }
    }
    return filteredState;
  }
 
  /**
   * trigger
   * Fires a callback event for any matching key in the listener queue.
   * It supports passing through unlimited arguments to the callback.
   * Useful for setting up actions.
   *
   * @param {string} key
   * @param {any} args
   * @returns {any} Return result of the callback.
   */
  function trigger(key: string, ...args: any[]): any {
    let matchedListeners = filter(listeners, function(listener: State.Listener) {
      return listener.keys.indexOf(key) > -1;
    });
 
    if (matchedListeners.length === 0) {
      storeError('trigger', key, 'Action not found.');
      return;
    }
 
    for (let i = 0; i < matchedListeners.length; i++) {
      Eif (matchedListeners[i].callback) {
        let output = matchedListeners[i].callback(...args);
        if (output !== undefined) {
          return output;
        }
      }
    }
  }
 
  function _connect(keys: string[], callback: State.StateCallback | State.TriggerCallback, id: number, context: object | undefined): void {
    let listener: State.Listener | undefined;
 
    Eif (callback) {
      listener = find(listeners, (_listener: State.Listener) => _listener && _listener.callback === callback);
 
      if (context) {
        callback = callback.bind(context);
      }
    }
 
    if (listener) {
      let newKeys = differenceKeys(keys, listener.keys);
      listener.keys = listener.keys.concat(newKeys);
    } else {
      listeners.push({keys, callback, id});
    }
  }
 
  /**
   * connect
   *
   * @param {any} actions - can be a string, array, or an object.
   * @param {function} callback - callback to be fired on either state
   * property change, or through the trigger method.
   * @returns ID of the added listener.
   */
  function connect(
    actions: State.ConnectActions,
    callback?: State.Callback,
    context?: object | undefined
  ): number {
    const id = connections++;
    let keys: string[];
 
    switch (true) {
      case (actions === '*'):
        listeners.push({keys: Object.keys(state), callback: <State.Callback>callback, id});
        break;
      case (typeof actions === 'string'):
        _connect([<string>actions], <State.Callback>callback, id, context);
        break;
      case (Array.isArray(actions)):
        _connect(<string[]>actions, <State.Callback>callback, id, context);
        break;
      case (typeof actions === 'object'):
        keys = Object.keys(actions);
        for (let i = 0; i < keys.length; i++) {
          _connect([keys[i]], <State.StateCallback>(<State.ActionsObject>actions)[keys[i]], id, context);
        }
        break;
    }
 
    return id;
  }
 
  function findListenerFn(key: State.DisconnectKey) {
    return function(listener: State.Listener) {
      for (let i = 0, len = listener.keys.length; i < len; i++) {
        if (listener.keys[i] === key) return true;
      }
 
      return false;
    }
  }
 
  function disconnectByKey(key: State.DisconnectKey): void {
    let matches = filter(listeners, findListenerFn(key));
    let count = matches.length;
 
    if (!matches.length) {
      storeError('disconnect', key, 'Invalid disconnect key.');
      return;
    }
 
    while (count) {
      listeners.splice(findIndex(listeners, findListenerFn(key)), 1);
 
      count--;
    }
  }
 
  /**
   * disconnect
   * Removes a callback listener from the queue.
   *
   * @param {string} key
   */
  function disconnect(key: State.DisconnectKey): void {
    switch (true) {
      case (typeof key === 'string'):
        disconnectByKey(key);
        break;
      case (Array.isArray(key)):
        key = <string[]> key;
        for (let i = 0; i < key.length; i++) {
          disconnectByKey(key[i]);
        }
        break;
      case (typeof key === 'number'):
        for (let i = 0; i < listeners.length; i++) {
          let index = findIndex(listeners, function(listener: State.Listener) {
            return listener.id === key;
          });
 
          Iif (index === -1) continue;
 
          listeners.splice(index, 1);
        }
        break;
    }
  }
 
  /**
   * destroy
   * Assigns undefined to all state properties and listeners. Intended
   * to be used at the end of the application life cycle.
   *
   */
  function destroy() {
    for (let i = 0; i < listeners.length; i++) {
      // @ts-ignore
      listeners[i] = undefined;
    }
    listeners = [];
  }
 
  return getAPIWithObject(<State.Data>state);
}
 
export {init};