Commit f064c792 authored by Muddsair Sharif's avatar Muddsair Sharif
Browse files

Initial commit

parents
Pipeline #8 canceled with stages
'use strict';
var util = require('util');
var union = require('arr-union');
var define = require('define-property');
var staticExtend = require('static-extend');
var isObj = require('isobject');
/**
* Expose class utils
*/
var cu = module.exports;
/**
* Expose class utils: `cu`
*/
cu.isObject = function isObject(val) {
return isObj(val) || typeof val === 'function';
};
/**
* Returns true if an array has any of the given elements, or an
* object has any of the give keys.
*
* ```js
* cu.has(['a', 'b', 'c'], 'c');
* //=> true
*
* cu.has(['a', 'b', 'c'], ['c', 'z']);
* //=> true
*
* cu.has({a: 'b', c: 'd'}, ['c', 'z']);
* //=> true
* ```
* @param {Object} `obj`
* @param {String|Array} `val`
* @return {Boolean}
* @api public
*/
cu.has = function has(obj, val) {
val = cu.arrayify(val);
var len = val.length;
if (cu.isObject(obj)) {
for (var key in obj) {
if (val.indexOf(key) > -1) {
return true;
}
}
var keys = cu.nativeKeys(obj);
return cu.has(keys, val);
}
if (Array.isArray(obj)) {
var arr = obj;
while (len--) {
if (arr.indexOf(val[len]) > -1) {
return true;
}
}
return false;
}
throw new TypeError('expected an array or object.');
};
/**
* Returns true if an array or object has all of the given values.
*
* ```js
* cu.hasAll(['a', 'b', 'c'], 'c');
* //=> true
*
* cu.hasAll(['a', 'b', 'c'], ['c', 'z']);
* //=> false
*
* cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']);
* //=> false
* ```
* @param {Object|Array} `val`
* @param {String|Array} `values`
* @return {Boolean}
* @api public
*/
cu.hasAll = function hasAll(val, values) {
values = cu.arrayify(values);
var len = values.length;
while (len--) {
if (!cu.has(val, values[len])) {
return false;
}
}
return true;
};
/**
* Cast the given value to an array.
*
* ```js
* cu.arrayify('foo');
* //=> ['foo']
*
* cu.arrayify(['foo']);
* //=> ['foo']
* ```
*
* @param {String|Array} `val`
* @return {Array}
* @api public
*/
cu.arrayify = function arrayify(val) {
return val ? (Array.isArray(val) ? val : [val]) : [];
};
/**
* Noop
*/
cu.noop = function noop() {
return;
};
/**
* Returns the first argument passed to the function.
*/
cu.identity = function identity(val) {
return val;
};
/**
* Returns true if a value has a `contructor`
*
* ```js
* cu.hasConstructor({});
* //=> true
*
* cu.hasConstructor(Object.create(null));
* //=> false
* ```
* @param {Object} `value`
* @return {Boolean}
* @api public
*/
cu.hasConstructor = function hasConstructor(val) {
return cu.isObject(val) && typeof val.constructor !== 'undefined';
};
/**
* Get the native `ownPropertyNames` from the constructor of the
* given `object`. An empty array is returned if the object does
* not have a constructor.
*
* ```js
* cu.nativeKeys({a: 'b', b: 'c', c: 'd'})
* //=> ['a', 'b', 'c']
*
* cu.nativeKeys(function(){})
* //=> ['length', 'caller']
* ```
*
* @param {Object} `obj` Object that has a `constructor`.
* @return {Array} Array of keys.
* @api public
*/
cu.nativeKeys = function nativeKeys(val) {
if (!cu.hasConstructor(val)) return [];
var keys = Object.getOwnPropertyNames(val);
if ('caller' in val) keys.push('caller');
return keys;
};
/**
* Returns property descriptor `key` if it's an "own" property
* of the given object.
*
* ```js
* function App() {}
* Object.defineProperty(App.prototype, 'count', {
* get: function() {
* return Object.keys(this).length;
* }
* });
* cu.getDescriptor(App.prototype, 'count');
* // returns:
* // {
* // get: [Function],
* // set: undefined,
* // enumerable: false,
* // configurable: false
* // }
* ```
*
* @param {Object} `obj`
* @param {String} `key`
* @return {Object} Returns descriptor `key`
* @api public
*/
cu.getDescriptor = function getDescriptor(obj, key) {
if (!cu.isObject(obj)) {
throw new TypeError('expected an object.');
}
if (typeof key !== 'string') {
throw new TypeError('expected key to be a string.');
}
return Object.getOwnPropertyDescriptor(obj, key);
};
/**
* Copy a descriptor from one object to another.
*
* ```js
* function App() {}
* Object.defineProperty(App.prototype, 'count', {
* get: function() {
* return Object.keys(this).length;
* }
* });
* var obj = {};
* cu.copyDescriptor(obj, App.prototype, 'count');
* ```
* @param {Object} `receiver`
* @param {Object} `provider`
* @param {String} `name`
* @return {Object}
* @api public
*/
cu.copyDescriptor = function copyDescriptor(receiver, provider, name) {
if (!cu.isObject(receiver)) {
throw new TypeError('expected receiving object to be an object.');
}
if (!cu.isObject(provider)) {
throw new TypeError('expected providing object to be an object.');
}
if (typeof name !== 'string') {
throw new TypeError('expected name to be a string.');
}
var val = cu.getDescriptor(provider, name);
if (val) Object.defineProperty(receiver, name, val);
};
/**
* Copy static properties, prototype properties, and descriptors
* from one object to another.
*
* @param {Object} `receiver`
* @param {Object} `provider`
* @param {String|Array} `omit` One or more properties to omit
* @return {Object}
* @api public
*/
cu.copy = function copy(receiver, provider, omit) {
if (!cu.isObject(receiver)) {
throw new TypeError('expected receiving object to be an object.');
}
if (!cu.isObject(provider)) {
throw new TypeError('expected providing object to be an object.');
}
var props = Object.getOwnPropertyNames(provider);
var keys = Object.keys(provider);
var len = props.length,
key;
omit = cu.arrayify(omit);
while (len--) {
key = props[len];
if (cu.has(keys, key)) {
define(receiver, key, provider[key]);
} else if (!(key in receiver) && !cu.has(omit, key)) {
cu.copyDescriptor(receiver, provider, key);
}
}
};
/**
* Inherit the static properties, prototype properties, and descriptors
* from of an object.
*
* @param {Object} `receiver`
* @param {Object} `provider`
* @param {String|Array} `omit` One or more properties to omit
* @return {Object}
* @api public
*/
cu.inherit = function inherit(receiver, provider, omit) {
if (!cu.isObject(receiver)) {
throw new TypeError('expected receiving object to be an object.');
}
if (!cu.isObject(provider)) {
throw new TypeError('expected providing object to be an object.');
}
var keys = [];
for (var key in provider) {
keys.push(key);
receiver[key] = provider[key];
}
keys = keys.concat(cu.arrayify(omit));
var a = provider.prototype || provider;
var b = receiver.prototype || receiver;
cu.copy(b, a, keys);
};
/**
* Returns a function for extending the static properties,
* prototype properties, and descriptors from the `Parent`
* constructor onto `Child` constructors.
*
* ```js
* var extend = cu.extend(Parent);
* Parent.extend(Child);
*
* // optional methods
* Parent.extend(Child, {
* foo: function() {},
* bar: function() {}
* });
* ```
* @param {Function} `Parent` Parent ctor
* @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype.
* @param {Function} `Child` Child ctor
* @param {Object} `proto` Optionally pass additional prototype properties to inherit.
* @return {Object}
* @api public
*/
cu.extend = function() {
// keep it lazy, instead of assigning to `cu.extend`
return staticExtend.apply(null, arguments);
};
/**
* Bubble up events emitted from static methods on the Parent ctor.
*
* @param {Object} `Parent`
* @param {Array} `events` Event names to bubble up
* @api public
*/
cu.bubble = function(Parent, events) {
events = events || [];
Parent.bubble = function(Child, arr) {
if (Array.isArray(arr)) {
events = union([], events, arr);
}
var len = events.length;
var idx = -1;
while (++idx < len) {
var name = events[idx];
Parent.on(name, Child.emit.bind(Child, name));
}
cu.bubble(Child, events);
};
};
The MIT License (MIT)
Copyright (c) 2015, 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.
# define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property)
> Define a non-enumerable property on an object.
## Install
Install with [npm](https://www.npmjs.com/)
```sh
$ npm i define-property --save
```
## Usage
**Params**
* `obj`: The object on which to define the property.
* `prop`: The name of the property to be defined or modified.
* `descriptor`: The descriptor for the property being defined or modified.
```js
var define = require('define-property');
var obj = {};
define(obj, 'foo', function(val) {
return val.toUpperCase();
});
console.log(obj);
//=> {}
console.log(obj.foo('bar'));
//=> 'BAR'
```
**get/set**
```js
define(obj, 'foo', {
get: function() {},
set: function() {}
});
```
## Related projects
* [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object)
* [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object)
* [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep)
* [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object)
## Running tests
Install dev dependencies:
```sh
$ npm i -d && npm test
```
## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new).
## Author
**Jon Schlinkert**
+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright © 2015 Jon Schlinkert
Released under the MIT license.
***
_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._
/*!
* define-property <https://github.com/jonschlinkert/define-property>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var isDescriptor = require('is-descriptor');
module.exports = function defineProperty(obj, prop, val) {
if (typeof obj !== 'object' && typeof obj !== 'function') {
throw new TypeError('expected an object or function.');
}
if (typeof prop !== 'string') {
throw new TypeError('expected `prop` to be a string.');
}
if (isDescriptor(val) && ('set' in val || 'get' in val)) {
return Object.defineProperty(obj, prop, val);
}
return Object.defineProperty(obj, prop, {
configurable: true,
enumerable: false,
writable: true,
value: val
});
};
{
"_from": "define-property@^0.2.5",
"_id": "define-property@0.2.5",
"_inBundle": false,
"_integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
"_location": "/class-utils/define-property",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "define-property@^0.2.5",
"name": "define-property",
"escapedName": "define-property",
"rawSpec": "^0.2.5",
"saveSpec": null,
"fetchSpec": "^0.2.5"
},
"_requiredBy": [
"/class-utils"
],
"_resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
"_shasum": "c35b1ef918ec3c990f9a5bc57be04aacec5c8116",
"_spec": "define-property@^0.2.5",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/class-utils",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/define-property/issues"
},
"bundleDependencies": false,
"dependencies": {
"is-descriptor": "^0.1.0"
},
"deprecated": false,
"description": "Define a non-enumerable property on an object.",
"devDependencies": {
"mocha": "*",
"should": "^7.0.4"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/define-property",
"keywords": [
"define",
"define-property",
"enumerable",
"key",
"non",
"non-enumerable",
"object",
"prop",
"property",
"value"
],
"license": "MIT",
"main": "index.js",
"name": "define-property",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/define-property.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"related": {
"list": [
"mixin-deep",
"mixin-object",
"delegate-object",
"forward-object"
]
}
},
"version": "0.2.5"
}
{
"_from": "class-utils@^0.3.5",
"_id": "class-utils@0.3.6",
"_inBundle": false,
"_integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==",
"_location": "/class-utils",
"_phantomChildren": {
"is-descriptor": "0.1.6"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "class-utils@^0.3.5",
"name": "class-utils",
"escapedName": "class-utils",
"rawSpec": "^0.3.5",
"saveSpec": null,
"fetchSpec": "^0.3.5"
},
"_requiredBy": [
"/base"
],
"_resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz",
"_shasum": "f93369ae8b9a7ce02fd41faad0ca83033190c463",
"_spec": "class-utils@^0.3.5",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/base",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/class-utils/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Brian Woodward",
"url": "https://twitter.com/doowb"
},
{
"name": "Jon Schlinkert",
"url": "http://twitter.com/jonschlinkert"
},
{
"url": "https://github.com/wtgtybhertgeghgtwtg"
}
],
"dependencies": {
"arr-union": "^3.1.0",
"define-property": "^0.2.5",
"isobject": "^3.0.0",
"static-extend": "^0.1.1"
},
"deprecated": false,
"description": "Utils for working with JavaScript classes and prototype methods.",
"devDependencies": {
"gulp": "^3.9.1",
"gulp-eslint": "^2.0.0",
"gulp-format-md": "^0.1.7",
"gulp-istanbul": "^0.10.3",
"gulp-mocha": "^2.2.0",
"mocha": "^2.4.5",
"should": "^8.2.2",
"through2": "^2.0.1"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/class-utils",
"keywords": [
"array",
"assign",
"class",
"copy",
"ctor",
"define",
"delegate",
"descriptor",
"extend",
"extends",
"inherit",
"inheritance",
"merge",
"method",
"object",
"prop",
"properties",
"property",
"prototype",
"util",
"utils"
],
"license": "MIT",
"main": "index.js",
"name": "class-utils",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/class-utils.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"run": true,
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"define-property",
"delegate-properties",
"is-descriptor"
]
},
"reflinks": [
"verb"
],
"lint": {
"reflinks": true
}
},
"version": "0.3.6"
}
{
"single": {
"topLeft": "┌",
"topRight": "┐",
"bottomRight": "┘",
"bottomLeft": "└",
"vertical": "│",
"horizontal": "─"
},
"double": {
"topLeft": "╔",
"topRight": "╗",
"bottomRight": "╝",
"bottomLeft": "╚",
"vertical": "║",
"horizontal": "═"
},
"round": {
"topLeft": "╭",
"topRight": "╮",
"bottomRight": "╯",
"bottomLeft": "╰",
"vertical": "│",
"horizontal": "─"
},
"single-double": {
"topLeft": "╓",
"topRight": "╖",
"bottomRight": "╜",
"bottomLeft": "╙",
"vertical": "║",
"horizontal": "─"
},
"double-single": {
"topLeft": "╒",
"topRight": "╕",
"bottomRight": "╛",
"bottomLeft": "╘",
"vertical": "│",
"horizontal": "═"
},
"classic": {
"topLeft": "+",
"topRight": "+",
"bottomRight": "+",
"bottomLeft": "+",
"vertical": "|",
"horizontal": "-"
}
}
'use strict';
module.exports = require('./boxes.json');
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
{
"_from": "cli-boxes@^1.0.0",
"_id": "cli-boxes@1.0.0",
"_inBundle": false,
"_integrity": "sha1-T6kXw+WclKAEzWH47lCdplFocUM=",
"_location": "/cli-boxes",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cli-boxes@^1.0.0",
"name": "cli-boxes",
"escapedName": "cli-boxes",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/boxen"
],
"_resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-1.0.0.tgz",
"_shasum": "4fa917c3e59c94a004cd61f8ee509da651687143",
"_spec": "cli-boxes@^1.0.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/boxen",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/cli-boxes/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Boxes for use in the terminal",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js",
"boxes.json"
],
"homepage": "https://github.com/sindresorhus/cli-boxes#readme",
"keywords": [
"cli",
"box",
"boxes",
"terminal",
"term",
"console",
"ascii",
"unicode",
"border",
"text",
"json"
],
"license": "MIT",
"name": "cli-boxes",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/cli-boxes.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.0.0"
}
# cli-boxes [![Build Status](https://travis-ci.org/sindresorhus/cli-boxes.svg?branch=master)](https://travis-ci.org/sindresorhus/cli-boxes)
> Boxes for use in the terminal
The list of boxes is just a [JSON file](boxes.json) and can be used wherever.
## Install
```
$ npm install --save cli-boxes
```
## Usage
```js
const cliBoxes = require('cli-boxes');
console.log(cliBoxes.single);
/*
{
"topLeft": "┌",
"topRight": "┐",
"bottomRight": "┘",
"bottomLeft": "└",
"vertical": "│",
"horizontal": "─"
}
*/
```
## API
### cliBoxes
#### `single`
```
┌────┐
│ │
└────┘
```
#### `double`
```
╔════╗
║ ║
╚════╝
```
#### `round`
```
╭────╮
│ │
╰────╯
```
#### `single-double`
```
╓────╖
║ ║
╙────╜
```
#### `double-single`
```
╒════╕
│ │
╘════╛
```
#### `classic`
```
+----+
| |
+----+
```
## Related
- [boxen](https://github.com/sindresorhus/boxen) - Create boxes in the terminal
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
The MIT License (MIT)
Copyright (c) 2015, 2017, 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.
# collection-visit [![NPM version](https://img.shields.io/npm/v/collection-visit.svg?style=flat)](https://www.npmjs.com/package/collection-visit) [![NPM monthly downloads](https://img.shields.io/npm/dm/collection-visit.svg?style=flat)](https://npmjs.org/package/collection-visit) [![NPM total downloads](https://img.shields.io/npm/dt/collection-visit.svg?style=flat)](https://npmjs.org/package/collection-visit) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/collection-visit.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/collection-visit)
> Visit a method over the items in an object, or map visit over the objects in an array.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save collection-visit
```
## Usage
```js
var visit = require('collection-visit');
var ctx = {
data: {},
set: function (key, value) {
if (typeof key === 'object') {
visit(ctx, 'set', key);
} else {
ctx.data[key] = value;
}
}
};
ctx.set('a', 'a');
ctx.set('b', 'b');
ctx.set('c', 'c');
ctx.set({d: {e: 'f'}});
console.log(ctx.data);
//=> {a: 'a', b: 'b', c: 'c', d: { e: 'f' }};
```
## About
### Related projects
* [base-methods](https://www.npmjs.com/package/base-methods): base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/jonschlinkert/base-methods) | [homepage](https://github.com/jonschlinkert/base-methods "base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.")
* [map-visit](https://www.npmjs.com/package/map-visit): Map `visit` over an array of objects. | [homepage](https://github.com/jonschlinkert/map-visit "Map `visit` over an array of objects.")
* [object-visit](https://www.npmjs.com/package/object-visit): Call a specified method on each value in the given object. | [homepage](https://github.com/jonschlinkert/object-visit "Call a specified method on each value in the given object.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 13 | [jonschlinkert](https://github.com/jonschlinkert) |
| 9 | [doowb](https://github.com/doowb) |
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 09, 2017._
\ No newline at end of file
/*!
* collection-visit <https://github.com/jonschlinkert/collection-visit>
*
* Copyright (c) 2015, 2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var visit = require('object-visit');
var mapVisit = require('map-visit');
module.exports = function(collection, method, val) {
var result;
if (typeof val === 'string' && (method in collection)) {
var args = [].slice.call(arguments, 2);
result = collection[method].apply(collection, args);
} else if (Array.isArray(val)) {
result = mapVisit.apply(null, arguments);
} else {
result = visit.apply(null, arguments);
}
if (typeof result !== 'undefined') {
return result;
}
return collection;
};
{
"_from": "collection-visit@^1.0.0",
"_id": "collection-visit@1.0.0",
"_inBundle": false,
"_integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=",
"_location": "/collection-visit",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "collection-visit@^1.0.0",
"name": "collection-visit",
"escapedName": "collection-visit",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/cache-base"
],
"_resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz",
"_shasum": "4bc0373c164bc3291b4d368c829cf1a80a59dca0",
"_spec": "collection-visit@^1.0.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/cache-base",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/collection-visit/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Brian Woodward",
"email": "brian.woodward@gmail.com",
"url": "https://twitter.com/doowb"
},
{
"name": "Jon Schlinkert",
"email": "jon.schlinkert@sellside.com",
"url": "http://twitter.com/jonschlinkert"
}
],
"dependencies": {
"map-visit": "^1.0.0",
"object-visit": "^1.0.0"
},
"deprecated": false,
"description": "Visit a method over the items in an object, or map visit over the objects in an array.",
"devDependencies": {
"clone-deep": "^0.2.4",
"gulp": "^3.9.1",
"gulp-eslint": "^3.0.1",
"gulp-format-md": "^0.1.12",
"gulp-istanbul": "^1.1.1",
"gulp-mocha": "^3.0.0",
"mocha": "^3.2.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/collection-visit",
"keywords": [
"array",
"arrays",
"collection",
"context",
"function",
"helper",
"invoke",
"key",
"map",
"method",
"object",
"objects",
"value",
"visit",
"visitor"
],
"license": "MIT",
"main": "index.js",
"name": "collection-visit",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/collection-visit.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"related": {
"list": [
"base-methods",
"map-visit",
"object-visit"
]
},
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
}
},
"version": "1.0.0"
}
# 1.0.0 - 2016-01-07
- Removed: unused speed test
- Added: Automatic routing between previously unsupported conversions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `convert()` class
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: all functions to lookup dictionary
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: `ansi` to `ansi256`
([#27](https://github.com/Qix-/color-convert/pull/27))
- Fixed: argument grouping for functions requiring only one argument
([#27](https://github.com/Qix-/color-convert/pull/27))
# 0.6.0 - 2015-07-23
- Added: methods to handle
[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
- rgb2ansi16
- rgb2ansi
- hsl2ansi16
- hsl2ansi
- hsv2ansi16
- hsv2ansi
- hwb2ansi16
- hwb2ansi
- cmyk2ansi16
- cmyk2ansi
- keyword2ansi16
- keyword2ansi
- ansi162rgb
- ansi162hsl
- ansi162hsv
- ansi162hwb
- ansi162cmyk
- ansi162keyword
- ansi2rgb
- ansi2hsl
- ansi2hsv
- ansi2hwb
- ansi2cmyk
- ansi2keyword
([#18](https://github.com/harthur/color-convert/pull/18))
# 0.5.3 - 2015-06-02
- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
([#15](https://github.com/harthur/color-convert/issues/15))
---
Check out commit logs for older releases
Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>
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.
# color-convert
[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
var convert = require('color-convert');
convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
convert.keyword.rgb('blue'); // [0, 0, 255]
var rgbChannels = convert.rgb.channels; // 3
var cmykChannels = convert.cmyk.channels; // 4
var ansiChannels = convert.ansi16.channels; // 1
```
# Install
```console
$ npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
```js
var convert = require('color-convert');
// Hex to LAB
convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
// RGB to CMYK
convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```
### Arrays
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
var convert = require('color-convert');
convert.rgb.hex(123, 45, 67); // '7B2D43'
convert.rgb.hex([123, 45, 67]); // '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
# License
Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
/* MIT license */
var cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
var reverseKeywords = {};
for (var key in cssKeywords) {
if (cssKeywords.hasOwnProperty(key)) {
reverseKeywords[cssKeywords[key]] = key;
}
}
var convert = module.exports = {
rgb: {channels: 3, labels: 'rgb'},
hsl: {channels: 3, labels: 'hsl'},
hsv: {channels: 3, labels: 'hsv'},
hwb: {channels: 3, labels: 'hwb'},
cmyk: {channels: 4, labels: 'cmyk'},
xyz: {channels: 3, labels: 'xyz'},
lab: {channels: 3, labels: 'lab'},
lch: {channels: 3, labels: 'lch'},
hex: {channels: 1, labels: ['hex']},
keyword: {channels: 1, labels: ['keyword']},
ansi16: {channels: 1, labels: ['ansi16']},
ansi256: {channels: 1, labels: ['ansi256']},
hcg: {channels: 3, labels: ['h', 'c', 'g']},
apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
gray: {channels: 1, labels: ['gray']}
};
// hide .channels and .labels properties
for (var model in convert) {
if (convert.hasOwnProperty(model)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
var channels = convert[model].channels;
var labels = convert[model].labels;
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', {value: channels});
Object.defineProperty(convert[model], 'labels', {value: labels});
}
}
convert.rgb.hsl = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var l;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
var rdif;
var gdif;
var bdif;
var h;
var s;
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var v = Math.max(r, g, b);
var diff = v - Math.min(r, g, b);
var diffc = function (c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var h = convert.rgb.hsl(rgb)[0];
var w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var c;
var m;
var y;
var k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
/**
* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
* */
function comparativeDistance(x, y) {
return (
Math.pow(x[0] - y[0], 2) +
Math.pow(x[1] - y[1], 2) +
Math.pow(x[2] - y[2], 2)
);
}
convert.rgb.keyword = function (rgb) {
var reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
var currentClosestDistance = Infinity;
var currentClosestKeyword;
for (var keyword in cssKeywords) {
if (cssKeywords.hasOwnProperty(keyword)) {
var value = cssKeywords[keyword];
// Compute comparative distance
var distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
var xyz = convert.rgb.xyz(rgb);
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
var h = hsl[0] / 360;
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var t1;
var t2;
var t3;
var rgb;
var val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
var h = hsl[0];
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var smin = s;
var lmin = Math.max(l, 0.01);
var sv;
var v;
l *= 2;
s *= (l <= 1) ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
v = (l + s) / 2;
sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
var h = hsv[0] / 60;
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var hi = Math.floor(h) % 6;
var f = h - Math.floor(h);
var p = 255 * v * (1 - s);
var q = 255 * v * (1 - (s * f));
var t = 255 * v * (1 - (s * (1 - f)));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
var h = hsv[0];
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var vmin = Math.max(v, 0.01);
var lmin;
var sl;
var l;
l = (2 - s) * v;
lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= (lmin <= 1) ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
var h = hwb[0] / 360;
var wh = hwb[1] / 100;
var bl = hwb[2] / 100;
var ratio = wh + bl;
var i;
var v;
var f;
var n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
var r;
var g;
var b;
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
var c = cmyk[0] / 100;
var m = cmyk[1] / 100;
var y = cmyk[2] / 100;
var k = cmyk[3] / 100;
var r;
var g;
var b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
var x = xyz[0] / 100;
var y = xyz[1] / 100;
var z = xyz[2] / 100;
var r;
var g;
var b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// assume sRGB
r = r > 0.0031308
? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
: r * 12.92;
g = g > 0.0031308
? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
: g * 12.92;
b = b > 0.0031308
? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
: b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var x;
var y;
var z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
var y2 = Math.pow(y, 3);
var x2 = Math.pow(x, 3);
var z2 = Math.pow(z, 3);
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var hr;
var h;
var c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
var l = lch[0];
var c = lch[1];
var h = lch[2];
var a;
var b;
var hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
var ansi = 30
+ ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
// we use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
var ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
var color = args % 10;
// handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
var mult = (~~(args > 50) + 1) * 0.5;
var r = ((color & 1) * mult) * 255;
var g = (((color >> 1) & 1) * mult) * 255;
var b = (((color >> 2) & 1) * mult) * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// handle greyscale
if (args >= 232) {
var c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
var rem;
var r = Math.floor(args / 36) / 5 * 255;
var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
var b = (rem % 6) / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
var integer = ((Math.round(args[0]) & 0xFF) << 16)
+ ((Math.round(args[1]) & 0xFF) << 8)
+ (Math.round(args[2]) & 0xFF);
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
var colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(function (char) {
return char + char;
}).join('');
}
var integer = parseInt(colorString, 16);
var r = (integer >> 16) & 0xFF;
var g = (integer >> 8) & 0xFF;
var b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var max = Math.max(Math.max(r, g), b);
var min = Math.min(Math.min(r, g), b);
var chroma = (max - min);
var grayscale;
var hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else
if (max === r) {
hue = ((g - b) / chroma) % 6;
} else
if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma + 4;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var c = 1;
var f = 0;
if (l < 0.5) {
c = 2.0 * s * l;
} else {
c = 2.0 * s * (1.0 - l);
}
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var c = s * v;
var f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
var h = hcg[0] / 360;
var c = hcg[1] / 100;
var g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
var pure = [0, 0, 0];
var hi = (h % 1) * 6;
var v = hi % 1;
var w = 1 - v;
var mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1; pure[1] = v; pure[2] = 0; break;
case 1:
pure[0] = w; pure[1] = 1; pure[2] = 0; break;
case 2:
pure[0] = 0; pure[1] = 1; pure[2] = v; break;
case 3:
pure[0] = 0; pure[1] = w; pure[2] = 1; break;
case 4:
pure[0] = v; pure[1] = 0; pure[2] = 1; break;
default:
pure[0] = 1; pure[1] = 0; pure[2] = w;
}
mg = (1.0 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
var f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var l = g * (1.0 - c) + 0.5 * c;
var s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else
if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
var w = hwb[1] / 100;
var b = hwb[2] / 100;
var v = 1 - b;
var c = v - w;
var g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
};
convert.rgb.apple = function (rgb) {
return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = convert.gray.hsv = function (args) {
return [0, 0, args[0]];
};
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
var val = Math.round(gray[0] / 100 * 255) & 0xFF;
var integer = (val << 16) + (val << 8) + val;
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
var conversions = require('./conversions');
var route = require('./route');
var convert = {};
var models = Object.keys(conversions);
function wrapRaw(fn) {
var wrappedFn = function (args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
return fn(args);
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
var wrappedFn = function (args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
var result = fn(args);
// we're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if (typeof result === 'object') {
for (var len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(function (fromModel) {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
var routes = route(fromModel);
var routeModels = Object.keys(routes);
routeModels.forEach(function (toModel) {
var fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment