I have a clear
function that accepts an array
, string
, or no arguments. If no arguments, it should clear the entire data
object. It works fine, but looking for a code review.
The possibilities should be:
clear('one');
clear(); //clear all
clear(['one', 'three']);
var data = {
one: 'test1',
two: 'test2',
three: 'test3'
};
var clear = function(fields) {
if (fields !== undefined) {
if (typeof fields === 'string') {
data[fields] = '';
} else {
_.each(fields, function(field) {
if(data.hasOwnProperty(field)) {
data[field] = '';
}
});
}
} else {
// clear all
_.each(data, function(value, key) {
data[key] = '';
});
}
};
clear(['one', 'two']);
clear();
clear(['one']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>