### Clone and Install Project Dependencies
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/js-sdsl/README.md
Instructions for cloning the project repository locally, navigating into the project directory, installing dependencies using npm, and starting the development server.
```bash
$ git clone https://github.com/js-sdsl/js-sdl.git
$ cd js-sdsl
$ npm install
$ npm run dev # development mode
```
--------------------------------
### Start Development Servers (Bash)
Source: https://context7.com/jamesshore/testing-without-mocks-complex/llms.txt
Shell scripts to start the WWW and ROT-13 development servers on specified ports for Mac/Linux and Windows.
```bash
# Mac/Linux
./serve_dev.sh 5010 5011
# Windows
.\serve_dev.cmd 5010 5011
# Access the web interface at http://localhost:5010
```
--------------------------------
### Install rimraf using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/rimraf/README.md
This command installs the rimraf package globally, making its command-line interface available.
```bash
npm install rimraf -g
```
--------------------------------
### Usage Example: js-sdsl with npm (Node.js)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/js-sdsl/README.md
Shows how to import and use js-sdsl in a Node.js environment using either ES Modules or CommonJS syntax. It includes an example of initializing and using an OrderedMap.
```javascript
// esModule
import { OrderedMap } from 'js-sdsl';
// commonJs
const { OrderedMap } = require('js-sdsl');
const myOrderedMap = new OrderedMap();
myOrderedMap.setElement(1, 2);
console.log(myOrderedMap.getElementByKey(1)); // 2
```
--------------------------------
### AllServers Application Startup (JavaScript)
Source: https://context7.com/jamesshore/testing-without-mocks-complex/llms.txt
JavaScript code for the AllServers class, handling command-line arguments and starting both WWW and ROT-13 servers. Shows production and test usage with nullable dependencies.
```javascript
import { AllServers } from "./all_servers.js";
// Production usage - creates and starts servers
AllServers.create().startAsync();
// Usage: node serve.js [www_port] [rot13_port]
// Example: node serve.js 5010 5011
// For testing - inject nullable dependencies
import { Log } from "infrastructure/log.js";
import { CommandLine } from "infrastructure/command_line.js";
import { HttpServer } from "http/http_server.js";
const testServers = new AllServers(
Log.createNull(),
CommandLine.createNull({ args: ["5010", "5011"] }),
HttpServer.createNull(),
HttpServer.createNull()
);
await testServers.startAsync();
```
--------------------------------
### Glob Usage Example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/glob/README.md
Demonstrates how to install and use the glob library for asynchronous file searching.
```APIDOC
## Installation
```bash
npm i glob
```
## Asynchronous Usage Example
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
```
--------------------------------
### Install and Test Project Dependencies
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/ajv/README.md
This snippet demonstrates the standard commands to install project dependencies, update git submodules, and run tests. It's a common setup for Node.js projects.
```bash
npm install
git submodule update --init
npm test
```
--------------------------------
### Usage Example: js-sdsl in Browser
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/js-sdsl/README.md
Demonstrates how to include and use js-sdsl in a web browser using a script tag. It shows how to import various data structures and perform basic operations.
```html
```
--------------------------------
### Install Anymatch
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/anymatch/README.md
Install the anymatch module using npm. This is the first step to using the library in your project.
```sh
npm install anymatch
```
--------------------------------
### Install resolve-from
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/resolve-from/readme.md
Installs the 'resolve-from' package using npm. This is the first step before using the package in your project.
```bash
npm install resolve-from
```
--------------------------------
### Usage Example: Find the first existing file
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/p-locate/readme.md
This JavaScript example demonstrates how to use 'p-locate' to find the first file in a list that exists on disk. It utilizes the 'path-exists' module as the testing function. The example is wrapped in an async IIFE to use await.
```javascript
const pathExists = require('path-exists');
const pLocate = require('p-locate');
const files = [
'unicorn.png',
'rainbow.png', // Only this one actually exists on disk
'pony.png'
];
(async () => {
const foundPath = await pLocate(files, file => pathExists(file));
console.log(foundPath);
//=> 'rainbow'
})();
```
--------------------------------
### LRU Cache Usage Example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/lru-cache/README.md
Demonstrates how to initialize and use the LRU cache. It shows setting options like max size, item length calculation, and disposal of items. It also illustrates basic cache operations like setting, getting, and resetting the cache, including handling of object keys.
```javascript
var LRU = require("lru-cache")
, options = { max: 500
, length: function (n, key) { return n * 2 + key.length }
, dispose: function (key, n) { n.close() }
, maxAge: 1000 * 60 * 60 }
, cache = new LRU(options)
, otherCache = new LRU(50) // sets just the max size
cache.set("key", "value")
cache.get("key") // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.reset() // empty the cache
```
--------------------------------
### Installation
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/js-yaml/README.md
Instructions for installing the js-yaml module for Node.js and as a global CLI executable.
```APIDOC
## Installation
### YAML module for node.js
```bash
npm install js-yaml
```
### CLI executable
If you want to inspect your YAML files from CLI, install js-yaml globally:
```bash
npm install -g js-yaml
```
#### Usage
```
usage: js-yaml [-h] [-v] [-c] [-t] file
Positional arguments:
file File with YAML document(s)
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-c, --compact Display errors in compact mode
-t, --trace Show stack trace on error
```
```
--------------------------------
### Install @nodelib/fs.scandir using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/@nodelib/fs.scandir/README.md
This command installs the @nodelib/fs.scandir package, which is used for listing files and directories. It is a standard npm installation command.
```console
npm install @nodelib/fs.scandir
```
--------------------------------
### Install fast-deep-equal
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/fast-deep-equal/README.md
Installs the fast-deep-equal package using npm. This is the primary installation command for the library.
```bash
npm install fast-deep-equal
```
--------------------------------
### Install eslint-visitor-keys
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/eslint-utils/node_modules/eslint-visitor-keys/README.md
Installs the 'eslint-visitor-keys' package using npm. Requires Node.js version 10.0.0 or later.
```bash
npm install eslint-visitor-keys
```
--------------------------------
### Install Production Dependencies
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/lodash/release.md
Installs only production dependencies for the project. This is often done after development dependencies have been installed to prepare the project for deployment or further steps.
```sh
cd ../../; npm i --production; cd ../../
```
--------------------------------
### Micromatch Quickstart: Basic Usage
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/micromatch/README.md
Demonstrates the basic usage of micromatch for matching strings against glob patterns. It shows how to import the library and use the main `micromatch` function for filtering lists.
```javascript
const micromatch = require('micromatch');
// micromatch(list, patterns[, options]);
console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])); //=> ['foo', 'bar', 'baz']
console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])); //=> ['foo', 'qux']
```
--------------------------------
### Usage Example: Get current file name with callsites
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/callsites/readme.md
This JavaScript example demonstrates how to use the 'callsites' module to retrieve the file name of the current script. It imports the module and then accesses the first callsite object to get its file name.
```javascript
const callsites = require('callsites');
function unicorn() {
console.log(callsites()[0].getFileName());
//=> '/Users/sindresorhus/dev/callsites/test.js'
}
unicorn();
```
--------------------------------
### Install fill-range with npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/fill-range/README.md
This command installs the fill-range package as a project dependency. It is typically used in the initial setup phase of a project.
```sh
npm install --save fill-range
```
--------------------------------
### Install locate-path using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/locate-path/readme.md
This command installs the locate-path package. It's a prerequisite for using the package in your Node.js projects.
```bash
npm install locate-path
```
--------------------------------
### Cloning and Setting Up Repository with Git
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/chai/CONTRIBUTING.md
This snippet demonstrates the initial steps for contributing to a GitHub project. It involves forking the repository, cloning it locally, and setting up the 'upstream' remote to track the original project's changes. This is essential for keeping your local copy updated and for submitting pull requests.
```bash
git clone https://github.com//
cd
git remote add upstream https://github.com//
```
--------------------------------
### Install p-locate using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/p-locate/readme.md
This command installs the 'p-locate' package using npm, making it available for use in your Node.js project. Ensure you have Node.js and npm installed.
```bash
$ npm install p-locate
```
--------------------------------
### onIgnore Callback Example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/picomatch/README.md
Shows how to use the `onIgnore` callback function, which is triggered when a pattern is ignored. This example uses an `ignore` pattern to exclude matches starting with 'f'.
```javascript
const onIgnore = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
--------------------------------
### Install Benchmark Dependencies
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/micromatch/README.md
Installs the necessary dependencies to run the performance benchmarks for minimatch and micromatch. This command should be executed within the 'bench' directory.
```shell
cd bench && npm install
```
--------------------------------
### Install and Test Project Dependencies (npm)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/diff/CONTRIBUTING.md
Installs project dependencies using npm and runs the test suite. This is a standard procedure for setting up and verifying the project's state before making changes or building.
```shell
npm install
npm test
```
--------------------------------
### Install callsites using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/callsites/readme.md
This snippet shows how to install the 'callsites' npm package. It is a prerequisite for using the module in a Node.js project.
```bash
npm install callsites
```
--------------------------------
### Install parent-module using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/parent-module/readme.md
This snippet shows the command to install the 'parent-module' package using npm. It's a prerequisite for using the module in your Node.js project.
```bash
npm install parent-module
```
--------------------------------
### Incorrect Code Example in TypeScript
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/@typescript-eslint/eslint-plugin/docs/rules/TEMPLATE.md
This snippet shows an incorrect implementation related to testing without mocks. It serves as a negative example to guide developers away from common pitfalls. Further details on the rule's purpose and context can be found in the primary documentation.
```typescript
// To fill out: incorrect code
```
--------------------------------
### Install p-limit using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/p-limit/readme.md
This command installs the p-limit package using npm. It is a prerequisite for using the library in your Node.js project.
```bash
npm install p-limit
```
--------------------------------
### Install string-width with npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/string-width/readme.md
This snippet shows the command to install the string-width package using npm, the Node Package Manager. It's a prerequisite for using the module in a Node.js project.
```bash
npm install string-width
```
--------------------------------
### Initialize Optionator and Parse Arguments (JavaScript)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/optionator/README.md
This snippet demonstrates how to initialize Optionator with custom options and then parse command-line arguments using `process.argv`. It includes basic option definitions for 'help' and 'count' and shows how to conditionally display help text.
```javascript
var optionator = require('optionator')({
prepend: 'Usage: cmd [options]',
append: 'Version 1.0.0',
options: [{
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'displays help'
}, {
option: 'count',
alias: 'c',
type: 'Int',
description: 'number of things',
example: 'cmd --count 2'
}]
});
var options = optionator.parseArgv(process.argv);
if (options.help) {
console.log(optionator.generateHelp());
}
...
```
--------------------------------
### Install path-key using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/path-key/readme.md
This snippet shows how to install the path-key package using npm, the Node Package Manager. This is a prerequisite for using the package in a Node.js project.
```bash
npm install path-key
```
--------------------------------
### Install Dependencies
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/lodash/release.md
Installs project dependencies using npm. This is a standard step for most Node.js projects to ensure all required packages are available.
```sh
npm i
```
--------------------------------
### Install get-caller-file using Yarn
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/get-caller-file/README.md
This command installs the get-caller-file package as a project dependency using the Yarn package manager. It's a prerequisite for using the utility in your Node.js project.
```bash
yarn add get-caller-file
```
--------------------------------
### Generate Readme Documentation (Shell)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/picomatch/README.md
Illustrates the command to generate the project's README.md file using the 'verb' documentation generator. This command installs necessary global packages and then executes the verb command.
```shell
npm install -g verbose/verb#dev verb-generate-readme && verb
```
--------------------------------
### Deno Example for yargs-parser
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/yargs-parser/README.md
Provides an example of using yargs-parser with Deno. It demonstrates how to import the parser and use it to parse arguments, including specifying types like strings.
```typescript
import parser from "https://deno.land/x/yargs_parser/deno.ts";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
--------------------------------
### Usage Example: Get parent module path in Node.js
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/parent-module/readme.md
Demonstrates how to use the 'parent-module' package in a Node.js application. It requires the module and then calls the default function to log the parent module's path.
```javascript
// bar.js
const parentModule = require('parent-module');
module.exports = () => {
console.log(parentModule());
//=> '/Users/sindresorhus/dev/unicorn/foo.js'
};
// foo.js
const bar = require('./bar');
bar();
```
--------------------------------
### Espree tokenize() method example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/espree/README.md
This example shows how to use the `espree.tokenize()` method to get the tokens of a JavaScript code string. It accepts the code and optional configuration. The `ecmaVersion` option is set to 6 for ES6 compatibility. The output is an array of token objects.
```javascript
import * as espree from "espree";
const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 });
console.log(tokens);
```
--------------------------------
### Basic flat-cache usage in JavaScript
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/flat-cache/README.md
Demonstrates the fundamental operations of flat-cache in JavaScript, including loading a cache by ID, setting and getting key-value pairs, retrieving all cached data, removing keys, and saving changes to disk. It also shows how to load a cache from a specific directory.
```javascript
var flatCache = require('flat-cache');
// loads the cache, if one does not exists for the given
// Id a new one will be prepared to be created
var cache = flatCache.load('cacheId');
// sets a key on the cache
cache.setKey('key', { foo: 'var' });
// get a key from the cache
cache.getKey('key'); // { foo: 'var' }
// fetch the entire persisted object
cache.all(); // { 'key': { foo: 'var' } }
// remove a key
cache.removeKey('key'); // removes a key from the cache
// save it to disk
cache.save(); // very important, if you don't save no changes will be persisted.
// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys
// loads the cache from a given directory, if one does
// not exists for the given Id a new one will be prepared to be created
var cache = flatCache.load('cacheId', path.resolve('./path/to/folder'));
```
--------------------------------
### Get Caller File Path in JavaScript
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/get-caller-file/README.md
This JavaScript snippet demonstrates how to use the get-caller-file utility. It requires the package and then calls it within a function to retrieve the file path of the function that invoked it. This is a core example of the package's functionality.
```javascript
// ./foo.js
const getCallerFile = require('get-caller-file');
module.exports = function() {
return getCallerFile(); // figures out who called it
};
```
```javascript
// index.js
const foo = require('./foo');
foo() // => /full/path/to/this/file/index.js
```
--------------------------------
### Tilde Version Range Examples
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/semver/README.md
Illustrates the behavior of Tilde (~) version ranges, which allow patch-level or minor-level changes depending on the specified version. It covers various formats and their corresponding semantic versioning interpretations.
```text
* `~1.2.3` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0`
```
--------------------------------
### Developer Setup for ModuleImporter
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/@humanwhocodes/module-importer/README.md
Provides instructions for setting up the development environment for ModuleImporter. This includes forking, cloning, installing dependencies, and running tests.
```bash
1. Fork the repository
2. Clone your fork
3. Run `npm install` to setup dependencies
4. Run `npm test` to run tests
```
--------------------------------
### Install and Use Flat Globally
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/flat/README.md
Demonstrates installing the 'flat' command globally and then using it to process a JSON file.
```sh
npm i -g flat && flat foo.json
```
--------------------------------
### Make POST Request to ROT-13 Service with httpie
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/README.md
This example demonstrates how to interact with the ROT-13 service using the httpie command-line tool. It shows the request headers, body, and the expected success response.
```sh
~ % http post :5011/rot13/transform content-type:application/json x-correlation-id:my-id text=hello -v
POST /rot13/transform HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 17
Host: localhost:5011
User-Agent: HTTPie/3.2.1
content-type: application/json
x-correlation-id: my-id
{
"text": "hello"
}
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 23
Date: Sat, 04 Feb 2023 08:33:00 GMT
Keep-Alive: timeout=5
content-type: application/json
{
"transformed": "uryyb"
}
```
--------------------------------
### Get high-resolution time (Browser)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/@sinonjs/fake-timers/README.md
Mimics the browser's `performance.now()` function, providing high-resolution time measurements relative to the navigation start of the document. This method is only available in browser environments.
```javascript
clock.performance.now()
```
--------------------------------
### Install Development Dependencies and Run Benchmarks
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/braces/README.md
This command installs the necessary development dependencies for the project and then executes the benchmark suite. It's used to verify performance claims and compare different implementations.
```bash
npm i -d && npm benchmark
```
--------------------------------
### he Binary Command-Line Usage
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/he/README.md
Provides examples of using the `he` command-line tool for encoding and decoding HTML entities. It covers installation, encoding, decoding, and file input/output operations.
```bash
npm install -g he
```
```bash
$ he --encode 'föo ♥ bår 𝌆 baz'
föo ♥ bår 𝌆 baz
```
```bash
$ he --encode --use-named-refs 'föo ♥ bår 𝌆 baz'
föo ♥ bår 𝌆 baz
```
```bash
$ he --decode 'föo ♥ bår 𝌆 baz'
föo ♥ bår 𝌆 baz
```
```bash
$ he --encode < foo.txt > foo-escaped.html
```
```bash
$ curl -sL "http://git.io/HnfEaw" | he --encode > escaped.html
```
```bash
$ he --decode < foo-escaped.html > foo.txt
```
```bash
$ curl -sL "http://git.io/HnfEaw" | he --decode > decoded.txt
```
--------------------------------
### Install binary-extensions using npm
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/binary-extensions/readme.md
This command installs the 'binary-extensions' package from the npm registry. It is a prerequisite for using the package in your Node.js projects.
```bash
npm install binary-extensions
```
--------------------------------
### Transforming Objects with Visitor Function in require-directory
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/require-directory/README.markdown
This example shows how a 'visit' function can transform loaded modules. By returning a value from the visitor function, you can modify the object that gets added to the exported hash.
```javascript
var requireDirectory = require('require-directory'),
visitor = function(obj) {
return obj(new Date());
},
hash = requireDirectory(module, {visit: visitor});
```
--------------------------------
### Basic Usage of Picomatch
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/picomatch/README.md
Demonstrates the basic usage of picomatch. It shows how to create a matcher function from a glob pattern and then use that function to test strings.
```javascript
const pm = require('picomatch');
const isMatch = pm('*.js');
console.log(isMatch('abcd')); //=> false
console.log(isMatch('a.js')); //=> true
console.log(isMatch('a.md')); //=> false
console.log(isMatch('a/b.js')); //=> false
```
--------------------------------
### Synchronous Example: Reusing objects with reusify
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/reusify/README.md
This example shows how to use 'reusify' to manage a pool of 'MyObject' instances for synchronous operations. It demonstrates getting an object from the pool, setting its state, performing an action, resetting the state, and releasing the object back to the pool. Proper state resetting is crucial for subsequent uses.
```javascript
var reusify = require('reusify')
var fib = require('reusify/benchmarks/fib')
var instance = reusify(MyObject)
// get an object from the cache,
// or creates a new one when cache is empty
var obj = instance.get()
// set the state
obj.num = 100
obj.func()
// reset the state.
// if the state contains any external object
// do not use delete operator (it is slow)
// prefer set them to null
obj.num = 0
// store an object in the cache
instance.release(obj)
function MyObject () {
// you need to define this property
// so V8 can compile MyObject into an
// hidden class
this.next = null
this.num = 0
var that = this
// this function is never reallocated,
// so it can be optimized by V8
this.func = function () {
if (null) {
// do nothing
} else {
// calculates fibonacci
fib(that.num)
}
}
}
```
--------------------------------
### Micromatch Quickstart: Boolean Matching with isMatch
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/micromatch/README.md
Illustrates how to use the `micromatch.isMatch()` function for boolean checks. This function returns true if a single string matches the provided glob pattern(s), and false otherwise.
```javascript
console.log(micromatch.isMatch('foo', 'f*')) //=> true
console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true
```
--------------------------------
### Basic Usage of yocto-queue
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/yocto-queue/readme.md
Demonstrates the basic usage of the yocto-queue. It shows how to create a new queue, enqueue elements, check its size, iterate over its elements, and dequeue elements.
```javascript
const Queue = require('yocto-queue');
const queue = new Queue();
queue.enqueue('🦄');
queue.enqueue('🌈');
console.log(queue.size);
//=> 2
console.log(...queue);
//=> '🦄 🌈'
console.log(queue.dequeue());
//=> '🦄'
console.log(queue.dequeue());
//=> '🌈'
```
--------------------------------
### HomePageController Web Handler
Source: https://context7.com/jamesshore/testing-without-mocks-complex/llms.txt
Handles GET and POST requests for the home page, orchestrating calls to the ROT-13 service with timeout handling. It supports both production and test usage with simulated requests.
```javascript
import { HomePageController } from "./www/home_page/home_page_controller.js";
import { HttpServerRequest } from "http/http_server_request.js";
import { WwwConfig } from "./www/www_config.js";
// Production usage
const controller = HomePageController.create();
// Test usage with nulled dependencies
const testController = HomePageController.createNull();
// Simulate GET request (returns empty form)
const getRequest = HttpServerRequest.createNull({
method: "GET",
path: "/"
});
const config = WwwConfig.createTestInstance({
rot13ServicePort: 5011,
correlationId: "test-id"
});
const getResponse = await testController.getAsync(getRequest, config);
console.log(getResponse.status); // 200
// Returns HTML form for text entry
// Simulate POST request (transforms text)
const postRequest = HttpServerRequest.createNull({
method: "POST",
path: "/",
body: "text=hello"
});
const postResponse = await testController.postAsync(postRequest, config);
console.log(postResponse.status); // 200
// Returns HTML with transformed text in form field
```
--------------------------------
### Spawn NPM Asynchronously and Synchronously with Cross-Spawn (JavaScript)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/cross-spawn/README.md
Demonstrates how to use the cross-spawn package to spawn the 'npm' command both asynchronously and synchronously. It shows the basic usage with command and arguments, and includes the 'stdio: inherit' option for direct output handling. This snippet is a direct replacement for Node.js's built-in spawn functions.
```javascript
const spawn = require('cross-spawn');
// Spawn NPM asynchronously
const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
// Spawn NPM synchronously
const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```
--------------------------------
### Async locatePath usage example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/locate-path/readme.md
Demonstrates how to use the asynchronous `locatePath` function to find the first existing file in an array of paths. It returns a Promise that resolves to the found path or undefined.
```javascript
const locatePath = require('locate-path');
const files = [
'unicorn.png',
'rainbow.png', // Only this one actually exists on disk
'pony.png'
];
(async () => {
console.log(await locatePath(files));
//=> 'rainbow'
})();
```
--------------------------------
### Initializing cliui with Options (JavaScript)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/cliui/README.md
Shows how to initialize the cliui library with specific options. This includes setting the maximum width of the UI and enabling or disabling text wrapping.
```javascript
cliui = require('cliui')
// Example with width
const uiWidth = cliui({ width: 80 })
// Example with wrap enabled
const uiWrap = cliui({ wrap: true })
// Example with no width provided (defaults to terminal width or 80)
const uiDefault = cliui()
```
--------------------------------
### Get Visitor Keys for a Specific AST Node
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/eslint-utils/node_modules/eslint-visitor-keys/README.md
Obtains the visitor keys for any given AST node. This function is useful for traversing unknown node types and excludes properties like 'parent', 'leadingComments', 'trailingComments', and those starting with '_'.
```javascript
const node = {
type: "AssignmentExpression",
left: { type: "Identifier", name: "foo" },
right: { type: "Literal", value: 0 }
}
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
```
--------------------------------
### Deno/ESM CLI UI Creation with cliui (TypeScript)
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/cliui/README.md
Illustrates how to use cliui with Deno and ESM modules. This example shows the import statement for Deno and the basic setup for creating a UI layout.
```typescript
import cliui from "https://deno.land/x/cliui/deno.ts";
const ui = cliui({})
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div({
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
})
console.log(ui.toString())
```
--------------------------------
### semver command-line utility help
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/semver/README.md
Displays the help information for the semver command-line utility. This shows available options for version comparison, incrementing, and coercion.
```bash
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] [ [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range
Print versions that match the specified range.
-i --increment []
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
--------------------------------
### Synchronous locatePath.sync usage example
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/locate-path/readme.md
Illustrates the synchronous usage of `locatePath.sync`. This function directly returns the first existing path or undefined without using Promises, suitable for scenarios where async is not required.
```javascript
const locatePath = require('locate-path');
const files = [
'unicorn.png',
'rainbow.png', // Only this one actually exists on disk
'pony.png'
];
console.log(locatePath.sync(files));
//=> 'rainbow'
```
--------------------------------
### Asynchronous Schema Compilation with Ajv
Source: https://github.com/jamesshore/testing-without-mocks-complex/blob/javascript/node_modules/ajv/README.md
This JavaScript example shows how to compile a JSON Schema asynchronously using Ajv. It requires a `loadSchema` function to fetch remote references and uses `compileAsync` to get a validation function.
```javascript
var ajv = new Ajv({ loadSchema: loadSchema });
ajv.compileAsync(schema).then(function (validate) {
var valid = validate(data);
// ...
});
function loadSchema(uri) {
return request.json(uri).then(function (res) {
if (res.statusCode >= 400)
throw new Error('Loading error: ' + res.statusCode);
return res.body;
});
}
```