<commit_before>'use strict';

/**
 * @ngdoc type
 * @name angular.Module
 * @module ng
 * @description
 *
 * Interface for configuring angular {@link angular.module modules}.
 */

function setupModuleLoader(window) {

  var $injectorMinErr = minErr('$injector');
  var ngMinErr = minErr('ng');

  function ensure(obj, name, factory) {
    return obj[name] || (obj[name] = factory());
  }

  var angular = ensure(window, 'angular', Object);

  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  angular.$$minErr = angular.$$minErr || minErr;

  return ensure(angular, 'module', function() {
    /** @type {Object.<string, angular.Module>} */
    var modules = {};

    /**
     * @ngdoc function
     * @name angular.module
     * @module ng
     * @description
     *
     * The `angular.module` is a global place for creating, registering and retrieving Angular
     * modules.
     * All modules (angular core or 3rd party) that should be available to an application must be
     * registered using this mechanism.
     *
     * When passed two or more arguments, a new module is created.  If passed only one argument, an
     * existing module (the name passed as the first argument to `module`) is retrieved.
     *
     *
     * # Module
     *
     * A module is a collection of services, directives, controllers, filters, and configuration information.
     * `angular.module` is used to configure the {@link auto.$injector $injector}.
     *
     * ```js
     * // Create a new module
     * var myModule = angular.module('myModule', []);
     *
     * // register a new service
     * myModule.value('appName', 'MyCoolApp');
     *
     * // configure existing services inside initialization blocks.
     * myModule.config(['$locationProvider', function($locationProvider) {
     *   // Configure existing providers
     *   $locationProvider.hashPrefix('!');
     * }]);
     * ```
     *
     * Then you can create an injector and load your modules like this:
     *
     * ```js
     * var injector = angular.injector(['ng', 'myModule'])
     * ```
     *
     * However it's more likely that you'll just use
     * {@link ng.directive:ngApp ngApp} or
     * {@link angular.bootstrap} to simplify this process for you.
     *
     * @param {!string} name The name of the module to create or retrieve.
     * @param {!Array.<string>=} requires If specified then new module is being created. If
     *        unspecified then the module is being retrieved for further configuration.
     * @param {Function=} configFn Optional configuration function for the module. Same as
     *        {@link angular.Module#config Module#config()}.
     * @returns {module} new module with the {@link angular.Module} api.
     */
    return function module(name, requires, configFn) {
      var assertNotHasOwnProperty = function(name, context) {
        if (name === 'hasOwnProperty') {
          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
        }
      };

      assertNotHasOwnProperty(name, 'module');
      if (requires && modules.hasOwnProperty(name)) {
        modules[name] = null;
      }
      return ensure(modules, name, function() {
        if (!requires) {
          throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
             "the module name or forgot to load it. If registering a module ensure that you " +
             "specify the dependencies as the second argument.", name);
        }

        /** @type {!Array.<Array.<*>>} */
        var invokeQueue = [];

        /** @type {!Array.<Function>} */
        var configBlocks = [];

        /** @type {!Array.<Function>} */
        var runBlocks = [];

        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);

        /** @type {angular.Module} */
        var moduleInstance = {
          // Private state
          _invokeQueue: invokeQueue,
          _configBlocks: configBlocks,
          _runBlocks: runBlocks,

          /**
           * @ngdoc property
           * @name angular.Module#requires
           * @module ng
           *
           * @description
           * Holds the list of modules which the injector will load before the current module is
           * loaded.
           */
          requires: requires,

          /**
           * @ngdoc property
           * @name angular.Module#name
           * @module ng
           *
           * @description
           * Name of the module.
           */
          name: name,

          /**
           * @ngdoc method
           * @name angular.Module#provider
           * @module ng
           * @param {string} name service name
           * @param {Function} providerType Construction function for creating new instance of the
           *                                service.
           * @description
           * See {@link auto.$provide#provider $provide.provider()}.
           */
          provider: invokeLater('$provide', 'provider'),

          /**
           * @ngdoc method
           * @name angular.Module#factory
           * @module ng
           * @param {string} name service name
           * @param {Function} providerFunction Function for creating new instance of the service.
           * @description
           * See {@link auto.$provide#factory $provide.factory()}.
           */
          factory: invokeLater('$provide', 'factory'),

          /**
           * @ngdoc method
           * @name angular.Module#service
           * @module ng
           * @param {string} name service name
           * @param {Function} constructor A constructor function that will be instantiated.
           * @description
           * See {@link auto.$provide#service $provide.service()}.
           */
          service: invokeLater('$provide', 'service'),

          /**
           * @ngdoc method
           * @name angular.Module#value
           * @module ng
           * @param {string} name service name
           * @param {*} object Service instance object.
           * @description
           * See {@link auto.$provide#value $provide.value()}.
           */
          value: invokeLater('$provide', 'value'),

          /**
           * @ngdoc method
           * @name angular.Module#constant
           * @module ng
           * @param {string} name constant name
           * @param {*} object Constant value.
           * @description
           * Because the constant are fixed, they get applied before other provide methods.
           * See {@link auto.$provide#constant $provide.constant()}.
           */
          constant: invokeLater('$provide', 'constant', 'unshift'),

          /**
           * @ngdoc method
           * @name angular.Module#animation
           * @module ng
           * @param {string} name animation name
           * @param {Function} animationFactory Factory function for creating new instance of an
           *                                    animation.
           * @description
           *
           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
           *
           *
           * Defines an animation hook that can be later used with
           * {@link ngAnimate.$animate $animate} service and directives that use this service.
           *
           * ```js
           * module.animation('.animation-name', function($inject1, $inject2) {
           *   return {
           *     eventName : function(element, done) {
           *       //code to run the animation
           *       //once complete, then run done()
           *       return function cancellationFunction(element) {
           *         //code to cancel the animation
           *       }
           *     }
           *   }
           * })
           * ```
           *
           * See {@link ng.$animateProvider#register $animateProvider.register()} and
           * {@link ngAnimate ngAnimate module} for more information.
           */
          animation: invokeLater('$animateProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#filter
           * @module ng
           * @param {string} name Filter name.
           * @param {Function} filterFactory Factory function for creating new instance of filter.
           * @description
           * See {@link ng.$filterProvider#register $filterProvider.register()}.
           */
          filter: invokeLater('$filterProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#controller
           * @module ng
           * @param {string|Object} name Controller name, or an object map of controllers where the
           *    keys are the names and the values are the constructors.
           * @param {Function} constructor Controller constructor function.
           * @description
           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
           */
          controller: invokeLater('$controllerProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#directive
           * @module ng
           * @param {string|Object} name Directive name, or an object map of directives where the
           *    keys are the names and the values are the factories.
           * @param {Function} directiveFactory Factory function for creating new instance of
           * directives.
           * @description
           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
           */
          directive: invokeLater('$compileProvider', 'directive'),

          /**
           * @ngdoc method
           * @name angular.Module#config
           * @module ng
           * @param {Function} configFn Execute this function on module load. Useful for service
           *    configuration.
           * @description
           * Use this method to register work which needs to be performed on module loading.
           * For more about how to configure services, see
           * {@link providers#provider-recipe Provider Recipe}.
           */
          config: config,

          /**
           * @ngdoc method
           * @name angular.Module#run
           * @module ng
           * @param {Function} initializationFn Execute this function after injector creation.
           *    Useful for application initialization.
           * @description
           * Use this method to register work which should be performed when the injector is done
           * loading all modules.
           */
          run: function(block) {
            runBlocks.push(block);
            return this;
          }
        };

        if (configFn) {
          config(configFn);
        }

        return  moduleInstance;

        /**
         * @param {string} provider
         * @param {string} method
         * @param {String=} insertMethod
         * @returns {angular.Module}
         */
        function invokeLater(provider, method, insertMethod, queue) {
          if (!queue) queue = invokeQueue;
          return function() {
            queue[insertMethod || 'push']([provider, method, arguments]);
            return moduleInstance;
          };
        }
      });
    };
  });

}
<commit_msg>fix(loader): fix double spaces<commit_after>'use strict';

/**
 * @ngdoc type
 * @name angular.Module
 * @module ng
 * @description
 *
 * Interface for configuring angular {@link angular.module modules}.
 */

function setupModuleLoader(window) {

  var $injectorMinErr = minErr('$injector');
  var ngMinErr = minErr('ng');

  function ensure(obj, name, factory) {
    return obj[name] || (obj[name] = factory());
  }

  var angular = ensure(window, 'angular', Object);

  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  angular.$$minErr = angular.$$minErr || minErr;

  return ensure(angular, 'module', function() {
    /** @type {Object.<string, angular.Module>} */
    var modules = {};

    /**
     * @ngdoc function
     * @name angular.module
     * @module ng
     * @description
     *
     * The `angular.module` is a global place for creating, registering and retrieving Angular
     * modules.
     * All modules (angular core or 3rd party) that should be available to an application must be
     * registered using this mechanism.
     *
     * When passed two or more arguments, a new module is created.  If passed only one argument, an
     * existing module (the name passed as the first argument to `module`) is retrieved.
     *
     *
     * # Module
     *
     * A module is a collection of services, directives, controllers, filters, and configuration information.
     * `angular.module` is used to configure the {@link auto.$injector $injector}.
     *
     * ```js
     * // Create a new module
     * var myModule = angular.module('myModule', []);
     *
     * // register a new service
     * myModule.value('appName', 'MyCoolApp');
     *
     * // configure existing services inside initialization blocks.
     * myModule.config(['$locationProvider', function($locationProvider) {
     *   // Configure existing providers
     *   $locationProvider.hashPrefix('!');
     * }]);
     * ```
     *
     * Then you can create an injector and load your modules like this:
     *
     * ```js
     * var injector = angular.injector(['ng', 'myModule'])
     * ```
     *
     * However it's more likely that you'll just use
     * {@link ng.directive:ngApp ngApp} or
     * {@link angular.bootstrap} to simplify this process for you.
     *
     * @param {!string} name The name of the module to create or retrieve.
     * @param {!Array.<string>=} requires If specified then new module is being created. If
     *        unspecified then the module is being retrieved for further configuration.
     * @param {Function=} configFn Optional configuration function for the module. Same as
     *        {@link angular.Module#config Module#config()}.
     * @returns {module} new module with the {@link angular.Module} api.
     */
    return function module(name, requires, configFn) {
      var assertNotHasOwnProperty = function(name, context) {
        if (name === 'hasOwnProperty') {
          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
        }
      };

      assertNotHasOwnProperty(name, 'module');
      if (requires && modules.hasOwnProperty(name)) {
        modules[name] = null;
      }
      return ensure(modules, name, function() {
        if (!requires) {
          throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
             "the module name or forgot to load it. If registering a module ensure that you " +
             "specify the dependencies as the second argument.", name);
        }

        /** @type {!Array.<Array.<*>>} */
        var invokeQueue = [];

        /** @type {!Array.<Function>} */
        var configBlocks = [];

        /** @type {!Array.<Function>} */
        var runBlocks = [];

        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);

        /** @type {angular.Module} */
        var moduleInstance = {
          // Private state
          _invokeQueue: invokeQueue,
          _configBlocks: configBlocks,
          _runBlocks: runBlocks,

          /**
           * @ngdoc property
           * @name angular.Module#requires
           * @module ng
           *
           * @description
           * Holds the list of modules which the injector will load before the current module is
           * loaded.
           */
          requires: requires,

          /**
           * @ngdoc property
           * @name angular.Module#name
           * @module ng
           *
           * @description
           * Name of the module.
           */
          name: name,

          /**
           * @ngdoc method
           * @name angular.Module#provider
           * @module ng
           * @param {string} name service name
           * @param {Function} providerType Construction function for creating new instance of the
           *                                service.
           * @description
           * See {@link auto.$provide#provider $provide.provider()}.
           */
          provider: invokeLater('$provide', 'provider'),

          /**
           * @ngdoc method
           * @name angular.Module#factory
           * @module ng
           * @param {string} name service name
           * @param {Function} providerFunction Function for creating new instance of the service.
           * @description
           * See {@link auto.$provide#factory $provide.factory()}.
           */
          factory: invokeLater('$provide', 'factory'),

          /**
           * @ngdoc method
           * @name angular.Module#service
           * @module ng
           * @param {string} name service name
           * @param {Function} constructor A constructor function that will be instantiated.
           * @description
           * See {@link auto.$provide#service $provide.service()}.
           */
          service: invokeLater('$provide', 'service'),

          /**
           * @ngdoc method
           * @name angular.Module#value
           * @module ng
           * @param {string} name service name
           * @param {*} object Service instance object.
           * @description
           * See {@link auto.$provide#value $provide.value()}.
           */
          value: invokeLater('$provide', 'value'),

          /**
           * @ngdoc method
           * @name angular.Module#constant
           * @module ng
           * @param {string} name constant name
           * @param {*} object Constant value.
           * @description
           * Because the constant are fixed, they get applied before other provide methods.
           * See {@link auto.$provide#constant $provide.constant()}.
           */
          constant: invokeLater('$provide', 'constant', 'unshift'),

          /**
           * @ngdoc method
           * @name angular.Module#animation
           * @module ng
           * @param {string} name animation name
           * @param {Function} animationFactory Factory function for creating new instance of an
           *                                    animation.
           * @description
           *
           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
           *
           *
           * Defines an animation hook that can be later used with
           * {@link ngAnimate.$animate $animate} service and directives that use this service.
           *
           * ```js
           * module.animation('.animation-name', function($inject1, $inject2) {
           *   return {
           *     eventName : function(element, done) {
           *       //code to run the animation
           *       //once complete, then run done()
           *       return function cancellationFunction(element) {
           *         //code to cancel the animation
           *       }
           *     }
           *   }
           * })
           * ```
           *
           * See {@link ng.$animateProvider#register $animateProvider.register()} and
           * {@link ngAnimate ngAnimate module} for more information.
           */
          animation: invokeLater('$animateProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#filter
           * @module ng
           * @param {string} name Filter name.
           * @param {Function} filterFactory Factory function for creating new instance of filter.
           * @description
           * See {@link ng.$filterProvider#register $filterProvider.register()}.
           */
          filter: invokeLater('$filterProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#controller
           * @module ng
           * @param {string|Object} name Controller name, or an object map of controllers where the
           *    keys are the names and the values are the constructors.
           * @param {Function} constructor Controller constructor function.
           * @description
           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
           */
          controller: invokeLater('$controllerProvider', 'register'),

          /**
           * @ngdoc method
           * @name angular.Module#directive
           * @module ng
           * @param {string|Object} name Directive name, or an object map of directives where the
           *    keys are the names and the values are the factories.
           * @param {Function} directiveFactory Factory function for creating new instance of
           * directives.
           * @description
           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
           */
          directive: invokeLater('$compileProvider', 'directive'),

          /**
           * @ngdoc method
           * @name angular.Module#config
           * @module ng
           * @param {Function} configFn Execute this function on module load. Useful for service
           *    configuration.
           * @description
           * Use this method to register work which needs to be performed on module loading.
           * For more about how to configure services, see
           * {@link providers#provider-recipe Provider Recipe}.
           */
          config: config,

          /**
           * @ngdoc method
           * @name angular.Module#run
           * @module ng
           * @param {Function} initializationFn Execute this function after injector creation.
           *    Useful for application initialization.
           * @description
           * Use this method to register work which should be performed when the injector is done
           * loading all modules.
           */
          run: function(block) {
            runBlocks.push(block);
            return this;
          }
        };

        if (configFn) {
          config(configFn);
        }

        return moduleInstance;

        /**
         * @param {string} provider
         * @param {string} method
         * @param {String=} insertMethod
         * @returns {angular.Module}
         */
        function invokeLater(provider, method, insertMethod, queue) {
          if (!queue) queue = invokeQueue;
          return function() {
            queue[insertMethod || 'push']([provider, method, arguments]);
            return moduleInstance;
          };
        }
      });
    };
  });

}
<|endoftext|>


<commit_before>var swig = require('../lib/swig'),
  expect = require('expect.js'),
  _ = require('lodash'),
  Swig = swig.Swig;

describe('Inheritance', function () {

});
<commit_msg>remove empty test<commit_after><|endoftext|>


<commit_before>/* @flow */

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const normalize = require('normalize-path');
const loaderUtils = require('loader-utils');
const enhancedResolve = require('enhanced-resolve/lib/node');
const Module = require('./babel/module');
const transform = require('./transform');

module.exports = function loader(content: string, inputSourceMap: ?Object) {
  const {
    sourceMap,
    cacheDirectory = '.linaria-cache',
    preprocessor,
    ...rest
  } = loaderUtils.getOptions(this) || {};

  const outputFilename = path.join(
    path.isAbsolute(cacheDirectory)
      ? cacheDirectory
      : path.join(process.cwd(), cacheDirectory),
    path.relative(
      process.cwd(),
      this.resourcePath.replace(/\.[^.]+$/, '.linaria.css')
    )
  );

  const resolveSync = enhancedResolve.create.sync(
    // this._compilation is a deprecated API
    // However there seems to be no other way to access webpack's resolver
    // There is this.resolve, but it's asynchronous
    // Another option is to read the webpack.config.js, but it won't work for programmatic usage
    // This API is used by many loaders/plugins, so hope we're safe for a while
    this._compilation.options.resolve
  );

  let result;

  const originalResolveFilename = Module._resolveFilename;

  try {
    // Use webpack's resolution when evaluating modules
    Module._resolveFilename = (id, { filename }) =>
      resolveSync(path.dirname(filename), id);

    result = transform(content, {
      filename: this.resourcePath,
      inputSourceMap: inputSourceMap != null ? inputSourceMap : undefined,
      outputFilename,
      pluginOptions: rest,
      preprocessor,
    });
  } finally {
    // Restore original behaviour
    Module._resolveFilename = originalResolveFilename;
  }

  if (result.cssText) {
    let { cssText } = result;

    if (sourceMap) {
      cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(
        result.cssSourceMapText || ''
      ).toString('base64')}*/`;
    }

    if (result.dependencies && result.dependencies.length) {
      result.dependencies.forEach(dep => {
        try {
          const f = resolveSync(path.dirname(this.resourcePath), dep);

          this.addDependency(f);
        } catch (e) {
          console.warn(`[linaria] failed to add dependency for: ${dep}`, e);
        }
      });
    }

    // Read the file first to compare the content
    // Write the new content only if it's changed
    // This will prevent unnecessary WDS reloads
    let currentCssText;

    try {
      currentCssText = fs.readFileSync(outputFilename, 'utf-8');
    } catch (e) {
      // Ignore error
    }

    if (currentCssText !== cssText) {
      mkdirp.sync(path.dirname(outputFilename));
      fs.writeFileSync(outputFilename, cssText);
    }

    this.callback(
      null,
      `${result.code}\n\nrequire("${normalize(outputFilename)}")`,
      result.sourceMap
    );
    return;
  }

  this.callback(null, result.code, result.sourceMap);
};
<commit_msg>fix: use only aliases from webpack options<commit_after>/* @flow */

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const normalize = require('normalize-path');
const loaderUtils = require('loader-utils');
const enhancedResolve = require('enhanced-resolve/lib/node');
const Module = require('./babel/module');
const transform = require('./transform');

module.exports = function loader(content: string, inputSourceMap: ?Object) {
  const {
    sourceMap,
    cacheDirectory = '.linaria-cache',
    preprocessor,
    ...rest
  } = loaderUtils.getOptions(this) || {};

  const outputFilename = path.join(
    path.isAbsolute(cacheDirectory)
      ? cacheDirectory
      : path.join(process.cwd(), cacheDirectory),
    path.relative(
      process.cwd(),
      this.resourcePath.replace(/\.[^.]+$/, '.linaria.css')
    )
  );

  const resolveSync = enhancedResolve.create.sync(
    // this._compilation is a deprecated API
    // However there seems to be no other way to access webpack's resolver
    // There is this.resolve, but it's asynchronous
    // Another option is to read the webpack.config.js, but it won't work for programmatic usage
    // This API is used by many loaders/plugins, so hope we're safe for a while
    this._compilation.options.resolve
      ? { alias: this._compilation.options.resolve.alias }
      : undefined
  );

  let result;

  const originalResolveFilename = Module._resolveFilename;

  try {
    // Use webpack's resolution when evaluating modules
    Module._resolveFilename = (id, { filename }) =>
      resolveSync(path.dirname(filename), id);

    result = transform(content, {
      filename: this.resourcePath,
      inputSourceMap: inputSourceMap != null ? inputSourceMap : undefined,
      outputFilename,
      pluginOptions: rest,
      preprocessor,
    });
  } finally {
    // Restore original behaviour
    Module._resolveFilename = originalResolveFilename;
  }

  if (result.cssText) {
    let { cssText } = result;

    if (sourceMap) {
      cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(
        result.cssSourceMapText || ''
      ).toString('base64')}*/`;
    }

    if (result.dependencies && result.dependencies.length) {
      result.dependencies.forEach(dep => {
        try {
          const f = resolveSync(path.dirname(this.resourcePath), dep);

          this.addDependency(f);
        } catch (e) {
          console.warn(`[linaria] failed to add dependency for: ${dep}`, e);
        }
      });
    }

    // Read the file first to compare the content
    // Write the new content only if it's changed
    // This will prevent unnecessary WDS reloads
    let currentCssText;

    try {
      currentCssText = fs.readFileSync(outputFilename, 'utf-8');
    } catch (e) {
      // Ignore error
    }

    if (currentCssText !== cssText) {
      mkdirp.sync(path.dirname(outputFilename));
      fs.writeFileSync(outputFilename, cssText);
    }

    this.callback(
      null,
      `${result.code}\n\nrequire("${normalize(outputFilename)}")`,
      result.sourceMap
    );
    return;
  }

  this.callback(null, result.code, result.sourceMap);
};
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
const path = require('path');
const util = require('util');
const mongoose = require('mongoose');
const walk = require('walk');
const toSchema = require('./schema').toSchema;

String.prototype.capitaliseFirstLetter = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

function throwError(message) {
  throw new Error('[Error]:[Mongoose-Model-Loader]: ' + message);
}

function validateOptions(options) {
  const sourcePath = options.sourcePath;
  const fileExtension = options.fileExtension;
  const excludedFiles = options.excludedFiles;

  if (!sourcePath) {
    throwError('Source path is required');
  }

  if (fileExtension && !util.isString(fileExtension)) {
    throwError('File extension must be a string');
  }

  if (excludedFiles && !util.isArray(excludedFiles)) {
    throwError('Excluded files must be an array');
  }
}

function isValidFileExtension(fileName, fileExtension) {
  var validFileExtension = fileName.match(new RegExp(fileExtension));
  if (!validFileExtension) {
    return false;
  }

  return true;
}

function notExcludedFile(fileName, excludedFiles) {
  return excludedFiles.find(excludedFile => excludedFile !== fileName);
}

function checkFile(fileExtension, excludedFiles) {
  return (root, fileStat, next) => {
    const fileName = fileStat.name;
    fs.readFile(path.resolve(root, fileName), () => {
      const shouldRequireModel =
        validFileExtension(fileName, fileExtension) &&
        notExcludedFile(fileName, excludedFiles);

      if (shouldRequireModel) {
        const modelName = getName(fileName).capitaliseFirstLetter();
        const model = require(mainPath + '/' + fileName);
        const schema = toSchema(model);
        mongoose.model(modelName, schema);
      }

      next();
    });
  };
}

function load(options) {
  return new Promise((resolve, reject) => {
    try {
      validateOptions(options);
      const sourcePath = options.sourcePath;
      const fileExtension = options.fileExtension || '.js';
      const excludedFiles = options.excludedFiles || [];
      const walker = walk.walk(sourcePath, { followLinks: false });

      walker.on('file', checkFile(fileExtension, excludedFiles));
      walker.on('error', () => reject());
      walker.on('end', () => resolve());
    } catch (e) {
      reject(e);
    }
  });
}

exports.loader = load;
<commit_msg>wrong function name<commit_after>'use strict';
const fs = require('fs');
const path = require('path');
const util = require('util');
const mongoose = require('mongoose');
const walk = require('walk');
const toSchema = require('./schema').toSchema;

String.prototype.capitaliseFirstLetter = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

function throwError(message) {
  throw new Error('[Error]:[Mongoose-Model-Loader]: ' + message);
}

function validateOptions(options) {
  const sourcePath = options.sourcePath;
  const fileExtension = options.fileExtension;
  const excludedFiles = options.excludedFiles;

  if (!sourcePath) {
    throwError('Source path is required');
  }

  if (fileExtension && !util.isString(fileExtension)) {
    throwError('File extension must be a string');
  }

  if (excludedFiles && !util.isArray(excludedFiles)) {
    throwError('Excluded files must be an array');
  }
}

function isValidFileExtension(fileName, fileExtension) {
  var validFileExtension = fileName.match(new RegExp(fileExtension));
  if (!validFileExtension) {
    return false;
  }

  return true;
}

function notExcludedFile(fileName, excludedFiles) {
  return excludedFiles.find(excludedFile => excludedFile !== fileName);
}

function checkFile(fileExtension, excludedFiles) {
  return (root, fileStat, next) => {
    const fileName = fileStat.name;
    fs.readFile(path.resolve(root, fileName), () => {
      const shouldRequireModel =
        isValidFileExtension(fileName, fileExtension) &&
        notExcludedFile(fileName, excludedFiles);

      if (shouldRequireModel) {
        const modelName = getName(fileName).capitaliseFirstLetter();
        const model = require(mainPath + '/' + fileName);
        const schema = toSchema(model);
        mongoose.model(modelName, schema);
      }

      next();
    });
  };
}

function load(options) {
  return new Promise((resolve, reject) => {
    try {
      validateOptions(options);
      const sourcePath = options.sourcePath;
      const fileExtension = options.fileExtension || '.js';
      const excludedFiles = options.excludedFiles || [];
      const walker = walk.walk(sourcePath, { followLinks: false });

      walker.on('file', checkFile(fileExtension, excludedFiles));
      walker.on('error', () => reject());
      walker.on('end', () => resolve());
    } catch (e) {
      reject(e);
    }
  });
}

exports.loader = load;
<|endoftext|>


<commit_before>/*global phantom:true*/
/*global require:true*/
/*global window:true*/

/*
phantom args sent from critical.js:
	[0] - url
	[1] - filename
	[2] - width of page
	[3] - height of page
*/
(function(){
	"use strict";

	var site = phantom.args[0],
		filename = phantom.args[1],
		width = phantom.args[2],
		height = phantom.args[3];

	var system = require( "system" );

	var errorHandler = function(msg, trace) {
		var msgStack = ["PHANTOM ERROR: " + msg];
		if (trace && trace.length) {
			msgStack.push("TRACE:");
			trace.forEach(function(t) {
				msgStack.push(" -> " + (t.file || t.sourceURL) + ": " + t.line + (t.function ? " (in function " + t.function +")" : ""));
			});
		}
		system.stderr.write( msgStack.join("\n") );
		phantom.exit(1);
	};

	var page = require( "webpage" ).create();
	var cc = require( "./criticalCSS" );

	/**
	 * Wait until the test condition is true or a timeout occurs. Useful for waiting
	 * on a server response or for a ui change (fadeIn, etc.) to occur.
	 *
	 * @param testFx javascript condition that evaluates to a boolean,
	 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
	 * as a callback function.
	 * @param onReady what to do when testFx condition is fulfilled,
	 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
	 * as a callback function.
	 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
	 */
	var waitFor = function(testFx, onReady, timeOutMillis) {
		var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
			start = new Date().getTime(),
			condition = false,
			interval = setInterval(function() {
				if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
					// If not time-out yet and condition not yet fulfilled
					condition = testFx();
				} else {
					if(!condition) {
						// If condition still not fulfilled (timeout but condition is 'false')
						throw new Error( "The filename you have given is not found at this url." );
					} else {
						// Condition fulfilled (timeout and/or condition is 'true')
						onReady();
						clearInterval(interval);
					}
				}
			}, 250); //< repeat check every 250ms
	};

	phantom.onError = errorHandler;
	page.onError = errorHandler;
	page.onConsoleMessage = function(msg) {
		system.stdout.write( "Console output: " + msg );
	};

	page.viewportSize = {  width: width , height: height };

	page.open( site, function( status ){
		if( status === "success" ){
			waitFor(function(){
				return page.evaluate(function(file){
					var styleSheets = Array.prototype.slice.call(window.document.styleSheets);
					return styleSheets.some(function(sheet){
						return !!sheet.href.match(file);
					});
				}, filename);
			}, function(){
				var maxTop = page.evaluate(function(){
					return window.innerHeight;
				});

				var stylesheets = page.evaluate(function(){
					return window.document.styleSheets;
				});

				var opts = {
					sheets: stylesheets,
					maxTop: maxTop,
					criticalSelectorList: function( list, maxTop ){
						return page.evaluate( function( selectors, maxTop ){
							var critical = [];
							for( var i = 0, l = selectors.length; i < l; i++ ){
								var elem = null;
								try {
									elem = window.document.querySelector( selectors[i] );
								} catch (e){}

								if( elem && elem.offsetTop <= maxTop ){
									critical.push( selectors[ i ] );
								}
							}
							return critical;
						}, list, maxTop );
					},
					isMatchingRule: function(rule){
						return page.evaluate(function(rule){
							var media = rule.media;
							return media && window.matchMedia( media.mediaText ).matches;
						}, rule);
					}

				};

				var crit = cc.criticalCSS( filename, opts );
				if( crit.length === 0 ){
					throw new Error( "criticalCSS didn't run or no critical css, that seems unlikely" );
				} else {
					system.stdout.write(crit);
					phantom.exit();
				}
			});

		} else {
			throw new Error( "Page didn't open: " + site );
		}
	});

}());
<commit_msg>Comment<commit_after>/*global phantom:true*/
/*global require:true*/
/*global window:true*/

/*
phantom args sent from critical.js:
	[0] - url
	[1] - filename
	[2] - width of page
	[3] - height of page
*/
(function(){
	"use strict";

	var site = phantom.args[0],
		filename = phantom.args[1],
		width = phantom.args[2],
		height = phantom.args[3];

	var system = require( "system" );

	var errorHandler = function(msg, trace) {
		var msgStack = ["PHANTOM ERROR: " + msg];
		if (trace && trace.length) {
			msgStack.push("TRACE:");
			trace.forEach(function(t) {
				msgStack.push(" -> " + (t.file || t.sourceURL) + ": " + t.line + (t.function ? " (in function " + t.function +")" : ""));
			});
		}
		system.stderr.write( msgStack.join("\n") );
		phantom.exit(1);
	};

	var page = require( "webpage" ).create();
	var cc = require( "./criticalCSS" );

	/**
	 * Wait until the test condition is true or a timeout occurs. Useful for waiting
	 * on a server response or for a ui change (fadeIn, etc.) to occur.
	 *
	 * @param testFx javascript condition that evaluates to a boolean,
	 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
	 * as a callback function.
	 * @param onReady what to do when testFx condition is fulfilled,
	 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
	 * as a callback function.
	 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
	 */
	var waitFor = function(testFx, onReady, timeOutMillis) {
		var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
			start = new Date().getTime(),
			condition = false,
			interval = setInterval(function() {
				if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
					// If not time-out yet and condition not yet fulfilled
					condition = testFx();
				} else {
					if(!condition) {
						// If condition still not fulfilled (timeout but condition is 'false')
						throw new Error( "The filename you have given is not found at this url." );
					} else {
						// Condition fulfilled (timeout and/or condition is 'true')
						onReady();
						clearInterval(interval);
					}
				}
			}, 250); //< repeat check every 250ms
	};

	phantom.onError = errorHandler;
	page.onError = errorHandler;
	page.onConsoleMessage = function(msg) {
		system.stdout.write( "Console output: " + msg );
	};

	page.viewportSize = {  width: width , height: height };

	page.open( site, function( status ){
		if( status === "success" ){
			waitFor(function(){
				// Wait for document.stylesheets to include the filename we're looking for before running
				return page.evaluate(function(file){
					return Array.prototype.slice.call(window.document.styleSheets).some(function(sheet){
						return !!sheet.href.match(file);
					});
				}, filename);
			}, function(){
				var maxTop = page.evaluate(function(){
					return window.innerHeight;
				});

				var stylesheets = page.evaluate(function(){
					return window.document.styleSheets;
				});

				var opts = {
					sheets: stylesheets,
					maxTop: maxTop,
					criticalSelectorList: function( list, maxTop ){
						return page.evaluate( function( selectors, maxTop ){
							var critical = [];
							for( var i = 0, l = selectors.length; i < l; i++ ){
								var elem = null;
								try {
									elem = window.document.querySelector( selectors[i] );
								} catch (e){}

								if( elem && elem.offsetTop <= maxTop ){
									critical.push( selectors[ i ] );
								}
							}
							return critical;
						}, list, maxTop );
					},
					isMatchingRule: function(rule){
						return page.evaluate(function(rule){
							var media = rule.media;
							return media && window.matchMedia( media.mediaText ).matches;
						}, rule);
					}

				};

				var crit = cc.criticalCSS( filename, opts );
				if( crit.length === 0 ){
					throw new Error( "criticalCSS didn't run or no critical css, that seems unlikely" );
				} else {
					system.stdout.write(crit);
					phantom.exit();
				}
			});

		} else {
			throw new Error( "Page didn't open: " + site );
		}
	});

}());
<|endoftext|>


<commit_before>/**
 * Global dependencies.
 * @global {Object} document - DOM
 */

var devnull = function() {},
    bundleIdCache = {},
    bundleResultCache = {},
    bundleCallbackQueue = {};

/**
 * Subscribe to bundle load event.
 * @param {string[]} bundleIds - Bundle ids
 * @param {Function} callbackFn - The callback function
 */
function subscribe(bundleIds, callbackFn) {
  // listify
  bundleIds = bundleIds.push ? bundleIds : [bundleIds];

  var depsNotFound = [],
      i = bundleIds.length,
      numWaiting = i,
      fn,
      bundleId,
      r,
      q;

  // define callback function
  fn = function (bundleId, pathsNotFound) {
    if (pathsNotFound.length) depsNotFound.push(bundleId);

    numWaiting--;
    if (!numWaiting) callbackFn(depsNotFound);
  };

  // register callback
  while (i--) {
    bundleId = bundleIds[i];

    // execute callback if in result cache
    r = bundleResultCache[bundleId];
    if (r) {
      fn(bundleId, r);
      continue;
    }

    // add to callback queue
    q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
    q.push(fn);
  }
}

/**
 * Publish bundle load event.
 * @param {string} bundleId - Bundle id
 * @param {string[]} pathsNotFound - List of files not found
 */
