Created
March 29, 2012 23:15
-
-
Save johntimothybailey/2244813 to your computer and use it in GitHub Desktop.
Underscore function for determining if a given object is viable
This file contains hidden or 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
!function(root){ | |
'use strict'; | |
/** | |
* Determine if an object is viable according to specifications given or the defaults provided | |
* @param value The object to evaluate for viability | |
* @param options (optional) The options for changing the viability criteria. If an array is provided then it is assumed to be the property "nonViables" Possible options: | |
* nonViables An array of properties and functions that describe the value as being nonviable. These will be added to the default nonviables | |
* defaultNonViables An array of the default nonviables. These will override the functions default nonviables. | |
* originally developed at: http://jsfiddle.net/johntimothybailey/6UUD5/ | |
* @contribution: RJ Regenold (https://gist.github.com/4927b3ba864d86209f7e). "The reduce idea and implementation is super clean" - John of the Bailey's | |
*/ | |
var _isViable = function ( value, options ) { | |
if(_.isArray(options)){ | |
options = { | |
"nonViables": options | |
} | |
} | |
options = _.extend({ | |
nonViables: [], | |
defaultNonViables: ["undefined","","null", "NaN",_.isNull,_.isUndefined,_.isNaN] | |
},options); | |
var nonViables = _.reduce(options.nonViables.concat(options.defaultNonViables), | |
function(memo, item) { | |
if (_.isFunction(item)) memo.methods.push(item); | |
if (_.isString(item)) memo.values.push(item); | |
return memo; | |
}, | |
{methods: [], values: []}); | |
// return false immediately if matching a non viable method | |
if( _.find(nonViables.methods,function(method){return method(value);})){ | |
return false; | |
} | |
return !_.contains(nonViables.values,value); // Otherwise check against the values. Normally these apply to the value being a String or Number | |
}; | |
// CommonJS module is defined | |
if (typeof exports !== 'undefined') { | |
if (typeof module !== 'undefined' && module.exports) { | |
// Export module | |
module.exports = _isViable; | |
} | |
exports._isViable = _isViable; | |
// Integrate with Underscore.js | |
} else if (typeof root._ !== 'undefined') { | |
root._.mixin({isViable:_isViable}); | |
// Or define it | |
} else { | |
root._ = { | |
isViable: _isViable | |
}; | |
} | |
}(this || window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment