[Pkg-javascript-commits] [node-lazy-cache] 01/04: Import Upstream version 2.0.1

Sruthi Chandran srud-guest at moszumanska.debian.org
Sun Oct 16 11:34:43 UTC 2016


This is an automated email from the git hooks/post-receive script.

srud-guest pushed a commit to branch master
in repository node-lazy-cache.

commit 344508984d84de767cb5b275d2ae61278fb50a74
Author: Sruthi <srud at disroot.org>
Date:   Sun Oct 16 16:51:56 2016 +0530

    Import Upstream version 2.0.1
---
 .editorconfig          |  22 ++++
 .eslintrc.json         | 275 +++++++++++++++++++++++++++++++++++++++++++++++++
 .gitattributes         |  10 ++
 .gitignore             |  15 +++
 .travis.yml            |  12 +++
 .verb.md               | 103 ++++++++++++++++++
 LICENSE                |  21 ++++
 README.md              | 163 +++++++++++++++++++++++++++++
 example-utils.js       |  54 ++++++++++
 example.js             |  28 +++++
 index.js               |  73 +++++++++++++
 package.json           |  65 ++++++++++++
 test/fixtures/utils.js |  40 +++++++
 test/test.js           | 218 +++++++++++++++++++++++++++++++++++++++
 14 files changed, 1099 insertions(+)

diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..408d870
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,22 @@
+# http://editorconfig.org
+root = true
+
+[*]
+indent_style = space
+end_of_line = lf
+charset = utf-8
+indent_size = 2
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.md]
+trim_trailing_whitespace = false
+insert_final_newline = false
+
+[**/{actual,fixtures,expected}/**]
+trim_trailing_whitespace = false
+insert_final_newline = false
+
+[**/templates/**]
+trim_trailing_whitespace = false
+insert_final_newline = false
diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644
index 0000000..5b78706
--- /dev/null
+++ b/.eslintrc.json
@@ -0,0 +1,275 @@
+{
+  "ecmaFeatures": {
+    "modules": true,
+    "experimentalObjectRestSpread": true
+  },
+  "env": {
+    "browser": false,
+    "es6": true,
+    "node": true,
+    "mocha": true
+  },
+  "globals": {
+    "document": false,
+    "navigator": false,
+    "window": false
+  },
+  "rules": {
+    "accessor-pairs": 2,
+    "arrow-spacing": [
+      2,
+      {
+        "before": true,
+        "after": true
+      }
+    ],
+    "block-spacing": [
+      2,
+      "always"
+    ],
+    "brace-style": [
+      2,
+      "1tbs",
+      {
+        "allowSingleLine": true
+      }
+    ],
+    "comma-dangle": [
+      2,
+      "never"
+    ],
+    "comma-spacing": [
+      2,
+      {
+        "before": false,
+        "after": true
+      }
+    ],
+    "comma-style": [
+      2,
+      "last"
+    ],
+    "constructor-super": 2,
+    "curly": [
+      2,
+      "multi-line"
+    ],
+    "dot-location": [
+      2,
+      "property"
+    ],
+    "eol-last": 2,
+    "eqeqeq": [
+      2,
+      "allow-null"
+    ],
+    "generator-star-spacing": [
+      2,
+      {
+        "before": true,
+        "after": true
+      }
+    ],
+    "handle-callback-err": [
+      2,
+      "^(err|error)$"
+    ],
+    "indent": [
+      2,
+      2,
+      {
+        "SwitchCase": 1
+      }
+    ],
+    "key-spacing": [
+      2,
+      {
+        "beforeColon": false,
+        "afterColon": true
+      }
+    ],
+    "keyword-spacing": [
+      2,
+      {
+        "before": true,
+        "after": true
+      }
+    ],
+    "new-cap": [
+      2,
+      {
+        "newIsCap": true,
+        "capIsNew": false
+      }
+    ],
+    "new-parens": 2,
+    "no-array-constructor": 2,
+    "no-caller": 2,
+    "no-class-assign": 2,
+    "no-cond-assign": 2,
+    "no-const-assign": 2,
+    "no-control-regex": 2,
+    "no-debugger": 2,
+    "no-delete-var": 2,
+    "no-dupe-args": 2,
+    "no-dupe-class-members": 2,
+    "no-dupe-keys": 2,
+    "no-duplicate-case": 2,
+    "no-empty-character-class": 2,
+    "no-eval": 2,
+    "no-ex-assign": 2,
+    "no-extend-native": 2,
+    "no-extra-bind": 2,
+    "no-extra-boolean-cast": 2,
+    "no-extra-parens": [
+      2,
+      "functions"
+    ],
+    "no-fallthrough": 2,
+    "no-floating-decimal": 2,
+    "no-func-assign": 2,
+    "no-implied-eval": 2,
+    "no-inner-declarations": [
+      2,
+      "functions"
+    ],
+    "no-invalid-regexp": 2,
+    "no-irregular-whitespace": 2,
+    "no-iterator": 2,
+    "no-label-var": 2,
+    "no-labels": 2,
+    "no-lone-blocks": 2,
+    "no-mixed-spaces-and-tabs": 2,
+    "no-multi-spaces": 2,
+    "no-multi-str": 2,
+    "no-multiple-empty-lines": [
+      2,
+      {
+        "max": 1
+      }
+    ],
+    "no-native-reassign": 0,
+    "no-negated-in-lhs": 2,
+    "no-new": 2,
+    "no-new-func": 2,
+    "no-new-object": 2,
+    "no-new-require": 2,
+    "no-new-wrappers": 2,
+    "no-obj-calls": 2,
+    "no-octal": 2,
+    "no-octal-escape": 2,
+    "no-proto": 0,
+    "no-redeclare": 2,
+    "no-regex-spaces": 2,
+    "no-return-assign": 2,
+    "no-self-compare": 2,
+    "no-sequences": 2,
+    "no-shadow-restricted-names": 2,
+    "no-spaced-func": 2,
+    "no-sparse-arrays": 2,
+    "no-this-before-super": 2,
+    "no-throw-literal": 2,
+    "no-trailing-spaces": 0,
+    "no-undef": 2,
+    "no-undef-init": 2,
+    "no-unexpected-multiline": 2,
+    "no-unneeded-ternary": [
+      2,
+      {
+        "defaultAssignment": false
+      }
+    ],
+    "no-unreachable": 2,
+    "no-unused-vars": [
+      2,
+      {
+        "vars": "all",
+        "args": "none"
+      }
+    ],
+    "no-useless-call": 0,
+    "no-with": 2,
+    "one-var": [
+      0,
+      {
+        "initialized": "never"
+      }
+    ],
+    "operator-linebreak": [
+      0,
+      "after",
+      {
+        "overrides": {
+          "?": "before",
+          ":": "before"
+        }
+      }
+    ],
+    "padded-blocks": [
+      0,
+      "never"
+    ],
+    "quotes": [
+      2,
+      "single",
+      "avoid-escape"
+    ],
+    "radix": 2,
+    "semi": [
+      2,
+      "always"
+    ],
+    "semi-spacing": [
+      2,
+      {
+        "before": false,
+        "after": true
+      }
+    ],
+    "space-before-blocks": [
+      2,
+      "always"
+    ],
+    "space-before-function-paren": [
+      2,
+      "never"
+    ],
+    "space-in-parens": [
+      2,
+      "never"
+    ],
+    "space-infix-ops": 2,
+    "space-unary-ops": [
+      2,
+      {
+        "words": true,
+        "nonwords": false
+      }
+    ],
+    "spaced-comment": [
+      0,
+      "always",
+      {
+        "markers": [
+          "global",
+          "globals",
+          "eslint",
+          "eslint-disable",
+          "*package",
+          "!",
+          ","
+        ]
+      }
+    ],
+    "use-isnan": 2,
+    "valid-typeof": 2,
+    "wrap-iife": [
+      2,
+      "any"
+    ],
+    "yoda": [
+      2,
+      "never"
+    ]
+  }
+}
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..660957e
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,10 @@
+# Enforce Unix newlines
+* text eol=lf
+
+# binaries
+*.ai binary
+*.psd binary
+*.jpg binary
+*.gif binary
+*.png binary
+*.jpeg binary
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..80a228c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+*.DS_Store
+*.sublime-*
+_gh_pages
+bower_components
+node_modules
+npm-debug.log
+actual
+test/actual
+temp
+tmp
+TODO.md
+vendor
+.idea
+benchmark
+coverage
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..cb1d261
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,12 @@
+sudo: false
+language: node_js
+node_js:
+  - '5'
+  - '4'
+  - '0.12'
+  - '0.10'
+matrix:
+  fast_finish: true
+  allow_failures:
+    - node_js: '0.10'
+    - node_js: '0.12'
diff --git a/.verb.md b/.verb.md
new file mode 100644
index 0000000..4b56714
--- /dev/null
+++ b/.verb.md
@@ -0,0 +1,103 @@
+**webpack users**
+
+If you use webpack and are experiencing issues, try using [unlazy-loader](https://github.com/doowb/unlazy-loader), a webpack loader that _fixes the webpack bug_ that prevents webpack from working with native javascript getters.
+
+## Usage
+
+```js
+var utils = require('{%= name %}')(require);
+```
+
+**Use as a property on `lazy`**
+
+The module is also added as a property to the `lazy` function
+so it can be called without having to call a function first.
+
+```js
+var utils = require('{%= name %}')(require);
+
+// `npm install glob`
+utils('glob');
+
+// glob sync
+console.log(utils.glob.sync('*.js'));
+
+// glob async
+utils.glob('*.js', function (err, files) {
+  console.log(files);
+});
+```
+
+**Use as a function**
+
+```js
+var utils = require('{%= name %}')(require);
+var glob = utils('glob');
+
+// `glob` is a now a function that may be called when needed
+glob().sync('foo/*.js');
+```
+
+## Aliases
+
+An alias may be passed as the second argument if you don't want to use the automatically camel-cased variable name.
+
+**Example**
+
+```js
+var utils = require('{%= name %}')(require);
+
+// alias `ansi-yellow` as `yellow`
+utils('ansi-yellow', 'yellow');
+console.log(utils.yellow('foo'));
+```
+
+Dot notation may also be used in the alias to create an object hierarchy.
+
+**Example**
+
+```js
+var utils = require('{%= name %}')(require);
+utils('ansi-cyan', 'color.cyan');
+utils('ansi-yellow', 'color.yellow');
+utils('ansi-magenta', 'color.magenta');
+console.log(utils.color.cyan('foo'));
+console.log(utils.color.yellow('bar'));
+console.log(utils.color.magenta('baz'));
+```
+
+## Browserify usage
+
+**Example**
+
+```js
+var utils = require('{%= name %}')(require);
+// temporarily re-assign `require` to trick browserify
+var fn = require;
+require = utils;
+// list module dependencies (here, `require` is actually `lazy-cache`)
+require('glob');
+require = fn; // restore the native `require` function
+
+/**
+ * Now you can use glob with the `utils.glob` variable
+ */
+
+// sync
+console.log(utils.glob.sync('*.js'));
+
+// async
+utils.glob('*.js', function (err, files) {
+  console.log(files.join('\n'));
+});
+```
+
+## Kill switch
+
+In certain rare edge cases it may be necessary to unlazy all lazy-cached dependencies (5 reported cases after ~30 million downloads).
+
+To force lazy-cache to immediately invoke all dependencies, do:
+
+```js
+process.env.UNLAZY = true;
+```
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..1e49edf
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-2016, Jon Schlinkert.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b00d4e2
--- /dev/null
+++ b/README.md
@@ -0,0 +1,163 @@
+# lazy-cache [![NPM version](https://img.shields.io/npm/v/lazy-cache.svg?style=flat)](https://www.npmjs.com/package/lazy-cache) [![NPM downloads](https://img.shields.io/npm/dm/lazy-cache.svg?style=flat)](https://npmjs.org/package/lazy-cache) [![Build Status](https://img.shields.io/travis/jonschlinkert/lazy-cache.svg?style=flat)](https://travis-ci.org/jonschlinkert/lazy-cache)
+
+> Cache requires to be lazy-loaded when needed.
+
+## Install
+
+Install with [npm](https://www.npmjs.com/):
+
+```sh
+$ npm install lazy-cache --save
+```
+
+**webpack users**
+
+If you use webpack and are experiencing issues, try using [unlazy-loader](https://github.com/doowb/unlazy-loader), a webpack loader that _fixes the webpack bug_ that prevents webpack from working with native javascript getters.
+
+## Usage
+
+```js
+var utils = require('lazy-cache')(require);
+```
+
+**Use as a property on `lazy`**
+
+The module is also added as a property to the `lazy` function
+so it can be called without having to call a function first.
+
+```js
+var utils = require('lazy-cache')(require);
+
+// `npm install glob`
+utils('glob');
+
+// glob sync
+console.log(utils.glob.sync('*.js'));
+
+// glob async
+utils.glob('*.js', function (err, files) {
+  console.log(files);
+});
+```
+
+**Use as a function**
+
+```js
+var utils = require('lazy-cache')(require);
+var glob = utils('glob');
+
+// `glob` is a now a function that may be called when needed
+glob().sync('foo/*.js');
+```
+
+## Aliases
+
+An alias may be passed as the second argument if you don't want to use the automatically camel-cased variable name.
+
+**Example**
+
+```js
+var utils = require('lazy-cache')(require);
+
+// alias `ansi-yellow` as `yellow`
+utils('ansi-yellow', 'yellow');
+console.log(utils.yellow('foo'));
+```
+
+Dot notation may also be used in the alias to create an object hierarchy.
+
+**Example**
+
+```js
+var utils = require('lazy-cache')(require);
+utils('ansi-cyan', 'color.cyan');
+utils('ansi-yellow', 'color.yellow');
+utils('ansi-magenta', 'color.magenta');
+console.log(utils.color.cyan('foo'));
+console.log(utils.color.yellow('bar'));
+console.log(utils.color.magenta('baz'));
+```
+
+## Browserify usage
+
+**Example**
+
+```js
+var utils = require('lazy-cache')(require);
+// temporarily re-assign `require` to trick browserify
+var fn = require;
+require = utils;
+// list module dependencies (here, `require` is actually `lazy-cache`)
+require('glob');
+require = fn; // restore the native `require` function
+
+/**
+ * Now you can use glob with the `utils.glob` variable
+ */
+
+// sync
+console.log(utils.glob.sync('*.js'));
+
+// async
+utils.glob('*.js', function (err, files) {
+  console.log(files.join('\n'));
+});
+```
+
+## Kill switch
+
+In certain rare edge cases it may be necessary to unlazy all lazy-cached dependencies (5 reported cases after ~30 million downloads).
+
+To force lazy-cache to immediately invoke all dependencies, do:
+
+```js
+process.env.UNLAZY = true;
+```
+
+## Related projects
+
+You might also be interested in these projects:
+
+[lint-deps](https://www.npmjs.com/package/lint-deps): CLI tool that tells you when dependencies are missing from package.json and offers you a… [more](https://www.npmjs.com/package/lint-deps) | [homepage](https://github.com/jonschlinkert/lint-deps)
+
+## Contributing
+
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/lazy-cache/issues/new).
+
+## Building docs
+
+Generate readme and API documentation with [verb](https://github.com/verbose/verb):
+
+```sh
+$ npm install verb && npm run docs
+```
+
+Or, if [verb](https://github.com/verbose/verb) is installed globally:
+
+```sh
+$ verb
+```
+
+## Running tests
+
+Install dev dependencies:
+
+```sh
+$ npm install -d && npm test
+```
+
+## Author
+
+**Jon Schlinkert**
+
+* [github/jonschlinkert](https://github.com/jonschlinkert)
+* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+
+Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
+Released under the [MIT license](https://github.com/jonschlinkert/lazy-cache/blob/master/LICENSE).
+
+***
+
+_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 28, 2016._
\ No newline at end of file
diff --git a/example-utils.js b/example-utils.js
new file mode 100644
index 0000000..72b618d
--- /dev/null
+++ b/example-utils.js
@@ -0,0 +1,54 @@
+/**
+ * The easiest way to add this file is to do:
+ *
+ * ```sh
+ * $ npm i -g lazy-cache-cli && lazy
+ * ```
+ * To do it manually:
+ *
+ * 1. Add a file named `utils.js` to your project.
+ * 2. Copy the contents of this file (below this comment)
+ *    into `utils.js`
+ * 3. Change the dependencies where it says
+ *    "your dependencies here" your project's actual dependencies
+ */
+'use strict';
+
+/**
+ * Module dependencies
+ */
+
+var utils = require('lazy-cache')(require);
+
+/**
+ * Temporarily re-assign `require` to trick browserify and
+ * webpack into reconizing lazy dependencies.
+ *
+ * This tiny bit of ugliness has the huge dual advantage of
+ * only loading modules that are actually called at some
+ * point in the lifecycle of the application, whilst also
+ * allowing browserify and webpack to find modules that
+ * are depended on but never actually called.
+ */
+
+var fn = require;
+require = utils;
+
+/**
+ * Lazily required module dependencies
+ */
+
+// __(your dependencies here)__
+require('ansi-yellow')
+
+/**
+ * reset `require`
+ */
+
+require = fn;
+
+/**
+ * Expose `utils` modules
+ */
+
+module.exports = utils;
diff --git a/example.js b/example.js
new file mode 100644
index 0000000..ca83454
--- /dev/null
+++ b/example.js
@@ -0,0 +1,28 @@
+var utils = require('./')(require);
+utils('glob');
+
+/**
+ * `utils.glob` is a getter that when called
+ * will require in `glob`
+ */
+
+console.log(utils.glob.sync('*.js'));
+utils.glob('*.js', function(err, files) {
+  console.log(files.join('\n'));
+});
+
+/**
+ * Browserify-friendly example
+ */
+
+var utils = require('./')(require);
+var fn = require;
+require = utils;
+require('ansi-yellow', 'yellow');
+require('glob');
+require = fn;
+
+console.log(utils.glob.sync('*.js'));
+utils.glob('*.js', function(err, files) {
+  console.log(files.join('\n'));
+});
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..751fcbb
--- /dev/null
+++ b/index.js
@@ -0,0 +1,73 @@
+'use strict';
+
+var set = require('set-getter');
+
+/**
+ * Cache results of the first function call to ensure only calling once.
+ *
+ * ```js
+ * var utils = require('lazy-cache')(require);
+ * // cache the call to `require('ansi-yellow')`
+ * utils('ansi-yellow', 'yellow');
+ * // use `ansi-yellow`
+ * console.log(utils.yellow('this is yellow'));
+ * ```
+ *
+ * @param  {Function} `fn` Function that will be called only once.
+ * @return {Function} Function that can be called to get the cached function
+ * @api public
+ */
+
+function lazyCache(requireFn) {
+  var cache = {};
+
+  return function proxy(name, alias) {
+    var key = alias;
+
+    // camel-case the module `name` if `alias` is not defined
+    if (typeof key !== 'string') {
+      key = camelcase(name);
+    }
+
+    // create a getter to lazily invoke the module the first time it's called
+    function getter() {
+      return cache[key] || (cache[key] = requireFn(name));
+    }
+
+    // trip the getter if `process.env.UNLAZY` is defined
+    if (unlazy(process.env)) {
+      getter();
+    }
+
+    set(proxy, key, getter);
+    return getter;
+  };
+}
+
+/**
+ * Return true if `process.env.LAZY` is true, or travis is running.
+ */
+
+function unlazy(env) {
+  return env.UNLAZY === 'true' || env.UNLAZY === true || env.TRAVIS;
+}
+
+/**
+ * Camelcase the the given module `name`.
+ */
+
+function camelcase(str) {
+  if (str.length === 1) {
+    return str.toLowerCase();
+  }
+  str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
+  return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
+    return ch.toUpperCase();
+  });
+}
+
+/**
+ * Expose `lazyCache`
+ */
+
+module.exports = lazyCache;
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..21e8c7f
--- /dev/null
+++ b/package.json
@@ -0,0 +1,65 @@
+{
+  "name": "lazy-cache",
+  "description": "Cache requires to be lazy-loaded when needed.",
+  "version": "2.0.1",
+  "homepage": "https://github.com/jonschlinkert/lazy-cache",
+  "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
+  "repository": "jonschlinkert/lazy-cache",
+  "bugs": {
+    "url": "https://github.com/jonschlinkert/lazy-cache/issues"
+  },
+  "license": "MIT",
+  "files": [
+    "index.js"
+  ],
+  "main": "index.js",
+  "engines": {
+    "node": ">=0.10.0"
+  },
+  "scripts": {
+    "test": "mocha"
+  },
+  "devDependencies": {
+    "ansi-cyan": "^0.1.1",
+    "ansi-magenta": "^0.1.1",
+    "ansi-yellow": "^0.1.1",
+    "glob": "^7.0.3",
+    "gulp-format-md": "^0.1.8",
+    "mocha": "^2.4.5",
+    "object.omit": "^2.0.0",
+    "object.pick": "^1.1.2"
+  },
+  "keywords": [
+    "cache",
+    "caching",
+    "dependencies",
+    "dependency",
+    "lazy",
+    "require",
+    "requires"
+  ],
+  "verb": {
+    "related": {
+      "list": [
+        "lint-deps"
+      ]
+    },
+    "plugins": [
+      "gulp-format-md"
+    ],
+    "toc": false,
+    "layout": "default",
+    "tasks": [
+      "readme"
+    ],
+    "lint": {
+      "reflinks": true
+    },
+    "reflinks": [
+      "verb"
+    ]
+  },
+  "dependencies": {
+    "set-getter": "^0.1.0"
+  }
+}
diff --git a/test/fixtures/utils.js b/test/fixtures/utils.js
new file mode 100644
index 0000000..7351e94
--- /dev/null
+++ b/test/fixtures/utils.js
@@ -0,0 +1,40 @@
+'use strict';
+
+/**
+ * Module dependencies
+ */
+
+var utils = require('../../')(require);
+
+/**
+ * Temporarily re-assign `require` to trick browserify and
+ * webpack into reconizing lazy dependencies.
+ *
+ * This tiny bit of ugliness has the huge dual advantage of
+ * only loading modules that are actually called at some
+ * point in the lifecycle of the application, whilst also
+ * allowing browserify and webpack to find modules that
+ * are depended on but never actually called.
+ */
+
+var fn = require;
+require = utils;
+
+/**
+ * Lazily required module dependencies
+ */
+
+// __(your dependencies here)__
+require('ansi-yellow')
+
+/**
+ * reset `require`
+ */
+
+require = fn;
+
+/**
+ * Expose `utils` modules
+ */
+
+module.exports = utils;
diff --git a/test/test.js b/test/test.js
new file mode 100644
index 0000000..13a9f50
--- /dev/null
+++ b/test/test.js
@@ -0,0 +1,218 @@
+'use strict';
+
+require('mocha');
+var assert = require('assert');
+var lazyCache = require('../');
+
+describe('lazy-cache', function() {
+  afterEach(function() {
+    delete require.cache[require.resolve('../index.js')];
+    process.env.UNLAZY = false;
+    lazyCache = require('../');
+  });
+
+  it('should return a function that lazyily requires a module', function() {
+    var lazy = lazyCache(require);
+    var yellow = lazy('ansi-yellow');
+    assert.deepEqual(typeof yellow, 'function');
+    assert.deepEqual(typeof yellow(), 'function');
+  });
+
+  it('should not invoke require until the module is used', function() {
+    var calls = {};
+    var lazy = lazyCache(function(name) {
+      calls[name] = (calls[name] || 0) + 1;
+      return require(name);
+    });
+
+    assert.deepEqual(calls, {});
+
+    var yellow = lazy('ansi-yellow');
+
+    if (process.env.TRAVIS) {
+      assert.deepEqual(calls, {'ansi-yellow': 1});
+    } else {
+      assert.deepEqual(calls, {});
+    }
+
+    yellow('one');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    yellow('two');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    yellow('three');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    yellow('four');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+  });
+
+  it('should add a property to the lazy function with the camelcased name', function() {
+    var lazy = lazyCache(require);
+    lazy('ansi-yellow');
+    assert.deepEqual(typeof lazy.ansiYellow, 'function');
+  });
+
+  it('should only require a dependency once', function() {
+    var calls = {};
+    var lazy = lazyCache(function(name) {
+      calls[name] = (calls[name] || 0) + 1;
+      return require(name);
+    });
+
+    assert.deepEqual(calls, {});
+    lazy('ansi-yellow');
+    if (process.env.TRAVIS) {
+      assert.deepEqual(calls, {'ansi-yellow': 1});
+    } else {
+      assert.deepEqual(calls, {});
+    }
+
+    lazy.ansiYellow('one');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('two');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('three');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('four');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+  });
+
+  it('should allow loading a dependency immediately with `process.env.UNLAZY` setting', function() {
+    process.env.UNLAZY = true;
+    var calls = {};
+    var lazy = lazyCache(function(name) {
+      calls[name] = (calls[name] || 0) + 1;
+      return require(name);
+    });
+
+    assert.deepEqual(calls, {});
+
+    lazy('ansi-yellow');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('one');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('two');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('three');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.ansiYellow('four');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+  });
+
+  it('should support an alias as the second argument:', function() {
+    var calls = {};
+    var lazy = lazyCache(function(name) {
+      calls[name] = (calls[name] || 0) + 1;
+      return require(name);
+    });
+
+    assert.deepEqual(calls, {});
+    lazy('ansi-yellow', 'yellow');
+    if (process.env.TRAVIS) {
+      assert.deepEqual(calls, {'ansi-yellow': 1});
+    } else {
+      assert.deepEqual(calls, {});
+    }
+
+    lazy.yellow('one');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.yellow('two');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.yellow('three');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+    lazy.yellow('four');
+    assert.deepEqual(calls, {'ansi-yellow': 1});
+  });
+
+  it('should support dot-notation in aliases', function() {
+    var lazy = lazyCache(require);
+    lazy('ansi-cyan', 'color.cyan');
+    lazy('ansi-yellow', 'color.yellow');
+    lazy('ansi-magenta', 'color.magenta');
+
+    assert.deepEqual(typeof lazy.color, 'object');
+    assert.deepEqual(typeof lazy.color.cyan, 'function');
+    assert.deepEqual(typeof lazy.color.yellow, 'function');
+    assert.deepEqual(typeof lazy.color.magenta, 'function');
+  });
+
+  it('should not use dot-notation in non-aliases', function() {
+    var lazy = lazyCache(require);
+    lazy('object.omit');
+    lazy('object.pick');
+    assert.deepEqual(typeof lazy.objectOmit, 'function');
+    assert.deepEqual(typeof lazy.objectPick, 'function');
+  });
+
+  it('should load local files', function() {
+    var lazy = lazyCache(require);
+    lazy('./fixtures/utils');
+    assert.deepEqual(typeof lazy.fixturesUtils, 'function');
+    assert.deepEqual(typeof lazy.fixturesUtils.ansiYellow, 'function');
+  });
+
+  it('should load local files with an alias', function() {
+    var lazy = lazyCache(require);
+    lazy('./fixtures/utils', 'utils');
+    assert.deepEqual(typeof lazy.utils, 'function');
+    assert.deepEqual(typeof lazy.utils.ansiYellow, 'function');
+  });
+
+  it('should support dot-notation when `process.env.UNLAZY` is used', function() {
+    process.env.UNLAZY = true;
+
+    var calls = {};
+    var lazy = lazyCache(function(name) {
+      calls[name] = (calls[name] || 0) + 1;
+      return require(name);
+    });
+
+    assert.deepEqual(calls, {});
+
+    lazy('ansi-cyan', 'color.cyan');
+    lazy('ansi-yellow', 'color.yellow');
+    lazy('ansi-magenta', 'color.magenta');
+
+    assert.deepEqual(calls, {
+      'ansi-cyan': 1,
+      'ansi-yellow': 1,
+      'ansi-magenta': 1
+    });
+    lazy.color.cyan('one');
+    lazy.color.yellow('one');
+    lazy.color.magenta('one');
+    assert.deepEqual(calls, {
+      'ansi-cyan': 1,
+      'ansi-yellow': 1,
+      'ansi-magenta': 1
+    });
+    lazy.color.cyan('two');
+    lazy.color.yellow('two');
+    lazy.color.magenta('two');
+    assert.deepEqual(calls, {
+      'ansi-cyan': 1,
+      'ansi-yellow': 1,
+      'ansi-magenta': 1
+    });
+    lazy.color.cyan('three');
+    lazy.color.yellow('three');
+    lazy.color.magenta('three');
+    assert.deepEqual(calls, {
+      'ansi-cyan': 1,
+      'ansi-yellow': 1,
+      'ansi-magenta': 1
+    });
+    lazy.color.cyan('four');
+    lazy.color.yellow('four');
+    lazy.color.magenta('four');
+    assert.deepEqual(calls, {
+      'ansi-cyan': 1,
+      'ansi-yellow': 1,
+      'ansi-magenta': 1
+    });
+
+    assert.deepEqual(typeof lazy.color, 'object');
+    assert.deepEqual(typeof lazy.color.cyan, 'function');
+    assert.deepEqual(typeof lazy.color.yellow, 'function');
+    assert.deepEqual(typeof lazy.color.magenta, 'function');
+  });
+});

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-lazy-cache.git



More information about the Pkg-javascript-commits mailing list