function publish(bundleId, pathsNotFound) {
  // exit if id isn't defined
  if (!bundleId) return;

  var q = bundleCallbackQueue[bundleId];

  // cache result
  bundleResultCache[bundleId] = pathsNotFound;

  // exit if queue is empty
  if (!q) return;

  // empty callback queue
  while (q.length) {
    q[0](bundleId, pathsNotFound);
    q.splice(0, 1);
  }
}

/**
 * Load individual file.
 * @param {string} path - The file path
 * @param {Function} callbackFn - The callback function
 */
function loadFile(path, callbackFn, args, numTries) {
  var doc = document,
      async = args.async,
      maxTries = (args.numRetries || 0) + 1,
      beforeCallbackFn = args.before || devnull,
      isCss,
      e;

  numTries = numTries || 0;

  if (/(^css!|\.css$)/.test(path)) {
    isCss = true;

    // css
    e = doc.createElement('link');
    e.rel = 'stylesheet';
    e.href = path.replace(/^css!/, '');  // remove "css!" prefix
  } else {
    // javascript
    e = doc.createElement('script');
    e.src = path;
    e.async = async === undefined ? true : async;
  }

  e.onload = e.onerror = e.onbeforeload = function (ev) {
    var result = ev.type[0];

    // Note: The following code isolates IE using `hideFocus` and treats empty
    // stylesheets as failures to get around lack of onerror support
    if (isCss && 'hideFocus' in e) {
      try {
        if (!e.sheet.cssText.length) result = 'e';
      } catch (x) {
        // sheets objects created from load errors don't allow access to
        // `cssText`
        result = 'e';
      }
    }

    // handle retries in case of load failure
    if (result == 'e') {
      // increment counter
      numTries += 1;

      // exit function and try again
      if (numTries < maxTries) {
        return loadFile(path, callbackFn, args, numTries);
      }
    }

    // execute callback
    callbackFn(path, result, ev.defaultPrevented);
  };

  // add to document (unless callback returns `false`)
  if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);
}

