Package Exports
- deep-cuts
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (deep-cuts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Deep Cuts
This project is a collection of otherwise uncategorized utility functions. Requires Lodash as peer dependency, be warned.
Installation
npm install --save lodash
npm install --save deep-cutsGetting Started
Just require the module, every method lives at the top level.
const { safeJsonParse } = require('deep-cuts');
console.log(safeJsonParse(JSON.stringify({message: 'I will be safely parsed'})));Methods
acceptNoArguments(fn, [args])
Creates a function that accepts no arguments at call time. Behaves similar to lodash partial method, arguments can be provided at create time. None can be passed at call time.
function myFunction(...args) {
console.log(`I was called with ${args.length} arguments.`);
}
acceptNoArguments(myFunction)(0, 1, 2); // I was called with 0 arguments.
acceptNoArguments(myFunction, 3, 4)(0, 1, 2); // I was called with 2 arguments.csvRowsToObjects(rows, [options={queryStringsToObjects: false, jsonStringsToObjects: false, parseFloats: false, trimValues: false, listDelimiter: ','}])
Takes an array of arrays as input and maps the headers out to objects in a consistent manner. Supports nesting with dot properties and array value types.
const rows = [
['red', 'green[]', 'blue.forty.goodTimes'],
['1', 'Iron Maiden', 'Ronnie James'],
['2', 'Koolaid,Hawaiian Punch', 'Peter Griffin']
];
csvRowsToObjects(rows);
/** Output
[
{
red: '1',
green: ['Iron Maiden'],
blue: {
forty: {
goodTimes: 'Ronnie James'
}
}
},
{
red: '2',
green: ['Koolaid', 'Hawaiian Punch'],
blue: {
forty: {
goodTimes: 'Peter Griffin'
}
}
}
]
**/Options
- queryStringsToObjects: Encodes query strings in array cells to objects.
- jsonStringsToObjects: Supports JSON objects in array cells.
- parseFloats: Parses any number found into a float.
- trimValues: Trims extra whitespace in values.
- listDelimiter: Default is comma, can be any character used for array delimiting.
objectsToCsvRows(objects, [options={queryStringsToObjects: false, jsonStringsToObjects: false, listDelimiter: ','}])
This method is the inverse of the above method. This will take the nested objects and get them back to CSV rows format.
const objects = [
{
red: '1',
green: ['Iron Maiden'],
blue: {
forty: {
goodTimes: 'Ronnie James'
}
}
},
{
red: '2',
green: ['Koolaid', 'Hawaiian Punch'],
blue: {
forty: {
goodTimes: 'Peter Griffin'
}
}
}
];
objectsToCsvRows(objects);
/** Output
[
['red', 'green[]', 'blue.forty.goodTimes'],
['1', 'Iron Maiden', 'Ronnie James'],
['2', 'Koolaid,Hawaiian Punch', 'Peter Griffin']
]
**/Options
- queryStringsToObjects: Encodes query strings in array cells to objects.
- jsonStringsToObjects: Supports JSON objects in array cells.
- listDelimiter: Default is comma, can be any character used for array delimiting.
escapeForRegExp(str)
Escapes any special characters so the strings can safely be placed in a RegExp constructor.
console.log(escapeForRegExp('function test() { return 5 * 5; }')); // function test\(\) \{ return 5 \* 5; \}flattenObject(obj)
Flattens an object so that every property is available at the top-level via the same key path as a property string. Compatible with lodash _.get / _.set.
const obj = {
name: {
first: 'Lemmy',
last: 'Kilmister'
},
favoriteColors: [
{ name: 'Black' },
{ name: 'Red' }
]
};
flattenObject(obj);
/** Output
{
'name.first': 'Lemmy',
'name.last': 'Kilmister',
'favoriteColors[0].name': 'Black',
'favoriteColors[1].name': 'Red'
}
**/functionOrValue(fnOrValue, [...args])
Returns either the value given or the return value of the function passed in. Can be called with optional arguments (...args). Also cascades downward if functions return functions.
console.log(functionOrValue(true)); // true
console.log(functionOrValue(() => false)); // false
console.log(functionOrValue((a, b, c) => a + b + c, 5, 6, 7)); // 18
console.log(functionOrValue((a, b, c) => () => a + c, 5, 6, 7)); // 12isJsonString(str)
Returns a boolean that specifies whether the string is parsable JSON.
const str = JSON.stringify({red: 5, green: 6});
isJsonString(str); // truejsonStreamToObject(stream)
Takes a stream object that contains stringified JSON data and parses it into an object (async).
const obj = await jsonStreamToObject(fs.createReadStream('my-json-file.json'));
// obj is just the exact, parsed json as an objectstringToBoolean(str)
Usually used for url parameters, converts null, undefined, 0, false, or '' to false even if they are strings. All other values are true.
console.log(stringToBoolean('0')); // false
console.log(stringToBoolean('null')); // false
console.log(stringToBoolean('undefined')); // false
console.log(stringToBoolean('false')); // false
console.log(stringToBoolean('')); // false
console.log(stringToBoolean(0)); // false
console.log(stringToBoolean(null)); // false
console.log(stringToBoolean(undefined)); // false
console.log(stringToBoolean(false)); // false
console.log(stringToBoolean()); // false
console.log(stringToBoolean(1)); // true
console.log(stringToBoolean({})); // true
console.log(stringToBoolean(true)); // truesafeJsonParse(strObj)
Wrapper around JSON.parse that will not throw errors for nil or poorly formatted strings. Returns null in any invalid case.
console.log(safeJsonParse("{\"message\": \"I will be safely parsed\"}")); // I will be safely parsed
console.log(safeJsonParse("{\"bad_key: \"value\"}")); // null
console.log(safeJsonParse(undefined)); // nulltryCatch(tryFn,[catchFn])
Functional, async tryCatch wrapper that provides an object with a response and error for alternative control flow.
async function trySomething() {...}
async function catchSomething(e) {
// DO SOME PASS THROUGH WORK HERE, OPTIONAL
return e;
}
const { response, error } = tryCatch(trySomething, catchSomething);
// response is the result of the trySomething function
// error is the error if no catchFn, or the return value of the catchFnContribution Guidelines
Fork the respository and install all the dependencies:
npm installMake sure to run the unit tests (and lint) before committing. Obviously, add to the tests as you make changes:
npm run testFor watch:
npm run test:watch