├── README └── dollars.js /README: -------------------------------------------------------------------------------- 1 | This is a custom library I'm starting that will include all kinds of javascript snippets I find useful. 2 | 3 | I will add them all to one file. They will possibly depend on Underscore.js and jQuery.js, and all of the functions will be attached to the "dollars" variable $$. 4 | 5 | This library is definitely not meant for production but rather for fast prototyping. Afterwards one could pick and choose the parts that are used. -------------------------------------------------------------------------------- /dollars.js: -------------------------------------------------------------------------------- 1 | $$ = dollars = {}; 2 | 3 | // Formatting Methods 4 | dollars.formatSize = function(size, precisionArg, thresholdArg) { 5 | var units = " bytes, KB, MB, GB".split(","); 6 | var precision = precisionArg || 1; 7 | var threshold = thresholdArg || 500; 8 | var kilo = 1024; 9 | 10 | for (var dim = 0; dim < units.length-1; dim++) { 11 | if (size < threshold) { 12 | return (size % 1 ? size.toFixed(precision) : size) + units[dim]; 13 | } else { 14 | size = size / kilo; 15 | } 16 | } 17 | 18 | return size.toFixed(precision) + units.pop(); 19 | } 20 | 21 | // Creates a copy from `collection` with only the key-value 22 | // pairs specified by `keys`. 23 | // 24 | // Example: 25 | // 26 | // var obj = {name: "David", age: 25, email: "david@crowdway.com"}; 27 | // $$.filterKeys(obj, ["name", "age"]); 28 | // // This would return 29 | // { name: "David", age: 25 } 30 | dollars.filterKeys = function(collection, keys, predicate) { 31 | var results = {}; 32 | var predicateArg = predicate || _.include; 33 | 34 | _.each(collection, function(value, key) { 35 | if (predicateArg(keys, key)) { 36 | results[key] = value; 37 | } 38 | }); 39 | 40 | return results; 41 | } 42 | 43 | // Does the opposite of `filterKeys`: creates a new object 44 | // containing key-values that were not in keys. 45 | dollars.withoutKeys = function(collection, keys) { 46 | return dollars.filterKeys(collection, keys, function(a, b) { 47 | return !_.include(a, b); 48 | }); 49 | } --------------------------------------------------------------------------------