Socket
Socket
Sign inDemoInstall

benchmarked

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

benchmarked - npm Package Compare versions

Comparing version 0.1.5 to 0.2.0

lib/utils.js

384

index.js
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var ansi = require('ansi');
var chalk = require('chalk');
var read = require('file-reader');
var hasValues = require('has-values');
var forOwn = require('for-own');
var Benchmark = require('benchmark');
var extend = require('extend-shallow');
var cursor = ansi(process.stdout);
var Base = require('base');
var File = require('vinyl');
var utils = require('./lib/utils');
var cursor = utils.ansi(process.stdout);
/**
* Suite constructor.
* Create an instance of Benchmarked with the given `options`.
*
* ```js
* var benchmarks = new Benchmarked();
* ```
* @param {Object} `options`
* @api public
*/
function Suite(options) {
this._fixtures = {};
this._fns = {};
this.options = extend({
cwd: process.cwd(),
name: function(fp) {
var ext = path.extname(fp);
return path.basename(fp, ext);
},
}, options);
function Benchmarked(options) {
if (!(this instanceof Benchmarked)) {
return new Benchmarked(options);
}
Base.call(this, null, options);
this.use(utils.option());
this.use(utils.cwd());
this.defaults(this);
}
/**
* Define fixtures to run benchmarks against.
* Inherit `Base`
*/
Base.extend(Benchmarked);
/**
* Default settings
*/
Benchmarked.prototype.defaults = function(benchmarked) {
this.fixtures = {
files: [],
cache: {},
toFile: function(file) {
file.contents = fs.readFileSync(file.path);
file.content = file.contents.toString();
file.title = util.format('(%d bytes)', file.content.length);
}
};
this.code = {
files: [],
cache: {},
toFile: function(file) {
file.run = require(file.path);
}
};
if (this.options.fixtures) {
this.addFixtures(this.options.fixtures);
}
if (this.options.code) {
this.addCode(this.options.code);
}
};
/**
* Create a vinyl file object.
*
* @param {String} `type` The type of file to create (`code` or `fixture`)
* @param {String} `filepath`
*/
Benchmarked.prototype.toFile = function(type, filepath, options) {
var opts = utils.merge({}, this.options, options);
var file = new File({path: path.resolve(this.cwd, filepath)});
file.key = utils.setKey(file, opts);
file.inspect = function() {
return `<${utils.toTitle(type)} ${this.key} "${this.relative}">`;
};
var fn = opts.toFile || this[type].toFile;
var res = fn.call(this, file);
if (utils.isFile(res)) {
file = res;
}
return file;
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
* @api public
*/
Suite.prototype.fixtures = function(patterns, options) {
options = extend({}, this.options, options);
this._fixtures = read(patterns, options);
return this;
Benchmarked.prototype.filter = function(type, patterns, options) {
if (typeof patterns === 'undefined') {
patterns = '*';
}
if (Array.isArray(patterns)) {
patterns = '{' + patterns.join(',') + '}';
}
var isMatch = utils.mm.matcher(patterns, options);
var results = [];
var self = this;
this.fixtures.files.forEach(function(file) {
if (isMatch(file.basename)) {
file.suite = self.addSuite(file);
results.push(file);
}
});
return results;
};
/**
* Specify the functions to be benchmarked.
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
* @api public
*/
Suite.prototype.add = function(patterns, options) {
options = extend({}, this.options, options);
this._fns = read(patterns, options);
return this;
Benchmarked.prototype.match = function(type, patterns, options) {
return utils.mm.matchKeys(this[type].files, patterns, options);
};
/**
* Run the benchmarks
* Add fixtures to run benchmarks against.
*
* @param {Object} `options`
* @param {Function} `cb`
* @param {Object} `thisArg`
* @api public
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Suite.prototype.run = function(options, cb, thisArg) {
var i = 0;
Benchmarked.prototype.addFile = function(type, file, options) {
if (utils.isGlob(file) || Array.isArray(file)) {
return this.addFiles.apply(this, arguments);
}
if (typeof options == 'function') {
thisArg = cb;
cb = options;
options = {};
type = utils.type(type);
if (typeof file === 'string') {
file = this.toFile(type, file, options);
}
options = extend({}, this.options, options);
var fixtures = this._fixtures;
var add = this._fns;
if (!utils.isFile(file)) {
throw new Error('expected "file" to be a vinyl file object');
}
if (options.fixtures) {
fixtures = read(options.fixtures, options);
this[type].cache[file.path] = file;
this[type].files.push(file);
return this;
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Benchmarked.prototype.addFiles = function(type, files, options) {
var opts = utils.merge({cwd: this.cwd}, this.options, options);
switch (utils.typeOf(files)) {
case 'string':
if (utils.isGlob(files)) {
this.addFiles(type, utils.glob.sync(files, opts), options);
} else {
this.addFile(type, files, options);
}
break;
case 'array':
this.addFilesArray(type, files, options);
break;
case 'object':
this.addFilesObject(type, files, options);
break;
default: {
throw new TypeError('cannot load files: ', util.inspect(arguments));
}
}
return this;
};
if (options.add) {
add = read(options.add, options);
/**
* Add an array of `files` to the files array and cache for the given `type`.
*
* @param {String} `type` Either `code` or `fixtures`
* @param {Array} Files to add
* @param {Object}
*/
Benchmarked.prototype.addFilesArray = function(type, files, options) {
for (var i = 0; i < files.length; i++) {
this.addFile(type, files[i], options);
}
return this;
};
forOwn(fixtures, function(args, name) {
if (typeof cb == 'function') {
args = cb(args);
/**
* Add a fixture to run benchmarks against.
*
* @param {String|Function} `fixture` Filepath or function
*/
Benchmarked.prototype.addFilesObject = function(type, files, options) {
for (var key in files) {
if (files.hasOwnProperty(key)) {
this.addFile(type, files[key], options);
}
}
return this;
};
args = Array.isArray(args) ? args : [args];
/**
* Add a fixture to run benchmarks against.
*
* @param {String|Function} `fixture` Filepath or function
*/
var lead = '';
if (options.showArgs) {
lead = ' - ' + util.inspect(args, null, 2).replace(/[\s\n]+/g, ' ');
Benchmarked.prototype.addFixture = function(file, options) {
this.addFile('fixtures', file, options);
return this;
};
/**
* Add fixtures to run benchmarks against.
*
* ```js
* benchmarks.addFixtures('fixtures/*.txt');
* ```
* @param {String|Array} `patterns` Filepaths or glob patterns.
* @param {Options} `options`
* @api public
*/
Benchmarked.prototype.addFixtures = function(files, options) {
this.addFiles('fixtures', files, options);
return this;
};
/**
* Specify the functions to be benchmarked.
*
* ```js
* benchmarks.addCode('fixtures/*.txt');
* ```
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
* @api public
*/
Benchmarked.prototype.addCode = function(file, options) {
this.addFile('code', file, options);
return this;
};
/**
* Add benchmark suite to the given `fixture` file.
*
* @param {Object} `fixture` vinyl file object
* @api public
*/
Benchmarked.prototype.addSuite = function(fixture, files) {
var colors = utils.colors;
var suite = new utils.Benchmark.Suite(fixture.title, {
name: fixture.key,
onStart: function onStart() {
console.log(colors.cyan('\n# %s %s'), fixture.relative, fixture.title);
},
onComplete: function() {
cursor.write('\n');
}
});
var benchmark = new Benchmark.Suite(name, {
name: name,
onStart: function() {
console.log(chalk.gray('#%s: %s'), ++i, name, lead);
files = files || this.code.files;
files.forEach(function(file) {
suite.add(file.key, {
onCycle: function onCycle(event) {
cursor.horizontalAbsolute();
cursor.eraseLine();
cursor.write(' ' + event.target);
},
fn: function() {
file.run(fixture.content);
return;
},
onComplete: function() {

@@ -110,51 +297,48 @@ cursor.write('\n');

});
});
forOwn(add, function(fn, fnName) {
benchmark.add(fnName, {
onCycle: function onCycle(event) {
cursor.horizontalAbsolute();
cursor.eraseLine();
cursor.write(' ' + event.target);
},
onComplete: function() {
if (options.result) {
var res = fn.apply(null, args);
var msg = chalk.bold('%j');
if (!hasValues(res)) {
msg = chalk.red('%j');
}
console.log(chalk.gray(' result: ') + msg, res);
} else {
cursor.write('\n');
}
},
fn: function() {
fn.apply(thisArg, args);
return;
}
});
if (files.length <= 1) {
return suite;
}
if (options.sample) {
console.log('> ' + fnName + ':\n %j', fn.apply(null, options.sample));
}
});
suite.on('complete', function() {
console.log(' fastest is', colors.green(this.filter('fastest').pluck('name')));
});
benchmark.on('complete', function() {
if (Object.keys(add).length > 1) {
var fastest = chalk.bold(this.filter('fastest').pluck('name'));
console.log(chalk.gray(' fastest is ') + fastest);
}
return suite;
};
/**
* Run the benchmarks.
*
* ```js
* benchmarks.run();
* ```
* @param {Object} `options`
* @param {Function} `cb`
* @param {Object} `thisArg`
* @api public
*/
Benchmarked.prototype.run = function(patterns, options) {
var files = this.filter('fixtures', patterns, options);
if (files.length > 0) {
console.log('Benchmarking: (%d of %d)', files.length, this.fixtures.files.length);
files.forEach(function(file) {
console.log(' · %s', file.key);
});
} else {
console.log('No matches for patterns: %s', util.inspect(patterns));
}
benchmark.run();
files.forEach(function(file) {
file.suite.run();
});
return this;
};
/**
* Expose `Suite`
* Expose `Benchmarked`
*/
module.exports = Suite;
module.exports = Benchmarked;
{
"name": "benchmarked",
"description": "Easily generate benchmarks from a glob of files.",
"version": "0.1.5",
"version": "0.2.0",
"homepage": "https://github.com/jonschlinkert/benchmarked",

@@ -13,3 +13,4 @@ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",

"files": [
"index.js"
"index.js",
"lib"
],

@@ -24,10 +25,30 @@ "main": "index.js",

"dependencies": {
"ansi": "^0.3.0",
"benchmark": "^1.0.0",
"chalk": "^1.0.0",
"extend-shallow": "^1.1.2",
"file-reader": "^1.0.0",
"for-own": "^0.1.3",
"has-values": "^0.1.2"
"ansi": "^0.3.1",
"base": "^0.8.1",
"base-cwd": "^0.1.6",
"base-option": "^0.7.0",
"benchmark": "^2.1.0",
"define-property": "^0.2.5",
"for-own": "^0.1.4",
"has-values": "^0.1.4",
"inflection": "^1.10.0",
"is-glob": "^2.0.1",
"kind-of": "^3.0.2",
"lazy-cache": "^1.0.4",
"log-utils": "^0.1.2",
"micromatch": "^2.3.8",
"mixin-deep": "^1.1.3",
"resolve-glob": "^0.1.8",
"vinyl": "^1.1.1"
},
"devDependencies": {
"gulp": "^3.9.1",
"gulp-eslint": "^2.0.0",
"gulp-format-md": "^0.1.9",
"gulp-istanbul": "^0.10.4",
"gulp-mocha": "^2.2.0",
"gulp-unused": "^0.1.2",
"memoize-path": "^0.1.2",
"mocha": "^2.4.5"
},
"keywords": [

@@ -37,6 +58,25 @@ "benchmark"

"verb": {
"plugins": [
"gulp-format-md"
],
"reflinks": [
"verb"
],
"toc": false,
"layout": "default",
"lint": {
"reflinks": true
},
"tasks": [
"readme"
],
"related": {
"list": []
"list": [
"base",
"base-option",
"base-cli",
"base-pkg"
]
}
}
}

@@ -1,7 +0,5 @@

# benchmarked [![NPM version](https://img.shields.io/npm/v/benchmarked.svg)](https://www.npmjs.com/package/benchmarked)
# benchmarked [![NPM version](https://img.shields.io/npm/v/benchmarked.svg?style=flat)](https://www.npmjs.com/package/benchmarked) [![NPM downloads](https://img.shields.io/npm/dm/benchmarked.svg?style=flat)](https://npmjs.org/package/benchmarked) [![Build Status](https://img.shields.io/travis/jonschlinkert/benchmarked.svg?style=flat)](https://travis-ci.org/jonschlinkert/benchmarked)
> Easily generate benchmarks from a glob of files.
Easily generate benchmarks from a glob of files.
This is an opinionated wrapper for [benchmark.js](http://benchmarkjs.com/) to make it easier to do benchmarks. Concept is from [remarkable](https://github.com/jonschlinkert/remarkable/tree/master/benchmark).
## Install

@@ -12,13 +10,14 @@

```sh
$ npm i benchmarked
$ npm install benchmarked --save
```
This is an opinionated wrapper for [benchmarked.js](http://benchmarkjs.com/) to make it easier to do benchmarks. Concept is from [remarkable](https://github.com/jonschlinkert/remarkable/tree/master/benchmark)
## Usage
```js
var Suite = require('benchmarked');
var suite = new Suite({
cwd: 'benchmark', // optionally define a current working directory
add: 'my-functions/*.js', // path or glob pattern to functions
fixtures: 'my-fixtures/*.txt' // path or glob pattern to fixtures
var suite = require('benchmarked')({
cwd: 'benchmark', // optionally define a base directory for code and fixtures
fixtures: 'my-fixtures/*.txt', // path or glob pattern to fixtures
code: 'my-functions/*.js' // path or glob pattern to code files
});

@@ -32,58 +31,81 @@

### Alternative setup
## API
Add functions to run:
### [Benchmarked](index.js#L21)
```js
suite.add('benchmark/my-functions/*.js');
```
Create an instance of Benchmarked with the given `options`.
Add fixtures to use:
**Params**
* `options` **{Object}**
**Example**
```js
suite.fixtures('benchmark/my-fixtures/*.txt');
var benchmarks = new Benchmarked();
```
Run benchmarks for each fixture and function defined:
### [.addFixtures](index.js#L240)
Add fixtures to run benchmarks against.
**Params**
* `patterns` **{String|Array}**: Filepaths or glob patterns.
* `options` **{Options}**
**Example**
```js
suite.run();
benchmarks.addFixtures('fixtures/*.txt');
```
Pass additional arguments beyond the content in the fixtures:
### [.addCode](index.js#L256)
Specify the functions to be benchmarked.
**Params**
* `patterns` **{String|Array}**: Filepath(s) or glob patterns.
* `options` **{Options}**
**Example**
```js
// `fixture` is the content returned for each fixture
suite.run(function (fixture) {
// this array will be applied as arguments to each function
return [fixture, ':'];
});
benchmarks.addCode('fixtures/*.txt');
```
## Options
### [.addSuite](index.js#L268)
### options.cwd
Add benchmark suite to the given `fixture` file.
Specify a current working directory to be used for both fixtures and functions:
**Params**
* `fixture` **{Object}**: vinyl file object
### [.run](index.js#L322)
Run the benchmarks.
**Params**
* `options` **{Object}**
* `cb` **{Function}**
* `thisArg` **{Object}**
**Example**
```js
var suite = new Suite({cwd: 'example'});
benchmarks.run();
```
### options.name
## Related projects
Pass a custom naming function to be used on functions. This only changes the name
that displays in the command line for each function:
You might also be interested in these projects:
```js
var path = require('path');
* [base-cli](https://www.npmjs.com/package/base-cli): Plugin for base-methods that maps built-in methods to CLI args (also supports methods from a… [more](https://www.npmjs.com/package/base-cli) | [homepage](https://github.com/node-base/base-cli)
* [base-option](https://www.npmjs.com/package/base-option): Adds a few options methods to base, like `option`, `enable` and `disable`. See the readme… [more](https://www.npmjs.com/package/base-option) | [homepage](https://github.com/node-base/base-option)
* [base-pkg](https://www.npmjs.com/package/base-pkg): Plugin for adding a `pkg` method that exposes pkg-store to your base application. | [homepage](https://github.com/node-base/base-pkg)
* [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://www.npmjs.com/package/base) | [homepage](https://github.com/node-base/base)
var suite = new Suite({
// this is the actual default
name: function(filepath) {
return path.basename(filepath);
}
});
```
## Contributing

@@ -93,2 +115,16 @@

## 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

@@ -99,3 +135,3 @@

```sh
$ npm i -d && npm test
$ npm install -d && npm test
```

@@ -107,12 +143,12 @@

+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright © 2014-2016 [Jon Schlinkert](https://github.com/jonschlinkert)
Released under the MIT license.
Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT license](https://github.com/jonschlinkert/benchmarked/blob/master/LICENSE).
***
_This file was generated by [verb](https://github.com/verbose/verb) on January 25, 2016._
_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc