Created
October 25, 2017 15:40
-
-
Save joseluisq/6c0d1efee6b3a47bfd738cd02465b302 to your computer and use it in GitHub Desktop.
Some NodeJS helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isEmpty = require('lodash.isempty') | |
const isObject = require('lodash.isobject') | |
/** | |
* Prevent empty object value | |
* | |
* @param {object} value | |
* @returns {object|null} | |
*/ | |
function notEmpty (value) { | |
return (isObject(value) && isEmpty(value)) || typeof value === 'undefined' ? null : value | |
} | |
/** | |
* Verify if a value is not an Array and return it as new array | |
* | |
* @param {string|number|object} value | |
* @returns {array} | |
*/ | |
function asArray (value = []) { | |
return Array.isArray(value) ? value : [ value ] | |
} | |
/** | |
* Verify an object value and return string value or an empty string | |
* | |
* @param {object} value | |
* @returns {string} | |
*/ | |
function asString (value = '') { | |
return notEmpty(value) || '' | |
} | |
/** | |
* Map a root object properties and return an array | |
* If callback is not provided the functions returns [key, value] | |
* | |
* @param {object} obj | |
* @returns {array} | |
*/ | |
function mapObject (obj, callback = null) { | |
const result = [] | |
const keys = Object.keys(obj) | |
const len = keys.length | |
for (let i = 0; i < len; i += 1) { | |
const key = keys[i] | |
const value = obj[key] | |
let res = [] | |
if (callback) { | |
res = callback(value, key) | |
} else { | |
res = [ key, value ] | |
} | |
if (res) result.push(res) | |
} | |
return result | |
} | |
module.exports = { | |
notEmpty, | |
asArray, | |
asString, | |
mapObject | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment