- Util
Extra useful Lodash mixins
- _
- .parameters ⇒
Mixed
- .arguments ⇒
number
- .arguments ⇒
number
- .utf8Encode(str) ⇒
string
- .utf8Decode(str) ⇒
string
- .md5(str) ⇒
string
- .stripCommonRoot(pathArray) ⇒
array
- .sumPaths(pathArray) ⇒
Object
|string
|array
- .valTypes(collection, [filter]) ⇒
array
- .sha1(str) ⇒
string
- .makeHash(str, salt) ⇒
string
- .randStr(length) ⇒
string
- .replaceAt(str, indexndex, character) ⇒
string
- .getType(item) ⇒
string
- .multiReplace(str, replacements, modifiers) ⇒
string
- .swap(obj) ⇒
object
- [.uniqObjs(arr, arr) ⇒
array
- .isNumeric(num) ⇒
boolean
- .isEmail(email) ⇒
boolean
- .sortMatch(object, source, [customizer]) ⇒
boolean
- .bool(value, trues, [lower]) ⇒
- .endWith(str, endChar) ⇒
string
- .dontEndWith(str, endChar) ⇒
string
- .startWith(str, startChar) ⇒
string
- .dontStartWith(str, startChar) ⇒
string
- .nl2br(str, [br]) ⇒
string
- .br2nl(str, [nl]) ⇒
string
- .censor(word, [masker], [maskType]) ⇒
string
- .passwordHash(password) ⇒
string
- .passwordVerify(password, passwdHash) ⇒
boolean
- .sortObj(obj, comparator) ⇒
object
- .isUniq(collection, [element]) ⇒
boolean
- .removeObj(obj, del) ⇒
object
- .mysqlEscape(content) ⇒
string
- .isSnake(str) ⇒
boolean
- .isCamel(str) ⇒
boolean
- .isKebab(str) ⇒
boolean
- .isStart(str) ⇒
boolean
- .isLower(str) ⇒
boolean
- .isUpper(str) ⇒
boolean
- .getCase(str) ⇒
string
|undefined
- .isCase(theCase, str) ⇒
boolean
- .includesAll(collection, values, fromIndex) ⇒
boolean
- .levenshtein(strA, strB) ⇒
number
- .strDist(strA, strB) ⇒
number
- .plural(str) ⇒
string
- .mergeObjs([...sources]) ⇒
object
- .setException(item, [type]) ⇒
Mixed
- .pullSample(arr) ⇒
Mixed
- .pullSampleSize(arr, size) ⇒
array
- .validPattern(pattern, flags, reason) ⇒
boolean
|string
- .typeof(value, inspect, returnTypes, flaggedVals) ⇒
string
- .parameters ⇒
Alternate through the parameters provided, returning the next one in line every time.
Instructions: - Calling alternator() with the SAME parameters will return the next param each time - Calling alternator() with NEW parameters will re-initialize the rotation, and return the first new parameter listed - Calling alternator() with NO parameters will reset the rotation to null, and return nothing
Kind: static property of _
Returns: Mixed
- Whatever array element is next in line, or nothing when resetting
Todo
- Create unit tests
Example
for(i = 0; i< 6; i++)
_.alternator('a','b','c')
// returns (incrementally) : a, b, c, a, b, c
Return the maximum value of all arguments passed. This is the same thing as _.max, only instead of an array, it takes all the arguments
Kind: static property of _
Returns: number
- Maximum value, retrieved by _.max()
Todo
- Create unit tests
Example
_.maxOf( 1, 20, 'a', ['test'], 1000 )
// => 1000
Return the minimum value of all arguments passed. This is the same thing as _.min, only instead of an array, it takes all the arguments
Kind: static property of _
Returns: number
- Minimum value, retrieved by _.min()
Todo
- Create unit tests
Example
_.minOf( 1, 20, 'a', ['test'], 1000 )
// => 1
Encodes an ISO-8859-1 string to UTF-8, this is meant to provide the same functionality as the PHP utf8_encode function.
Kind: static method of _
Returns: string
- UTF-8 encoded version of the str param value
Param | Type | Description |
---|---|---|
str | string |
Standard ISO-8859-1 encoded string |
Example
_.utf8Encode('Hello World')
// => Hello World
Decodes a UTF-8 encoded string to the standard ISO-8859-1, this is meant to provide the same functionality as the PHP utf8_decode function.
Kind: static method of _
Returns: string
- ISO-8859-1 decoded string
Param | Type | Description |
---|---|---|
str | string |
UTF-8 encoded string |
Example
_.utf8Decode('Hello World')
// => Hello World
Retrieve the md5sum value for a specific string.
This source was taken from the PHP.js project, I take no credit for this code
Kind: static method of _
Returns: string
- 32 character MD5 sum
See: http://phpjs.org/functions/md5/
Author: Not me (Justin Hyland)
Todo
- Create unit tests
Param | Type | Description |
---|---|---|
str | string |
String to hash |
Example
md5('Hello World') === 'b10a8db164e0754105b7a99be72e3fe5'
Iterate through an array of absolute file paths, removing the common paths from each element. This is useful for when you don't need to have the entire absolute path in the name.
Kind: static method of _
Returns: array
- Modified version of the provided array
Param | Type | Description |
---|---|---|
pathArray | array |
Array of paths.. |
Example
Gizmo.stripCommonRoot([
'/home/jdoe/app/lib/helpers/mongoose-helper.js',
'/home/jdoe/app/dev/file-foo.js',
'/home/jdoe/app/dev/some-file.js'
]).join(', ')
// => /lib/helpers/mongoose-helper.js, /dev/file-foo.js, /dev/some-file.js
Iterate through an array of absolute file paths, removing the common paths from each absolute path. The shortened filenames are returned in an array, while the common path
Kind: static method of _
Returns: Object
- pathObj Object containing the common absolute path, and an array of files (with
paths relative to the common absolute path)string
- pathObj.path The absolute path up to the last common folder that all files sharearray
- pathObj.files Array of filenames, paths starting where {pathObj.path} left off
Param | Type | Description |
---|---|---|
pathArray | array |
Array of paths.. |
Example
_.sumPaths.summarizePaths([
'/home/jdoe/app/lib/helpers/mongoose-helper.js',
'/home/jdoe/app/dev/file-foo.js',
'/home/jdoe/app/dev/some-file.js'
])
// => { path: '/home/jdoe/app',
files: [
'/lib/helpers/mongoose-helper.js', '/dev/file-foo.js', '/dev/some-file.js'
]
}
Retrieve the types of values in an array or an object.
Kind: static method of _
Returns: array
- Array of types of values in the collection
Param | Type | Description |
---|---|---|
collection | Object | array |
Array or object (collection of data). |
[filter] | function |
Filter the collection using a simple function |
Example
// Example showing how duplicate value types only display the value type once
_.valTypes([
1, 'Str', false, [], null, new Array(), undefined, {},
new Date(), function(){}, (s => `This is a ${s}`)('str')
]).join(', ').join(', ')
// => number, string, boolean, array, null, undefined, object, date, function
Example
// Using Gizmo.valueTypes to verify all parameters are string types
function onlyAcceptsStringParams( foo, bar, baz, bang ){
var invalidParamTypes = Gizmo.valTypes( arguments, f => ! _.isString(f) )
if( invalidParamTypes.length > 0 )
throw new Error( 'Expected ll parameters to be strings - received invalid type(s): ' + invalidParamTypes.join(', ') )
}
Calculate the sha1 hash of a specific string. This is the equivalent of PHP's sha1() function.
Kind: static method of _
Returns: string
- SHA1 hash
Param | Type | Description |
---|---|---|
str | string |
String to calculate hash for |
Example
_.sha1('test')
// => a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
Generate a hash of a given string, using the provided salt
Kind: static method of _
Returns: string
- base64 encoded hash
Param | Type | Description |
---|---|---|
str | string |
String to hash |
salt | string |
Salt to use for hash |
Example
_.makeHash('superSecretPassword','secret-salt')
// => ebA3UZET3LDQWzl <cut> TUnV5oRxAvOLsA==
Return a randomly generated string - at a specific length
Kind: static method of _
Todo
- Add the ability to specify the 'possible' string characters
Param | Type | Description |
---|---|---|
length | number |
Length of the desored string (Default: 20) |
Example
_.randStr( 15 )
// => gyC8Q9MABoEjGK6
Substitute specific characters within a string with a specified replacement. Replacement positions are specified by either a single (numeric) value, or an array of numeric values
Kind: static method of _
Returns: string
- Parsed/modified version of the provided string
Todo
- Allow the character parameter to be an array, and use the alternator method to iterate through them while substituting the replacements
- Allow the index to be a range
Param | Type | Description |
---|---|---|
str | string |
String to process |
indexndex | number | array |
Location(s) to be substituted |
character | string |
Character to substitute replacements with |
Example
_.replaceAt( 'baz', 2, 'r')
// => bar
_.replaceAt( 'bad-word', [1,2,5,6], '*')
// => b**-w**d
_.replaceAt( 'Hello World', [6,7,8,9,10] )
// => Hello ?????
Return items true type by grabbing the 2nd string content from Object.prototype.toString.call, as opposed to the less-specific 'typeof'
Kind: static method of _
Returns: string
- Type of variable
Param | Type | Description |
---|---|---|
item | * |
Item to retrieve type for |
Example
_.type([])
// => array
_.type({})
// => object
_.type(() => {})
// => function
This performs a series of replacements in a string, using the items within an object/array. Just a quicker/easier way than chaining .replace() over and over again. The replacements can be an array of arrays, an array of objects, or an object
Kind: static method of _
Returns: string
- Parsed and modified version of the provided string
Param | Type | Description |
---|---|---|
str | string |
String to be parsed/returned |
replacements | object | array |
Replacements, with original string as the key, and replacement as the value |
modifiers | string |
Regex modifiers to use for search (EG: i for case-insensitivity) 'g' (global) is included by default |
Example
_.multiReplace( 'test', { t: 'T'} )
// => TesT
_.multiReplace( 'foo', { FOO: 'bar'}, 'i' )
// => bar
_.multiReplace( 'Windows XP', [{ windows: 'Linux'}, {xp: 'RHEL'}], 'i' )
// => Linux RHEL
Swap the keys and values of a simple plain object
Kind: static method of _
Returns: object
- Returns a version of the original object with the keys and values switched (wherever possible)
Param | Type | Description |
---|---|---|
obj | object |
Object to swap values for |
Example
_.swap({a:'b', c:'d'})
// => {b:'a', d:'c'}
Return a new array containing only the unique objects inside the provided array. Unlike _.uniq, this will check every key/value in the array
Kind: static method of _
Param | Type | Description |
---|---|---|
arr | array |
Array of structurally identical objects |
arr[ | object |
All values in the provided array need to be objects |
Example
// Remove any duplicate objects
const objs = [ { x: 1, y: 2 }, { a: 1, b: 2 }, { x: 1, y: 2 }]
console.log( _( objs ).uniqObjs().value() )
console.log( _.uniqObjs( objs ) )
// => [ { x: 1, y: 2 }, { a: 1, b: 2 } ]
Check if the provided number is a float or integer value. This just tacks a 2nd check onto lodashes isNumber, which uses a lenient comparative operator to check if the value of Number is the same as the provided number
Kind: static method of _
Param | Type | Description |
---|---|---|
num | string | integer | number |
Number to check |
Example
_.isNumber( 123 )
_.isNumber( '123' )
_.isNumber( 1.2 )
_.isNumber( '1.2' )
// => true
_.isNumber( 'foo' )
_.isNumber( [] )
_.isNumber( {} )
// => false
Validate a string against an RFC822 compliant pattern
Kind: static method of _
Param | Type | Description |
---|---|---|
string |
Email address to validate against pattern |
Example
_.isEmail( 'j@linux.com' )
// => true
_.isEmail( 'j@linux.c' )
_.isEmail( 'jinux.com' )
_.isEmail( null )
// => false
Check if two values match each other. Basically sorts the object and source, then passes it off to _.isMatch, (Since objects/arrays with same values in different orders would be considered discrepancies
Kind: static method of _
Param | Type | Description |
---|---|---|
object | * |
Item A to match to B |
source | * |
Item B to match to A |
[customizer] | function |
Function to cuztomize the object and src (Just handed of to _.isMatch) |
Example
_.sortMatch( [1,2,3], [3,2,1] )
// => true
_.sortMatch( [1,2,'3'], [3,2,1] )
// => false
Just a boolean comparison tool, Allows you to specify other true-type variables, as well as convert the value to lower case (Since the string representations of the boolean values are lower). Also compares integer values
Kind: static method of _
Returns: Boolean casted version of the provided value
Param | Type | Default | Description |
---|---|---|---|
value | string | boolean | integer |
Value to compare | |
trues | array | string |
Any other custom 'true' type variables, an attempt is made to convert any value to an array | |
[lower] | boolean |
false |
Process the values after toLowerCase() is called |
Example
_.bool( true ) === true
_.bool( 'true' ) === true
_.bool( 1 ) === true
_.bool( 'foo', [ 'foo', 'bar' ] ) === true
_.bool( '1' ) === true
_.bool( 'false' ) === false
_.bool( false ) === false
_.bool( 0 ) === false
_.bool( '0' ) === false
_.bool( 'foo', [ 'bar', 'baz' ] ) === false
Ensure a specific string ends with a certain character
Kind: static method of _
Returns: string
- The string returned will be either the exact same string provided, or ${str + endChar} if
the original string doesn't end with the endChar character
Param | Type | Description |
---|---|---|
str | string |
String to parse and modify (if needed) |
endChar | string |
String to check for on the ending, and possibly append |
Example
_.endWith('/User/john.doe/Documents', '/')
// => /User/john.doe/Documents/
_.endWith('Something else.', '.')
// => Something else.
Ensure a specific string DOESN'T end with a certain character
Kind: static method of _
Returns: string
- The string returned will be either the exact same string provided, or a version of the
original string with the value of endChar removed from the end
Todo
- Should be able to replace an ending str like // with /
Param | Type | Description |
---|---|---|
str | string |
String to parse and modify (if needed) |
endChar | string |
String to check for on the ending, and possibly remove |
Example
_.dontEndWith('/v1/resource/name/', '/')
// => /v1/resource/name
Ensure a specific string starts with a certain character
Kind: static method of _
Returns: string
- The string returned will be either the exact same string provided, or ${startChar + str} if
the original string doesn't begin with the startChar character
Param | Type | Description |
---|---|---|
str | string |
String to parse and modify (if needed) |
startChar | string |
String to check for on the beginning, and possibly append |
Example
_.startWith('Documents/', '~/')
// => ~/Documents/
_.startWith('Something else.', '.')
// => Something else.
_( 'Using startsWith and endsWith together' )
.startWith('(')
.endWith(')')
.value()
// => (Using startsWith and endsWith together)
Ensure a specific string DOESN'T start with a certain character
Kind: static method of _
Returns: string
- The string returned will be either the exact same string provided, or a version of the
original string with the value of startChar removed from the beginning
Todo
- Should be able to replace an starting str like // with /
Param | Type | Description |
---|---|---|
str | string |
String to parse and modify (if needed) |
startChar | string |
String to check for on the beginning, and possibly remove |
Example
_.dontStartWith('.unhide-me', '.')
// => unhide-me
Convert any new-line characters to HTML Line breaks, which can optionally be specified,
but defaults to just
. The replaced characters consists of \r\n, \n\r, \n and \r.
Kind: static method of _
Returns: string
- Modified version of ${str}, with all new-line characters replaced with an HTML line break
Todo
- Another parameter to optionally trim the string before line breaks to get rid of first/last
- Another parameter to keep the \n on the end of the newly added
tag
Param | Type | Default | Description |
---|---|---|---|
str | string |
String to process and replace any new lines for | |
[br] | string |
"'</br>'" |
HTML Break ( by default) |
Example
_.nl2br("One\r\nTwo\n\rThree\nFour\rFive")
// => One</br>Two</br>Three</br>Four</br>Five
Complete opposite of the _.nl2br - This replaces any HTML Line breaks with the line return character,
which can optionally be specified, but defaults to just \r\n. The HTML break replaced is
,
,
or
Kind: static method of _
Returns: string
- Modified version of ${str}, with all HTML line breaks replaced with new-line characters
Todo
- Another parameter to optionally trim the string before line breaks to get rid of first/last
- Another parameter to keep the </br> tag on the end of the newly added \n
Param | Type | Default | Description |
---|---|---|---|
str | string |
String to process and replace any HTML line breaks for | |
[nl] | string |
"'\r\n'" |
New line character (\r\n by default) |
Example
_.nl2br("One<br>Two</br>Three</BR>Four<BR>Five")
// => One\r\nTwo\r\nThree\r\nFour\r\nFive
Censor any common profanity words by replacing it with a specified word, or masking all or some of the characters with a single specified character. The words are kept in the separate data.js file, and base64 encrypted, as to not store a huge list of profanity on any users computer. The list of words is actually a list that was downloaded from a TeamSpeak related website of words to ban: http://addons.teamspeak.com/directory/addon/miscellaneous-tools/TXT-English-badwords-bans-and-list.html Note: This only supports the English language, the dirty version
Kind: static method of _
Returns: string
- Parsed and censored version of the provided word
Param | Type | Default | Description |
---|---|---|---|
word | string |
Word to censor and parse | |
[masker] | string |
"'*'" |
Single character or full single word |
[maskType] | string |
"'partial'" |
The masking 'type', can be: full Entire word single Single character firstlast First and last letters middle All BUT first and last partial Majority of letters (55% after first letter) |
Example
_.censor('damn')
// => d**n
Generate a salted hash of a specified password string - Similar to PHPs password_hash function, which returns a string with the hash AND the salt, making it easier to store in a database, and easier to verify
Kind: static method of _
Returns: string
- 109 character password hash (salt is first 20 characters)
Note: Every password hash is generated by using a salt value that is randomly generated every time, this means
that the resulting hash will be different every time it executes, even if the passwords are the same
Param | Type | Description |
---|---|---|
password | string |
Password to hash |
Example
const pwd1 = _.passwordHash('SomePass')
// => LIE9OKy0g$eNB <cut> XFMcfx78L5SuZZivA==
const pwd2 = _.passwordHash('SomePass')
pwd1 === pwd2
// => false
Verify a password against a password hash generated by _.passwordHash
Kind: static method of _
Returns: boolean
- TRUE if the result of a hash generated with the
same password and the salt found in passwordHash,
matches the hash inside passwordHash
Param | Type | Description |
---|---|---|
password | string |
Password to verify |
passwdHash | string |
String generated by _.passwordHash |
Example
const hashA = _.passwordHash( 'secret' )
_.passwordVerify( 'secret', hashA )
// => true
Return a copy of the object with the content sorted by the keys
Kind: static method of _
Param | Type | Description |
---|---|---|
obj | object |
Object to sort by keys |
comparator | function |
Function to compare/sort the elements |
Example
const obj = {b: 3, c: 2, a: 1}
console.log( _.sortObj( obj ) )
console.log( _( obj ).sortObj().value() )
// => {a: 1, b: 3, c: 2}
_.sortObj( obj, ( value, key ) => value )
// => {a: 1, c: 2, b: 3}
Validate that an array, or objects in an array, or elements within the objects in an array are all unique
Kind: static method of _
Param | Type | Description |
---|---|---|
collection | array |
Single level array or array of objects |
[element] | string |
If collection is an array of objects, and we are to check that a specific element in those objects is unique, then this should be the name of the element in the object |
Example
_.isUniq( [ 1, 2, 3, 2 ] )
// => false
_.isUniq( [ {a: 1}, {a: 2}, {a: 1} ] )
// => false
_.isUniq( [ {a: 1, b: 2}, {a: 2, b: 5}, {a: 1, b: 2} ], 'b')
// => false
Remove items from object, mutating the original object by removing specified element(s), and returning a new object of said element(s) This is basically the same as lodashes _.remove method, except this works for Objects, not arrays.
Kind: static method of _
Returns: object
- Object of items removed from obj param
Note: This will mutate the original object, removing the del
element(s)
Todo
- Need to add some sanity checking, some more logic, etc etc
- This should be able to take a function for the del
Param | Type | Description |
---|---|---|
obj | object |
Object (to mutate) |
del | array | string |
Element(s) to remove from obj |
Example
var testObj = { first: 'John', last: 'Doe', middle: 'w', age: 26, height: 75 }
testObj = _.removeObj( testObj, 'height')
// => { first: 'John', last: 'Doe', middle: 'w', age: 26 }
testObj = _.removeObj( testObj, [ 'age','middle' ])
// => { first: 'John', last: 'Doe' }
Escape a string, making it safe to use in a MySQL query. Based off of PHPs mysql_real_escape_string
Kind: static method of _
Returns: string
- Safe version of the content string parameter
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
content | string |
String to use in the MySQL query |
Example
_.mysqlEscape( "Justin\\\\'s Boots" )
// => "Justin\\'s Boots"
Check if a specified string is in snake_case format
Kind: static method of _
Returns: boolean
- Returns True if the string is in case snake, False otherwise.
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isSnake( _.snakeCase('Foo Bar') )
// => true
_.isSnake( _.camelCase('Foo Bar') )
// => false
Check if a specified string is in camelCase format
Kind: static method of _
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isSnake( _.snakeCase('Foo Bar') )
// => true
_.isSnake( _.camelCase('Foo Bar') )
// => false
Check if a specified string is in kebab-case format
Kind: static method of _
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isKebab( _.kebabCase('Foo Bar') )
// => true
_.isKebab( _.camelCase('Foo Bar') )
// => false
Check if a specified string is in Start Case format
Kind: static method of _
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isSnake( _.snakeCase('Foo Bar') )
// => true
_.isSnake( _.camelCase('Foo Bar') )
// => false
Check if a specified string is in lower case format
Kind: static method of _
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isLower( _.lowerCase('Foo Bar') )
// => true
_.isLower( _.upperCase('Foo Bar') )
// => false
Check if a specified string is in UPPER CASE format
Kind: static method of _
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
_.isUpper( _.upperCase('Foo Bar') )
// => true
_.isUpper( _.lowerCase('Foo Bar') )
// => false
Retrieve the case type of a specified string
Kind: static method of _
Returns: string
| undefined
- Will return one of: snake, camel, kebab, start, lower, upper or undefined if none
Note: ALPHA PHASE - Under Construction, needs a serious re-write
Param | Type | Description |
---|---|---|
str | string |
String to inspect |
Example
var str = 'Hello World..'
_.each()
Verify a string is in a specified format.
Kind: static method of _
Note: ALPHA PHASE - Under Construction
Param | Type | Description |
---|---|---|
theCase | string |
The case to validate |
str | string |
String to inspect |
Example
_.isCase( 'snake', _.snakeCase( 'Hello World' ) )
// => true
_.isCase( 'kebab', _.snakeCase( 'Hello World' ) )
// => false
Verify that a collection (string, array or object) has all listed values, basically just an array-friendly version of _.includes
Kind: static method of _
Returns: boolean
- Returns true
based on the result of _.includes
Param | Type | Description |
---|---|---|
collection | array | object | string |
The collection to search |
values | mixed |
The value or values to search for |
fromIndex | number |
The index to search from. |
Example
_.includesAll( [1,2,3], [1,3] )
// => true
_.includesAll( [1,2,3], [1,2], 2 )
// => false
_.includesAll( {user: 'fred', age: 40 }, ['fred', 40] )
// => true
_.includesAll( 'abcdef', ['a','d] )
// => true
Use the Levenshtein formula to calculate the distance in the similarities of two separate strings, which can be anywhere from 0 (strings are identical) to the length of the longer string provided (100% different). The higher the distance, the more different the strings are, but the distance can only be as high as high as the number of characters in the longer string
Kind: static method of _
Returns: number
- Levenshtein distance value
Note: ALPHA PHASE - Under Construction
Todo
- Create unit tests
Param | Type | Description |
---|---|---|
strA | string | number |
String A |
strB | string | number |
String .... Yep, B |
Example
levenshtein( 'foo','foo' )
// => 0
levenshtein( 'foo','bar' )
// => 3
String Difference Distance (In percentages). This basically returns the Levenshtein value as a percentage
Kind: static method of _
Returns: number
- Levenshtein distance percentage (WITHOUT the % on the end)
Todo
- Create unit tests
Param | Type | Description |
---|---|---|
strA | string | number |
String A |
strB | string | number |
String .... Yep, B |
Example
strDist( 'foo','foo' )
// => 0
strDist( 'foo','bar' )
// => 100
strDist( 'something', 'somewhere' )
// => 44.44
Return the plural version of a string
Kind: static method of _
Returns: string
- Plural version of same noun
Todo
- Create unit tests
Param | Type | Description |
---|---|---|
str | string |
Singular format of a noun |
Example
_.plural( 'apple' )
// => apples
_.plural( 'toy' )
// => toys
_.plural( 'fly' )
// => flies
Merge multiple objects together without mutating the original object This basically just hands everything off to _.merge, just adds an empty object to the beginning, so _.merge( {}, ObjsA, ObjsB ) would be the same as _.mergeObjs( ObjsA, ObjsB )
Kind: static method of _
Returns: object
- Newly merged object
Param | Type | Description |
---|---|---|
[...sources] | object |
The source objects |
Example
_.mergeObjs( { a: 1 }, { b: 2 }, { c: 3 } )
// => { a: 1, b: 2, c: 3 }
Ensures the item is an instance of the exception specified by type
Kind: static method of _
Returns: Mixed
- Returns an instance of Error, or whatevers specified by item
Param | Type | Default | Description |
---|---|---|---|
item | Mixed |
Item/Error/Whatever | |
[type] | Mixed |
Error |
Exception type (Default: Error) |
Example
let err = 'Error Str'
// => Error Str
err = _.setException( err )
// => [Error: Error Str]
err = _.setException( err )
// => [Error: Error Str]
// Notice no matter how many times its used, Error is not nested, as opposed to setting new Error( err )
Pulls a sample from an array - Useful for when iterating over an array (manually), and having to remove the previous iterations
Kind: static method of _
Returns: Mixed
- Whatever element was sampled from the array
Note: This method mutates the array, just as _.pull does
Param | Type | Description |
---|---|---|
arr | array |
Array to sample |
Example
var data = [ 100, 200 ]
_.pullSample( data )
// => 200
_.pullSample( data )
// => 100
_.pullSample( data )
// => []
Pulls an array of samples from an array - Basically the same thing as _.pullSample, except this samples multiple elements, with the amount specified by the size parameter
Kind: static method of _
Returns: array
- Array of one or more elements from arr
Note: This method mutates the array, just as _.pull does
Param | Type | Description |
---|---|---|
arr | array |
Array to sample |
size | number |
Amount of elements to sample/remove from arr |
Example
var data = [ 100, 200, 300, 400 ]
_.pullSampleSize( data, 2 ) // [ 100, 200 ]
_.pullSampleSize( data, 2 ) // [ 300, 400 ]
_.pullSampleSize( data, 2 ) // [ ]
data // []
Validation for legitimate regular expression pattern validation
Kind: static method of _
Returns: boolean
| string
- If the pattern will work in a regexp check, then true
Note: This is best used when validating strings, as invalid regexp elements will throw an error before this
function even gets a chance to validate. Meaning something like _.validPattern(/a/asdf)
will throw an
exception on the line the invalid pattern was passed
Todo
- Somehow parse a string for a regex pattern and flags; EG: /foo/g -> ['foo','g']; %bar%i -> ['bar','i']
Param | Type | Description |
---|---|---|
pattern | Mixed |
Pattern to validate (String, number, regexp, etc) |
flags | string |
Regular expression flags (Not required) |
reason | boolean |
If pattern is invalid, instead of returning false, return the error (string), which would change the return to true = valid, and any string = invalid |
Return the type of a specific variable, much like the standard 'typeof', only with a little more functionality. This is primarily used for input from libraries/packages/modules that may convert the variable to a different type when interacting with it. For example, pretty much anything passed through the URI parameters will be a string, as well as anything passed through GetOpts, but you may want integers, for example, to actually be identified as numbers, or true/false/null/undefined strings to be identified as boolean/null/undefined. That's what the scrutinize parameter does here, it will process the variable to attempt to identify the type it originally was.
NOTE: If no type is matched, then the toString() value will be returned
Kind: static method of _
Returns: string
- The variable type; The default type names are:
undefined, null, string, boolean, array, element, date, regexp, object, number, function, unknown
However, these can be overridden by providing an object as the 3rd parameter
Param | Type | Description |
---|---|---|
value | * |
Value to process |
inspect | boolean |
Determine if the true value type should be determined through logical processing |
returnTypes | object |
Object of return type strings to overwrite |
flaggedVals | object |
Values used to determine the real value types of flagged values (Only used if scrutinize is enabled) |
Example
_.typeof( [1,2] ) // array
_.typeof( 'foo' ) // string
_.typeof( true ) // boolean
_.typeof( 'true' ) // string
_.typeof( 'true',true ) // boolean
_.typeof( null ) // null
_.typeof( 'null' ) // string
_.typeof( 'null',true ) // null
Extra useful Lodash mixins
Kind: global constant
Requires: module:lodash,
Title: Lodash Mixins aka flat-line
Url: https://github.com/SASSET/flat-line
See: https://github.com/SASSET/flat-line
Version: 0.1.0
Author: Justin Hyland (Mostly)
Todo
-
Split all functions into separate .js files; which can all be loaded by loading the index