ship-components-utility
v2.1.1
Published
Javascript set of utilities
Downloads
27
Readme
ship-components-utility
JavaScript set of utilities. Exports a commonjs module that can be used with webpack. Source is in ES6 and an ES5 version is available using Babel.
Docs & Help
Here is the list of utilities you can use.
- Collections
- KeyEvents
- NativeFileUploadDialog
- ParseUrl
- Sort
- [Strings]( isEqual(Object1, Object2);#strings) isEqual(Object1, Object2);
- Utils
Usage
ES6 (Recommended)
The component is written using ES6 therefore Babel is recommended to use it. The below example is based on using webpack and babel-loader.
<!-- import everything -->
import * as Utility from 'ship-components-utility';
<!-- import specific library -->
import {Strings, Sort, Utils, Collections} from 'ship-components-utility';
<!-- import specific method from a library -->
import {capitalize, titleCase, toUnderscoreCase, generateRandomString} from 'ship-components-utility'.Strings;
Docs
Collections
const {Collections} = require('ship-components-utility');
keys
/**
* Returns the Objects keys
* @param {Object} obj
* @return {Array} result
*/
const {keys} = require('ship-components-utility').Collections;
let obj = { name: 'test' }
expect(keys(obj)[0]).toEqual('name');
toArray
/**
* Converts an Object to an Array
* @param {Object} val
* @return {Array} result
*/
each
/**
* Iterate through each Object keys
* And binds a callback to each keys
* @param {Object} val
* @param {func} fn
*/
const {each} = require('ship-components-utility').Collections;
let obj = { name: 'test' };
let fn = function() {}
each(obj, fn);
size
/**
* Returns the size of an object or array
* @param {Object || Array} val
* @return {Number}
*/
searchFn
/**
* Returns the function if available inside an object
* @param {Object || Array || Func} val
* @return {mixed}
*/
any
/**
* Similar to Javscript .some() function
* @param {Object || Array} values
* @param {Func} compare
* @return {Bool}
*/
find
/**
* Similar to Underscore _.find() function
* @param {Array} arr
* @param {Func} compare
* @param {Mixed} ctx (default value) optional
* @return {Mixed}
*/
findIndex
/**
* Returns the index of an item in array if exisits, -1 otherwise
* @param {Array} arr
* @param {Func} compare
* @param {Mixed} ctx (default value) optional
* @return {Number} -1 if can't find it
*/
getIn
/**
* Get a nested value of an object or return
* @param {Array<String>} path
* @param {Object} obj
* @param {Mixed} defaultValue
* @return {Mixed}
*/
const {getIn} = require('ship-components-utility').Collections;
const testMap = {
obj1: {
name: 'test1',
obj2: {
name: 'test2',
}
}
};
getIn(['obj1', 'obj2', 'name'], testMap); // test2
hasIn
/**
* Returns true if an object has the matched value,
* otherwise false
* @param {Object} obj
* @param {Array<String>} path
* @return {Mixed}
*/
const {hasIn} = require('ship-components-utility').Collections;
const testMap = {
obj1: {
name: 'test1',
obj2: {
name: 'test2',
}
}
};
hasIn(['obj1', 'obj2', 'name'], testMap); // true
isEqual
/**
* First compres the size of two objects and then does a shallow
* comparison of the two objects values
* @param {Mixed} one
* @param {Mixed} two
* @return {Boolean}
*/
isEqual(Object1, Object2);
KeyEvents
/**
* List of key events
* @param {String} prop.Collections
* @return {Number}
*/
const {KeyEvents} = require('ship-components-utility');
KeyEvents('DOM_VK_PAGE_DOWN'); // 34
KeyEvents('DOM_VK_ESCAPE'); // 27
NativeFileUploadDialog
/**
* File upload dialog
* @constructor param {String} type
*/
const {NativeFileUploadDialog} = require('ship-components-utility');
new NativeFileUploadDialog('image/*')
.open
.thenWith(callback_function)
ParseUrl
/**
* Breaks a URL into parts
* @param {String} url
*/
const {ParseUrl} = require('ship-components-utility');
let url = 'http://www.sony.com/homepage?param1=something¶m2=somethingelse';
ParseUrl(url);
<!--
return value
{
protocol: 'http'
hostname: 'www.sony.com'
query: 'param1=something¶m2=somethingelse'
path: '/homepage'
}
-->
Sort
const {Sort} = require('ship-components-utility');
compareDates
/**
* Compare two dates
*
* @param {Date} a
* @param {Date} b
* @return {Number}
*/
const {compareDates} = require('ship-components-utility').Sort;
sortBy
/**
* Create a sorting function to sort an array of objects by prop. We accept any
* number of arguments to sort by
*
* @param {String...} prop
* @return {Function}
*/
const {sortBy} = require('ship-components-utility').Sort;
sortByDates
/**
* Create a sorting function to sort an array of objects by prop. We accept any
* number of arguments to sort by
*
* @param {String...} prop
* @return {Function}
*/
const {sortByDates} = require('ship-components-utility').Sort;
Strings
const {Strings} = require('ship-components-utility');
hash
/**
* Convert a string to a unique hash we can use as an key
* http://stackoverflow.com/a/7616484
* @param {String} str
* @return {Number}
*/
const {hash} = require('ship-components-utility').Strings;
slugify
/**
* Convert a string into something that is url and css friendly
* @param {String} str
* @return {String}
*/
const {slugify} = require('ship-components-utility').Strings;
let str1 = 'THis Is A! sample--string';
let str2 = 'this-is-a---sample--string';
let result = slugify(str1);
expect(result).not.toEqual(str1);
expect(result).toEqual(str2);
capitalize
/**
* Capitalize string
* Convert to TitleCase if more than one word
* @param {String} str
* @return {String}
*/
const {capitalize} = require('ship-components-utility').Strings;
let str1 = 'test test';
let str2 = 'Test Test';
let result = capitalize(str1);
expect(result).not.toEqual(str1);
expect(result).toEqual(str2);
titleCase
/**
* Title case string
* @param {String} str
* @return {String}
*/
const {titleCase} = require('ship-components-utility').Strings;
camelCase
/**
* Convert to camelCase string
* @param {String} str
* @return {String}
*/
const {camelCase} = require('ship-components-utility').Strings;
toUnderscoreCase
/**
* Convert camel case to underscore case
* @param {String} str
* @return {String}
*/
const {toUnderscoreCase} = require('ship-components-utility').Strings;
generateRandomString
/**
* Generates a short random String
* @param {Number} len
* @return {String}
*/
const {generateRandomString} = require('ship-components-utility').Strings;
stringShortener
/**
* Shorten string
* @param {String} str
* @param {Number} charCount [default==100]
* @return {String}
*/
const {stringShortener} = require('ship-components-utility').Strings;
stringIsValid
/**
* Validate strings (name, username or email)
*
* @param {String} prop [default=email]
* @param {String} str
* @return {Bool}
*/
const {stringIsValid} = require('ship-components-utility').Strings;
convertHTMLToString
/**
* Removes HTML tags from string
*
* @param {String} str
* @return {String}
*/
const {convertHTMLToString} = require('ship-components-utility').Strings;
let str = '<p>this is a text for<span>testing</span></p>';
let result = convertHTMLToString(str);
expect(result).not.toEqual(str);
expect(result).toEqual('this is a text fortesting');
Utils
const {Utils} = require('ship-components-utility');
objectSize
/**
* Returns the size of an Object
* @param {Object} obj
* @return {Number} size
*/
const {objectSize} = require('ship-components-utility').Utils;
isObject
/**
* Checks if value is the language type of Object
* will skip values === null
* @param {Mixed} prop
* @return {Bool}
*/
const {isObject} = require('ship-components-utility').Utils;
isFunction
/**
* Checks if value is classified as a Function object
* @param {Mixed} prop
* @return {Bool}
*/
const {isFunction} = require('ship-components-utility').Utils;
isString
/**
* Checks if value is classified as a String primitive or object
* @param {Mixed} prop
* @return {Bool}
*/
const {isString} = require('ship-components-utility').Utils;
isArray
/**
* Checks if value is classified as an Array object
* @param {Mixed} prop
* @return {Bool}
*/
const {isArray} = require('ship-components-utility').Utils;
isEqualArray
/**
* Shallow comparison between 2 arrays
* or envoke the callback function
* @param {Array} arr1
* @param {Array} arr2
* @param {Function} callback {optional}
* @return {Bool}
*/
const {isEqualArray} = require('ship-components-utility').Utils;
isUndefined
/**
* Checks if value is undefined
* @param {Mixed} prop
* @return {Bool}
*/
const {isUndefined} = require('ship-components-utility').Utils;
bind
/**
* Bind to itself
* @param {args...}
* @return {Undefined}
* @example bind(this, 'handleClick', 'handleSubmit');
*/
const {bind} = require('ship-components-utility').Utils;
bindAll
/**
* Binds methods of an object to the object itself,
* overwriting the existing method.
* Method names may be specified as individual arguments
* or as arrays of method names
* @param {Object} obj
* @return {Object} result
*/
const {bindAll} = require('ship-components-utility').Utils;
unique
/**
* Creates a duplicate-free version of an array
* @param {Array} val
* @return {Immutable.Set}
*/
const {unique} = require('ship-components-utility').Utils;
mergeDeep
/**
* This method is like _.assign except that it
* recursively merges own and inherited enumerable
* string keyed properties of source objects into the
* destination object
* @param {Object} target
* @param {Object} source
* @return {Object} target
*/
const {mergeDeep} = require('ship-components-utility').Utils;
deepCopy
/**
* Recursive object copy
*
* @param {Array<Objects> || Objects} obj
* @return {Array<Objects> || Objects}
*/
const {deepCopy} = require('ship-components-utility').Utils;
pluck
/**
* Extract a subset of keys off of an object
*
* @param {Object} src
* @return {Array<String>} fields
* @return {Object}
*/
const {pluck} = require('ship-components-utility').Utils;
isIEBrowser
/**
* Detect IE browser
* @param {String} prop
* @return {Bool}
*/
const {isIEBrowser} = require('ship-components-utility').Utils;
detectIEVersion
/**
* Detect IE browser version
* @return {String}
*/
const {detectIEVersion} = require('ship-components-utility').Utils;
Development
More examples can be found in the examples/
folder. A development server can be run with:
$ git clone https://github.com/ship-components/ship-components-utility.git
$ npm install
$ npm test
Webpack Configuration
This module is designed to be used with webpack but requires a few loaders if you are pulling the source into another project.
$ npm install webpack babel-loader --save-dev
Below are is a sample of how to setup the loaders:
/**
* Relevant Webpack Configuration
*/
{
[...]
module: {
loaders: [
// Setup support for ES6
{
test: /\.(js|es6)$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
[...]
}
Tests
npm install
npm test
History
- 2.1.1 - Fixes unambiguous imports and exports (ES vs node).
- 2.1.0 - Updates Webpack, eslint, jest and dependencies, grunt, husky, eslint-plugin-react and coverals
- 2.0.0 - Updates Webpack to 4.21.0, Babel to 7 (monorepo). Fixes npm warnings & security vulnerabilities.
- 2.0.0-beta.1 - Updates Webpack to 4.3.0 as well as eslint-loader, grunt-coveralls and lint-stages to latest.
- 1.5.2 - Bugfix for getScrollTop and testing improvements
- 1.5.1 - Adds functions throttle and getScrollTop to Utils.
- 1.5.0 - Adds isEqualArray function to Utils to shallow compare 2 arrays.
- 1.4.0 - updates dev dependencies to latest version (webpack, babel, eslint, jest, coveralls, eslint-config-ship-components).
- 1.3.2 - Removes the unnecessary babel plugins.
- 1.3.1 - Updates jest and babel-eslint to latest version.
- 1.3.0 - Updates the babel presets from latest to env - latest has been deprecated.
- 1.2.2 - Adds a pre-commit hook that will run jest test and eslint before for the changed files. NOTE: please make the precommit hook to be executable for the first time (chmod +x ./.git/hooks/pre-commit)
- 1.2.1 - Fixed an issue in getIn where it wasn't returning the defaultValue as expected
- 1.2.0 - Added pluck function to Util and added watch:test command
- 1.1.0 - Adds a deepCopy function to utility library to copy (recursively) objects, array of objects or date objects.
- 1.0.0 - First major version, fixed the export module path
- 0.1.0 - Initial
License
The MIT License (MIT)
Copyright (c) 2017
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.