/**
 * Load multiple files.
 * @param {string[]} paths - The file paths
 * @param {Function} callbackFn - The callback function
 */
function loadFiles(paths, callbackFn, args) {
  // listify paths
  paths = paths.push ? paths : [paths];

  var numWaiting = paths.length,
      x = numWaiting,
      pathsNotFound = [],
      fn,
      i;

  // define callback function
  fn = function(path, result, defaultPrevented) {
    // handle error
    if (result == 'e') pathsNotFound.push(path);

    // handle beforeload event. If defaultPrevented then that means the load
    // will be blocked (ex. Ghostery/ABP on Safari)
    if (result == 'b') {
      if (defaultPrevented) pathsNotFound.push(path);
      else return;
    }

    numWaiting--;
    if (!numWaiting) callbackFn(pathsNotFound);
  };

  // load scripts
  for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}

/**
 * Initiate script load and register bundle.
 * @param {(string|string[])} paths - The file paths
 * @param {(string|Function)} [arg1] - The bundleId or success callback
 * @param {Function} [arg2] - The success or error callback
 * @param {Function} [arg3] - The error callback
 */
function loadjs(paths, arg1, arg2) {
  var bundleId,
      args;

  // bundleId (if string)
  if (arg1 && arg1.trim) bundleId = arg1;

  // args (default is {})
  args = (bundleId ? arg2 : arg1) || {};

  // throw error if bundle is already defined
  if (bundleId) {
    if (bundleId in bundleIdCache) {
      throw "LoadJS";
    } else {
      bundleIdCache[bundleId] = true;
    }
  }

  // load scripts
  loadFiles(paths, function (pathsNotFound) {
    // success and error callbacks
    if (pathsNotFound.length) (args.error || devnull)(pathsNotFound);
    else (args.success || devnull)();

    // publish bundle load event
    publish(bundleId, pathsNotFound);
  }, args);
}

/**
 * Execute callbacks when dependencies have been satisfied.
 * @param {(string|string[])} deps - List of bundle ids
 * @param {Object} args - success/error arguments
 */
loadjs.ready = function ready(deps, args) {
  // subscribe to bundle load event
  subscribe(deps, function (depsNotFound) {
    // execute callbacks
    if (typeof args === 'function')
      args();
    if (depsNotFound.length) (args.error || devnull)(depsNotFound);
    else (args.success || devnull)();
  });

  return loadjs;
};

/**
 * Manually satisfy bundle dependencies.
 * @param {string} bundleId - The bundle id
 */
loadjs.done = function done(bundleId) {
  publish(bundleId, []);
};

/**
 * Reset loadjs dependencies statuses
 */
loadjs.reset = function reset() {
  bundleIdCache = {};
  bundleResultCache = {};
  bundleCallbackQueue = {};
};

/**
 * Determine if bundle has already been defined
 * @param String} bundleId - The bundle id
 */
loadjs.isDefined = function isDefined(bundleId) {
  return bundleId in bundleIdCache;
};

// export
return loadjs;
<commit_msg>added callback function support to loadjs(), refactored code<commit_after>/**
 * Global dependencies.
 * @global {Object} document - DOM
 */

var devnull = function() {},
    bundleIdCache = {},
    bundleResultCache = {},
    bundleCallbackQueue = {};

/**
 * Subscribe to bundle load event.
 * @param {string[]} bundleIds - Bundle ids
 * @param {Function} callbackFn - The callback function
 */
function subscribe(bundleIds, callbackFn) {
  // listify
  bundleIds = bundleIds.push ? bundleIds : [bundleIds];

  var depsNotFound = [],
      i = bundleIds.length,
      numWaiting = i,
      fn,
      bundleId,
      r,
      q;

  // define callback function
  fn = function (bundleId, pathsNotFound) {
    if (pathsNotFound.length) depsNotFound.push(bundleId);

    numWaiting--;
    if (!numWaiting) callbackFn(depsNotFound);
  };

  // register callback
  while (i--) {
    bundleId = bundleIds[i];

    // execute callback if in result cache
    r = bundleResultCache[bundleId];
    if (r) {
      fn(bundleId, r);
      continue;
    }

    // add to callback queue
    q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
    q.push(fn);
  }
}

/**
 * Publish bundle load event.
 * @param {string} bundleId - Bundle id
 * @param {string[]} pathsNotFound - List of files not found
 */
function publish(bundleId, pathsNotFound) {
  // exit if id isn't defined
  if (!bundleId) return;

  var q = bundleCallbackQueue[bundleId];

  // cache result
  bundleResultCache[bundleId] = pathsNotFound;

  // exit if queue is empty
  if (!q) return;

  // empty callback queue
  while (q.length) {
    q[0](bundleId, pathsNotFound);
    q.splice(0, 1);
  }
}

/**
 * Execute callbacks.
 * @param {Object or Function} args - The callback args
 * @param {strin[]} depsNotFound - List of dependencies not found
 */
function executeCallbacks(args, depsNotFound) {
  // accept function as argument
  if (args.call) args = {success: args};

  // success and error callbacks
  if (depsNotFound.length) (args.error || devnull)(depsNotFound);
  else (args.success || devnull)();
}

/**
 * Load individual file.
 * @param {string} path - The file path
 * @param {Function} callbackFn - The callback function
 */
function loadFile(path, callbackFn, args, numTries) {
  var doc = document,
      async = args.async,
      maxTries = (args.numRetries || 0) + 1,
      beforeCallbackFn = args.before || devnull,
      isCss,
      e;

  numTries = numTries || 0;

  if (/(^css!|\.css$)/.test(path)) {
    isCss = true;

    // css
    e = doc.createElement('link');
    e.rel = 'stylesheet';
    e.href = path.replace(/^css!/, '');  // remove "css!" prefix
  } else {
    // javascript
    e = doc.createElement('script');
    e.src = path;
    e.async = async === undefined ? true : async;
  }

  e.onload = e.onerror = e.onbeforeload = function (ev) {
    var result = ev.type[0];

    // Note: The following code isolates IE using `hideFocus` and treats empty
    // stylesheets as failures to get around lack of onerror support
    if (isCss && 'hideFocus' in e) {
      try {
        if (!e.sheet.cssText.length) result = 'e';
      } catch (x) {
        // sheets objects created from load errors don't allow access to
        // `cssText`
        result = 'e';
      }
    }

    // handle retries in case of load failure
    if (result == 'e') {
      // increment counter
      numTries += 1;

      // exit function and try again
      if (numTries < maxTries) {
        return loadFile(path, callbackFn, args, numTries);
      }
    }

    // execute callback
    callbackFn(path, result, ev.defaultPrevented);
  };

  // add to document (unless callback returns `false`)
  if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);
}

/**
 * Load multiple files.
 * @param {string[]} paths - The file paths
 * @param {Function} callbackFn - The callback function
 */
function loadFiles(paths, callbackFn, args) {
  // listify paths
  paths = paths.push ? paths : [paths];

  var numWaiting = paths.length,
      x = numWaiting,
      pathsNotFound = [],
      fn,
      i;

  // define callback function
  fn = function(path, result, defaultPrevented) {
    // handle error
    if (result == 'e') pathsNotFound.push(path);

    // handle beforeload event. If defaultPrevented then that means the load
    // will be blocked (ex. Ghostery/ABP on Safari)
    if (result == 'b') {
      if (defaultPrevented) pathsNotFound.push(path);
      else return;
    }

    numWaiting--;
    if (!numWaiting) callbackFn(pathsNotFound);
  };

  // load scripts
  for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}

/**
 * Initiate script load and register bundle.
 * @param {(string|string[])} paths - The file paths
 * @param {(string|Function)} [arg1] - The bundleId or success callback
 * @param {Function} [arg2] - The success or error callback
 * @param {Function} [arg3] - The error callback
 */
function loadjs(paths, arg1, arg2) {
  var bundleId,
      args;

  // bundleId (if string)
  if (arg1 && arg1.trim) bundleId = arg1;

  // args (default is {})
  args = (bundleId ? arg2 : arg1) || {};

  // throw error if bundle is already defined
  if (bundleId) {
    if (bundleId in bundleIdCache) {
      throw "LoadJS";
    } else {
      bundleIdCache[bundleId] = true;
    }
  }

  // load scripts
  loadFiles(paths, function (pathsNotFound) {
    // execute callbacks
    executeCallbacks(args, pathsNotFound);

    // publish bundle load event
    publish(bundleId, pathsNotFound);
  }, args);
}

/**
 * Execute callbacks when dependencies have been satisfied.
 * @param {(string|string[])} deps - List of bundle ids
 * @param {Object} args - success/error arguments
 */
loadjs.ready = function ready(deps, args) {
  // subscribe to bundle load event
  subscribe(deps, function (depsNotFound) {
    // execute callbacks
    executeCallbacks(args, depsNotFound);
  });

  return loadjs;
};

/**
 * Manually satisfy bundle dependencies.
 * @param {string} bundleId - The bundle id
 */
loadjs.done = function done(bundleId) {
  publish(bundleId, []);
};

/**
 * Reset loadjs dependencies statuses
 */
loadjs.reset = function reset() {
  bundleIdCache = {};
  bundleResultCache = {};
  bundleCallbackQueue = {};
};

/**
 * Determine if bundle has already been defined
 * @param String} bundleId - The bundle id
 */
loadjs.isDefined = function isDefined(bundleId) {
  return bundleId in bundleIdCache;
};

// export
return loadjs;
<|endoftext|>


<commit_before>css = {
  padding:        0,
  margin:         0,
  width:          '30%',
  top:            '40%',
  left:           '35%',
  textAlign:      'center',
  color:          '#000',
  border:         '3px solid #f4511e',
  backgroundColor:'#fff',
  cursor:         'wait'
};
$.blockUI({ message: '
Waiting for opponent...
', fadeOut: 0, css: css});

var buildings = [
  { name : "Hacker", base : 15, power: .1 },
  { name : "Grandma", base : 100, power: 1 },
  { name : "Farm", base : 1100, power: 8 },
  { name : "Mine", base : 12000, power: 47 },
  { name : "Factory", base : 130000, power: 260 },
  { name : "Bank", base : 1400000, power: 1400 },
  { name : "Temple", base : 20000000, power: 7800 },
  { name : "Wizard Tower", base : 330000000, power: 44000 },
  { name : "Shipment", base : 5100000000, power: 260000 },
  { name : "Alchemy Lab", base : 75000000000, power: 1600000 },
  { name : "Portal", base : 1000000000000, power: 10000000 },
  { name : "Time Machine", base : 14000000000000, power: 65000000 },
  { name : "Antimatter Condenser", base : 170000000000000, power: 430000000 },
  { name : "Prism", base : 2100000000000000, power: 2900000000}
];
var scale = 1.1;

var points = 0,
  gross = 0,
  ogross = 0,
  freq = [];
for (var i = 0; i < buildings.length; i++) {
  freq.push(0);
}

for (var i = 0; i < buildings.length; i++) {
  $("#buildings").find('tbody').append(
    $('
').append(
      $('')
        .attr('id', 'freq' + i.toString())
        .text('0')
    ).append(
      $('').append(
        $('<button>')
          .attr('class', 'button')
          .attr('onClick', 'buyBuilding(' + i.toString() + ')')
          .text(buildings[i].name)
      )
    ).append(
      $('')
        .attr('id', 'price' + i.toString())
        .text(buildings[i].base.toString())
    )
  );
}

function single() {
  ++points;
  ++gross;
  document.getElementById("points").innerHTML = points;
  document.getElementById("gross").innerHTML = gross;
  checkWin();
}

function updatePoints() {
  for (var i = 0; i < buildings.length; i++) {
    points += buildings[i].power * freq[i];
    gross += buildings[i].power * freq[i];
  }
  document.getElementById("points").innerHTML = points;
  document.getElementById("gross").innerHTML = gross;
  checkWin();
}

function buyBuilding(idx) {
  var name = buildings[idx].name,
    base = buildings[idx].base,
    num = freq[idx];
  var price = base * Math.pow(scale, num);
  if (price <= points) {
    ++freq[idx];
    points -= price;
    gross += price;
    document.getElementById("points").innerHTML = points;
    document.getElementById("freq" + idx.toString()).innerHTML = freq[idx];
    document.getElementById("price" + idx.toString()).innerHTML = price * scale;
  }
}

window.setInterval(function(){
  updatePoints();
}, 50);

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function update() {
  document.getElementById("gross").innerHTML = gross;
  document.getElementById("ogross").innerHTML = ogross;
}

//globals
var urlsplit = window.location.href.split('/'),
    roomid = urlsplit[urlsplit.length - 1],
    pid,
    win,
    limit;

var socket = io();

if (document.cookie && readCookie('roomid') == roomid) {
  pid = readCookie('pid');
  socket.emit('auth', {'pid': pid, 'roomid': roomid});
  gross = parseInt(readCookie('score'));
  ogross = parseInt(readCookie('oscore'));
  win = readCookie('win');
  limit = parseFloat(readCookie('limit'));
  update();
} else {
  socket.emit('request-pid', roomid);
}

socket.on('dangit', function() { window.location.href = '/';}); //do stuff

socket.on('authorized', function(obj) {
  win = obj.win;
  document.cookie = 'win=' + win;
  limit = obj.limit;
  document.cookie = 'limit=' + limit.toString();
}); //do stuff

socket.on('score', function(oscore) {
  ogross = oscore;
  update();
});

socket.on('pid', function(newpid) {
  pid = newpid;
  document.cookie = 'pid=' + newpid + ' ; roomid=' + roomid; //add to this
  document.cookie = 'roomid=' + roomid;
  document.cookie = 'score=' + gross;
  document.cookie = 'oscore=' + ogross;
  socket.emit('auth', {'pid': pid, 'roomid': roomid});
});

window.setInterval(function() {
  socket.emit('score', {'score' : gross, 'roomid' : roomid});
}, 500);
window.setInterval(function() {
  document.cookie= 'score=' + gross;
  document.cookie="oscore=" + ogross;
}, 1000);

function checkWin() {
  if (win == 'points') {
    if (points >= limit) {
      socket.emit('win', {'pid' : pid, 'roomid' : roomid});
    }
  } else {

  }
}

socket.on('winner', function(winpid) {
  if (pid == winpid) {
    alert('You won! Congratulations!');
  } else {
    alert('You lost. Your ancestors are ashamed of you...');
  }
  socket.disconnect();
});

socket.on('start', function() {
  var timer = 5;
  (function t_minus() {
    $.blockUI({ fadeIn: 0, fadeOut: 0,
                message: '
' + timer.toString() + '
', css: css});
    --timer;
    if (timer >= 0) {
      setTimeout(function() {
        t_minus();
      }, 1000);
    } else {
      $.unblockUI({ fadeOut: 0 });
    }
  }());
});
<commit_msg>Rounded numbers<commit_after>css = {
  padding:        0,
  margin:         0,
  width:          '30%',
  top:            '40%',
  left:           '35%',
  textAlign:      'center',
  color:          '#000',
  border:         '3px solid #f4511e',
  backgroundColor:'#fff',
  cursor:         'wait'
};
$.blockUI({ message: '
Waiting for opponent...
', fadeOut: 0, css: css});

var buildings = [
  { name : "Hacker", base : 15, power: .1 },
  { name : "Grandma", base : 100, power: 1 },
  { name : "Farm", base : 1100, power: 8 },
  { name : "Mine", base : 12000, power: 47 },
  { name : "Factory", base : 130000, power: 260 },
  { name : "Bank", base : 1400000, power: 1400 },
  { name : "Temple", base : 20000000, power: 7800 },
  { name : "Wizard Tower", base : 330000000, power: 44000 },
  { name : "Shipment", base : 5100000000, power: 260000 },
  { name : "Alchemy Lab", base : 75000000000, power: 1600000 },
  { name : "Portal", base : 1000000000000, power: 10000000 },
  { name : "Time Machine", base : 14000000000000, power: 65000000 },
  { name : "Antimatter Condenser", base : 170000000000000, power: 430000000 },
  { name : "Prism", base : 2100000000000000, power: 2900000000}
];
var scale = 1.1;

var points = 0,
  gross = 0,
  ogross = 0,
  freq = [];
for (var i = 0; i < buildings.length; i++) {
  freq.push(0);
}

for (var i = 0; i < buildings.length; i++) {
  $("#buildings").find('tbody').append(
    $('
').append(
      $('')
        .attr('id', 'freq' + i.toString())
        .text('0')
    ).append(
      $('').append(
        $('<button>')
          .attr('class', 'button')
          .attr('onClick', 'buyBuilding(' + i.toString() + ')')
          .text(buildings[i].name)
      )
    ).append(
      $('')
        .attr('id', 'price' + i.toString())
        .text(buildings[i].base.toString())
    )
  );
}

function single() {
  ++points;
  ++gross;
  document.getElementById("points").innerHTML = Math.round(points);
  document.getElementById("gross").innerHTML = Math.round(gross);
  checkWin();
}

function updatePoints() {
  for (var i = 0; i < buildings.length; i++) {
    points += buildings[i].power * freq[i];
    gross += buildings[i].power * freq[i];
  }
  document.getElementById("points").innerHTML = Math.round(points);
  document.getElementById("gross").innerHTML = Math.round(gross);
  checkWin();
}

function buyBuilding(idx) {
  var name = buildings[idx].name,
    base = buildings[idx].base,
    num = freq[idx];
  var price = base * Math.pow(scale, num);
  if (price <= points) {
    ++freq[idx];
    points -= price;
    gross += price;
    document.getElementById("points").innerHTML = points;
    document.getElementById("freq" + idx.toString()).innerHTML = freq[idx];
    document.getElementById("price" + idx.toString()).innerHTML = Math.round(price * scale);
  }
}

window.setInterval(function(){
  updatePoints();
}, 50);

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function update() {
  document.getElementById("gross").innerHTML = Math.round(gross);
  document.getElementById("ogross").innerHTML = Math.round(ogross);
}

//globals
var urlsplit = window.location.href.split('/'),
    roomid = urlsplit[urlsplit.length - 1],
    pid,
    win,
    limit;

var socket = io();

if (document.cookie && readCookie('roomid') == roomid) {
  pid = readCookie('pid');
  socket.emit('auth', {'pid': pid, 'roomid': roomid});
  gross = parseInt(readCookie('score'));
  ogross = parseInt(readCookie('oscore'));
  win = readCookie('win');
  limit = parseFloat(readCookie('limit'));
  update();
} else {
  socket.emit('request-pid', roomid);
}

socket.on('dangit', function() { window.location.href = '/';}); //do stuff

socket.on('authorized', function(obj) {
  win = obj.win;
  document.cookie = 'win=' + win;
  limit = obj.limit;
  document.cookie = 'limit=' + limit.toString();
}); //do stuff

socket.on('score', function(oscore) {
  ogross = oscore;
  update();
});

socket.on('pid', function(newpid) {
  pid = newpid;
  document.cookie = 'pid=' + newpid + ' ; roomid=' + roomid; //add to this
  document.cookie = 'roomid=' + roomid;
  document.cookie = 'score=' + gross;
  document.cookie = 'oscore=' + ogross;
  socket.emit('auth', {'pid': pid, 'roomid': roomid});
});

window.setInterval(function() {
  socket.emit('score', {'score' : gross, 'roomid' : roomid});
}, 500);
window.setInterval(function() {
  document.cookie= 'score=' + gross;
  document.cookie="oscore=" + ogross;
}, 1000);

function checkWin() {
  if (win == 'points') {
    if (points >= limit) {
      socket.emit('win', {'pid' : pid, 'roomid' : roomid});
    }
  } else {

  }
}

socket.on('winner', function(winpid) {
  if (pid == winpid) {
    alert('You won! Congratulations!');
  } else {
    alert('You lost. Your ancestors are ashamed of you...');
  }
  socket.disconnect();
});

socket.on('start', function() {
  var timer = 5;
  (function t_minus() {
    $.blockUI({ fadeIn: 0, fadeOut: 0,
                message: '
' + timer.toString() + '
', css: css});
    --timer;
    if (timer >= 0) {
      setTimeout(function() {
        t_minus();
      }, 1000);
    } else {
      $.unblockUI({ fadeOut: 0 });
    }
  }());
});
<|endoftext|>


<commit_before>

suite('Blocks', function() {

  suite('Unplug', function() {
    function assertUnpluggedNoheal(blocks) {
      // A has nothing connected to it.
      assertEquals(0, blocks.A.getChildren().length);
      // B and C are still connected.
      assertEquals(blocks.B, blocks.C.getParent());
      // B is the top of its stack.
      assertNull(blocks.B.getParent());
    }

    function assertUnpluggedHealed(blocks) {
      // A and C are connected.
      assertEquals(1, blocks.A.getChildren().length);
      assertEquals(blocks.A, blocks.C.getParent());
      // B has nothing connected to it.
      assertEquals(0, blocks.B.getChildren().length);
      // B is the top of its stack.
      assertNull(blocks.B.getParent());
    }

    setup(function() {
      Blockly.defineBlocksWithJsonArray([{
        "type": "stack_block",
        "message0": "",
        "previousStatement": null,
        "nextStatement": null
      },
      {
        "type": "row_block",
        "message0": "%1",
        "args0": [
          {
            "type": "input_value",
            "name": "INPUT"
          }
        ],
        "output": null
      }]);

      this.workspace = new Blockly.Workspace();
    });

    teardown(function() {
      delete Blockly.Blocks['stack_block'];
      delete Blockly.Blocks['row_block'];

      this.workspace.dispose();
    });

    suite('Row', function() {
      setup(function() {
        var blockA = this.workspace.newBlock('row_block');
        var blockB = this.workspace.newBlock('row_block');
        var blockC = this.workspace.newBlock('row_block');

        blockA.inputList[0].connection.connect(blockB.outputConnection);
        blockB.inputList[0].connection.connect(blockC.outputConnection);

        assertEquals(blockB, blockC.getParent());

        this.blocks = {
          A: blockA,
          B: blockB,
          C: blockC
        };
      });

      test('Don\'t heal', function() {
        this.blocks.B.unplug(false);
        assertUnpluggedNoheal(this.blocks);
      });

      test('Heal', function() {
        this.blocks.B.unplug(true);
        // Each block has only one input, and the types work.
        assertUnpluggedHealed(this.blocks);
      });

      test('Heal with bad checks', function() {
        var blocks = this.blocks;

        // A and C can't connect, but both can connect to B.
        blocks.A.inputList[0].connection.setCheck('type1');
        blocks.C.outputConnection.setCheck('type2');

        // Each block has only one input, but the types don't work.
        blocks.B.unplug(true);
        assertUnpluggedNoheal(blocks);
      });

      test('Parent has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to parent
        blocks.A.appendValueInput("INPUT").setCheck(null);
        blocks.B.unplug(true);
        assertUnpluggedHealed(blocks);
      });

      test('Middle block has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to middle block
        blocks.B.appendValueInput("INPUT").setCheck(null);
        blocks.B.unplug(true);
        assertUnpluggedNoheal(blocks);
      });

      test('Child block has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to child block
        blocks.C.appendValueInput("INPUT").setCheck(null);
        // Child block input count doesn't matter.
        blocks.B.unplug(true);
        assertUnpluggedHealed(blocks);
      });
    });

    suite('Stack', function() {
      setup(function() {
        var blockA = this.workspace.newBlock('stack_block');
        var blockB = this.workspace.newBlock('stack_block');
        var blockC = this.workspace.newBlock('stack_block');

        blockA.nextConnection.connect(blockB.previousConnection);
        blockB.nextConnection.connect(blockC.previousConnection);

        assertEquals(blockB, blockC.getParent());

        this.blocks = {
          A: blockA,
          B: blockB,
          C: blockC
        };
      });

      test('Don\'t heal', function() {
        this.blocks.B.unplug();
        assertUnpluggedNoheal(this.blocks);
      });

      test('Heal', function() {
        this.blocks.B.unplug(true);
        assertUnpluggedHealed(this.blocks);
      });

      test('Heal with bad checks', function() {
        var blocks = this.blocks;
        // A and C can't connect, but both can connect to B.
        blocks.A.nextConnection.setCheck('type1');
        blocks.C.previousConnection.setCheck('type2');

        // The types don't work.
        blocks.B.unplug(true);

        // Stack blocks unplug before checking whether the types match.
        // TODO (#1994): Check types before unplugging.
        // A has nothing connected to it.
        assertEquals(0, blocks.A.getChildren().length);
        // B has nothing connected to it.
        assertEquals(0, blocks.B.getChildren().length);
        // C has nothing connected to it.
        assertEquals(0, blocks.C.getChildren().length);
        // A is the top of its stack.
        assertNull(blocks.A.getParent());
        // B is the top of its stack.
        assertNull(blocks.B.getParent());
        // C is the top of its stack.
        assertNull(blocks.C.getParent());
      });
    });
  });
});
<commit_msg>Fix test (matching fix in jsunit tests)<commit_after>

suite('Blocks', function() {

  suite('Unplug', function() {
    function assertUnpluggedNoheal(blocks) {
      // A has nothing connected to it.
      assertEquals(0, blocks.A.getChildren().length);
      // B and C are still connected.
      assertEquals(blocks.B, blocks.C.getParent());
      // B is the top of its stack.
      assertNull(blocks.B.getParent());
    }

    function assertUnpluggedHealed(blocks) {
      // A and C are connected.
      assertEquals(1, blocks.A.getChildren().length);
      assertEquals(blocks.A, blocks.C.getParent());
      // B has nothing connected to it.
      assertEquals(0, blocks.B.getChildren().length);
      // B is the top of its stack.
      assertNull(blocks.B.getParent());
    }

    setup(function() {
      Blockly.defineBlocksWithJsonArray([{
        "type": "stack_block",
        "message0": "",
        "previousStatement": null,
        "nextStatement": null
      },
      {
        "type": "row_block",
        "message0": "%1",
        "args0": [
          {
            "type": "input_value",
            "name": "INPUT"
          }
        ],
        "output": null
      }]);

      this.workspace = new Blockly.Workspace();
    });

    teardown(function() {
      delete Blockly.Blocks['stack_block'];
      delete Blockly.Blocks['row_block'];

      this.workspace.dispose();
    });

    suite('Row', function() {
      setup(function() {
        var blockA = this.workspace.newBlock('row_block');
        var blockB = this.workspace.newBlock('row_block');
        var blockC = this.workspace.newBlock('row_block');

        blockA.inputList[0].connection.connect(blockB.outputConnection);
        blockB.inputList[0].connection.connect(blockC.outputConnection);

        assertEquals(blockB, blockC.getParent());

        this.blocks = {
          A: blockA,
          B: blockB,
          C: blockC
        };
      });

      test('Don\'t heal', function() {
        this.blocks.B.unplug(false);
        assertUnpluggedNoheal(this.blocks);
      });

      test('Heal', function() {
        this.blocks.B.unplug(true);
        // Each block has only one input, and the types work.
        assertUnpluggedHealed(this.blocks);
      });

      test('Heal with bad checks', function() {
        var blocks = this.blocks;

        // A and C can't connect, but both can connect to B.
        blocks.A.inputList[0].connection.setCheck('type1');
        blocks.C.outputConnection.setCheck('type2');

        // Each block has only one input, but the types don't work.
        blocks.B.unplug(true);
        assertUnpluggedNoheal(blocks);
      });

      test('Parent has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to parent
        blocks.A.appendValueInput("INPUT").setCheck(null);
        blocks.B.unplug(true);
        assertUnpluggedHealed(blocks);
      });

      test('Middle block has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to middle block
        blocks.B.appendValueInput("INPUT").setCheck(null);
        blocks.B.unplug(true);
        assertUnpluggedHealed(blocks);
      });

      test('Child block has multiple inputs', function() {
        var blocks = this.blocks;
        // Add extra input to child block
        blocks.C.appendValueInput("INPUT").setCheck(null);
        // Child block input count doesn't matter.
        blocks.B.unplug(true);
        assertUnpluggedHealed(blocks);
      });
    });

    suite('Stack', function() {
      setup(function() {
        var blockA = this.workspace.newBlock('stack_block');
        var blockB = this.workspace.newBlock('stack_block');
        var blockC = this.workspace.newBlock('stack_block');

        blockA.nextConnection.connect(blockB.previousConnection);
        blockB.nextConnection.connect(blockC.previousConnection);

        assertEquals(blockB, blockC.getParent());

        this.blocks = {
          A: blockA,
          B: blockB,
          C: blockC
        };
      });

      test('Don\'t heal', function() {
        this.blocks.B.unplug();
        assertUnpluggedNoheal(this.blocks);
      });

      test('Heal', function() {
        this.blocks.B.unplug(true);
        assertUnpluggedHealed(this.blocks);
      });

      test('Heal with bad checks', function() {
        var blocks = this.blocks;
        // A and C can't connect, but both can connect to B.
        blocks.A.nextConnection.setCheck('type1');
        blocks.C.previousConnection.setCheck('type2');

        // The types don't work.
        blocks.B.unplug(true);

        // Stack blocks unplug before checking whether the types match.
        // TODO (#1994): Check types before unplugging.
        // A has nothing connected to it.
        assertEquals(0, blocks.A.getChildren().length);
        // B has nothing connected to it.
        assertEquals(0, blocks.B.getChildren().length);
        // C has nothing connected to it.
        assertEquals(0, blocks.C.getChildren().length);
        // A is the top of its stack.
        assertNull(blocks.A.getParent());
        // B is the top of its stack.
        assertNull(blocks.B.getParent());
        // C is the top of its stack.
        assertNull(blocks.C.getParent());
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Created by edlc on 12/12/16.
 */

'use strict';

import {expect} from 'chai';
import compose from '../../src/compose';
import {__} from '../../src/curry';
import {expectInstanceOf, expectFunction, expectEqual, add, multiply, divide} from './../helpers';
import Monad from '../../src/monad/Monad';
import {id} from '../../src/operators';

import {Maybe, Just, Nothing} from '../../src/monad/Maybe';

let expectMonad = value => expectInstanceOf(value, Monad),
    expectMaybe = value => expectInstanceOf(value, Maybe) && expectMonad(value),
    expectJust = value => expectInstanceOf(value, Just),
    expectNothing = value => expectInstanceOf(value, Nothing),
    monadInterface = ['ap', 'map', 'join', 'chain'];

describe('Maybe', function () {

    describe('Construction:', function () {

        it('should map to `Nothing` when constructed using function syntax and passed in value is `null` or `undefined`', function () {
            let result = Maybe();
            expectMaybe(result);
            expectNothing(result.map(id));
        });

        it('should map to `Just` when constructed using function syntax function and passed in value is not `null` and not `undefined`', function () {
            let result = Maybe('something');
            expectMaybe(result);
            expectJust(result.map(id));
        });

        it('should map to `Nothing` when constructed with new and passed in value is `null` or `undefined`', function () {
            let result = new Maybe();
            expectMaybe(result);
            expectNothing(result.map(id));
        });

        it('should map to `Just` when constructed with new and passed in value is not `null` and not `undefined`', function () {
            let result = new Maybe('something');
            expectMaybe(result);
            expectJust(result.map(id));
        });

    });

    describe('#Nothing', function () {
        let someInstance = Nothing();

        describe ('Constructor', function () {
            it('should be a singleton instance even when call `new Nothing()`', function () {
                [new Nothing(), Nothing(), Nothing()].reduce((aggInstance, instance) => {
                    expectNothing(aggInstance);
                    expectEqual(aggInstance, instance);
                    return instance;
                }, new Nothing());
            });
        });

        monadInterface.forEach(key => {
            describe ('#' + key, function () {
                it(`should have a \`${key}\` method`, function () {
                    expectFunction(someInstance[key]);
                });
                it('should return a singleton instance of `Nothing`', function () {
                    let result = someInstance[key]();
                    expectNothing(result);
                    expectEqual(result, someInstance);
                });
            });
        });
    });

});
<commit_msg>Added tests for 'Just'.<commit_after>/**
 * Created by edlc on 12/12/16.
 */

'use strict';

import {expect} from 'chai';
import {expectInstanceOf, expectFunction, expectEqual, add, multiply} from './../helpers';
import Monad from '../../src/monad/Monad';
import {id} from '../../src/operators';

import {Maybe, Just, Nothing} from '../../src/monad/Maybe';

let expectMonad = value => expectInstanceOf(value, Monad),
    expectMaybe = value => expectInstanceOf(value, Maybe) && expectMonad(value),
    expectJust = value => expectInstanceOf(value, Just),
    expectNothing = value => expectInstanceOf(value, Nothing),
    monadInterface = ['ap', 'map', 'join', 'chain'];

describe('Maybe', function () {

    describe('Construction:', function () {

        it('should map to `Nothing` when constructed using function syntax and passed in value is `null` or `undefined`', function () {
            let result = Maybe();
            expectMaybe(result);
            expectNothing(result.map(id));
        });

        it('should map to `Just` when constructed using function syntax function and passed in value is not `null` and not `undefined`', function () {
            let result = Maybe('something');
            expectMaybe(result);
            expectJust(result.map(id));
        });

        it('should map to `Nothing` when constructed with new and passed in value is `null` or `undefined`', function () {
            let result = new Maybe();
            expectMaybe(result);
            expectNothing(result.map(id));
        });

        it('should map to `Just` when constructed with new and passed in value is not `null` and not `undefined`', function () {
            let result = new Maybe('something');
            expectMaybe(result);
            expectJust(result.map(id));
        });

    });

    describe('#Nothing', function () {
        let someInstance = Nothing();

        describe('Constructor', function () {
            it('should be a singleton instance even when call `new Nothing()`', function () {
                [new Nothing(), Nothing(), Nothing()].reduce((aggInstance, instance) => {
                    expectNothing(aggInstance);
                    expectEqual(aggInstance, instance);
                    return instance;
                }, new Nothing());
            });
        });

        monadInterface.forEach(key => {
            describe('#' + key, function () {
                it(`should have a \`${key}\` method`, function () {
                    expectFunction(someInstance[key]);
                });
                it('should return a singleton instance of `Nothing`', function () {
                    let result = someInstance[key]();
                    expectNothing(result);
                    expectEqual(result, someInstance);
                });
            });
        });
    });

    describe('#Just', function () {

        describe('Constructor', function () {
            it('should return an instance when receiving any value  (when called with `new` and without `new`)', function () {
                [null, undefined, 99, 0, -1, true, false, [1, 2, 3], {}, {a: 'b'}, () => {
                }]
                    .forEach(value => {
                        expectJust(Just(value));
                        expectJust(new Just(value));
                    });
            });

            it('should return an instance of itself even when receiving no value (when called with `new` and without `new`)', function () {
                expectJust(Just());
                expectJust(new Just());
            });
        });

        describe('Statics', function () {
            it('#of (should act as unit)', function () {
                let result = Just.of(multiply(4)).ap(Just(25));
                expectFunction(Just.of);
                expectJust(Just.of());
                expectEqual(result.value, 100);
            });
        });

        describe('Interface ["' + (monadInterface.join('", "') + '"]'), function () {
            let someInstance = Just();
            monadInterface.forEach(key => {
                it(`should have a \`${key}\` method`, function () {
                    expectFunction(someInstance[key]);
                });
            });
        });

        describe('#map', function () {
            let someFn = value => value.toString();
            it('should return nothing when contained value is `null` or `undefined`', function () {
                expectNothing(Just().map(someFn));
                expectNothing(Just(null).map(someFn));
                expectNothing(Just(undefined).map(someFn));
            });
            expectJust(Just(-1).map(someFn));
            expectJust(Just(0).map(someFn));
            expectJust(Just(1).map(someFn));
            [-1, 0, 1, true, false, [1, 2, 3], {}, {a: 'b'}, () => {}]
                .forEach(function (value) {
                    it('should return an instance of `Just` when contained value is ' +
                        '`' + value.toString() + '`', function () {
                        expectJust(Just(value).map(someFn));
                    });
                });
        });

        describe('#ap', function () {
            it('should map incoming functor over it\'s value', function () {
                let instance = Just(add(1)),
                    result = instance.ap(Just(99));
                expectJust(result);
                expectEqual(result.value, 100);
            });
        });

        describe('#chain', function () {
            it('should map incoming function over it\'s value and flatten it result if it is nested within an ' +
                'instance of it\'s own type', function () {
                let addReturnsJust = value => Just(add(1, value)),
                    instance = Just(99),
                    result1 = instance.chain(addReturnsJust), // nested result
                    result2 = instance.chain(add(1)); // un-nested result

                // Check results
                [result1, result2].forEach(result => {
                    expectJust(result);
                    expectEqual(result.value, 100);
                });
            });
        });

        describe('#join', function () {
            it('should remove one level of monadic structure on it\'s own type;  ' +
                'E.g., If it\'s inner value is of the same type.', function () {
                let innerMostValue = 5,
                    monad1 = Just(innerMostValue),
                    monad2 = Just(monad1),
                    monad3 = Just(monad2),
                    monad4 = Just(),
                    expectInnerValueEqual = (value, value2) => expectEqual(value, value2),
                    expectations = (result, equalTo) => {
                        expectJust(result);
                        expectInnerValueEqual(result.value, equalTo);
                    };
                expectations(monad1.join(), innerMostValue);
                expectations(monad2.join(), innerMostValue);
                expectations(monad3.join(), monad1);
                expectations(monad4.join(), undefined);
            });
        });

    });

});
<|endoftext|>


<commit_before>angular.module("animals", ["ngExtender"]);

function AbstractMammal($scope){

    $scope.speak = function(){
        var rand = Math.round(Math.random() * ($scope.wordsArray.length-1));
        window.alert($scope.wordsArray[rand]);
    }

    $scope.setTitle = function(){
        $scope.title = "Hi! I am a " + $scope.name + "!";
    }

    $scope.$binded(function(){
        $scope.setTitle();
    });

    $scope.$abstract("wordsArray");
    $scope.$abstract("name");
}

function Cat($extend, $scope){
    $extend($scope).with(AbstractMammal);

    $scope.wordsArray = ["Meow!", "Hiss!"];
    $scope.name = "Cat";
}

function Dog($extend, $scope){
    $extend($scope).with(AbstractMammal);

    $scope.wordsArray = ["Woof!", "Lick!"];
    $scope.name = "Dog";
}

function AngryDog($extend, $scope){
    $extend($scope).with(Dog);

    $scope.speak = function(){
        $scope.$super.speak();
        $scope.name = "Angry Dog";
        $scope.setTitle();
    }
}<commit_msg>changed scope to this<commit_after>angular.module("animals", ["ngExtender"]);

function AbstractMammal(){

    var self = this;

    this.speak = function(){
        var rand = Math.round(Math.random() * (self.wordsArray.length-1));
        window.alert(self.wordsArray[rand]);
    }

    this.setTitle = function(){
        self.title = "Hi! I am a " + self.name + "!";
    }

    this.$binded(function(){
        self.setTitle();
    });

    this.$abstract("wordsArray");
    this.$abstract("name");
}

function Cat($extend){
    $extend(this).with(AbstractMammal);

    this.wordsArray = ["Meow!", "Hiss!"];
    this.name = "Cat";
}

function Dog($extend){
    $extend(this).with(AbstractMammal);

    this.wordsArray = ["Woof!", "Lick!"];
    this.name = "Dog";
}

function AngryDog($extend){
    var $super = $extend(this).with(Dog);

    var self = this;

    this.speak = function(){
        $super.speak();
        self.name = "Angry Dog";
        self.setTitle();
    }
}
<|endoftext|>


<commit_before>['idb-1'].map(function(adapter) {

  module('attachment performance: ' + adapter, {
    setup : function () {
      this.name = generateAdapterUrl(adapter)
    }
  });

  asyncTest("Test large attachments", function() {

    var fiveMB="";
    for (i=0;i<5000000;i++){ //not sure if this is exactly 5MB but it's big enough
      fiveMB+="a";
    }

    var fiveMB2="";
    for (i=0;i<5000000;i++){
      fiveMB2+="b";
    }

    initTestDB(this.name, function(err, db) {

      var queryStartTime1=new Date().getTime();
      function map(doc){
	{emit(null, doc);}
      }

      db.query({map: map},{reduce: false}, function(err, response) {
	var duration1 = new Date().getTime() - queryStartTime1;
	console.log("query 1 took " + duration1 + " ms");
	db.put({ _id: 'mydoc' }, function(err, resp) {
	  db.putAttachment('mydoc/mytext', resp.rev, fiveMB, 'text/plain', function(err, res) {
	    db.put({ _id: 'mydoc2' }, function(err, resp) {
	      db.putAttachment('mydoc/mytext2', resp.rev, fiveMB2, 'text/plain', function(err, res) {
		var queryStartTime2 = new Date().getTime();
		function map(doc) { emit(null, doc); }
		db.query({map: map},{reduce: false}, function(err, response) {
		  var duration2 = new Date().getTime()-queryStartTime2;
		  console.log("query 2 took "+duration2+" ms");
		  ok(duration2<=duration1*10, 'Query finished within order of magnitude');
		  start();
		});
	      });
	    });
	  });
	});
      });
    });
  });

});
<commit_msg>(#416) - Fix lint errors in perf.attachments.js<commit_after>["idb-1"].map(function(adapter) {

  module('attachment performance: ' + adapter, {
    setup : function () {
      this.name = generateAdapterUrl(adapter)
    }
  });

  asyncTest("Test large attachments", function() {

    var fiveMB="";
    for (i=0;i<5000000;i++){ //not sure if this is exactly 5MB but it's big enough
      fiveMB+="a";
    }

    var fiveMB2="";
    for (i=0;i<5000000;i++){
      fiveMB2+="b";
    }

    initTestDB(this.name, function(err, db) {

      var queryStartTime1=new Date().getTime();
      function map(doc){
	{emit(null, doc);}
      }

      db.query({map: map},{reduce: false}, function(err, response) {
	var duration1 = new Date().getTime() - queryStartTime1;
	console.log("query 1 took " + duration1 + " ms");
	db.put({ _id: 'mydoc' }, function(err, resp) {
	  db.putAttachment('mydoc/mytext', resp.rev, fiveMB, 'text/plain', function(err, res) {
	    db.put({ _id: 'mydoc2' }, function(err, resp) {
	      db.putAttachment('mydoc/mytext2', resp.rev, fiveMB2, 'text/plain', function(err, res) {
		var queryStartTime2 = new Date().getTime();
		function map(doc) { emit(null, doc); }
		db.query({map: map},{reduce: false}, function(err, response) {
		  var duration2 = new Date().getTime()-queryStartTime2;
		  console.log("query 2 took "+duration2+" ms");
		  ok(duration2<=duration1*10, 'Query finished within order of magnitude');
		  start();
		});
	      });
	    });
	  });
	});
      });
    });
  });

});
<|endoftext|>