Socket
Socket
Sign inDemoInstall

dry-underscore

Package Overview
Dependencies
Maintainers
1
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dry-underscore - npm Package Compare versions

Comparing version 0.4.4 to 0.4.13

build

728

lib/common.js
exports.mixin = function(_){
_.date = function(ts){
if(_.isNumber(ts)){
return(new Date(ts));
}else{
return(new Date());
}
};
_.timestamp = function(d){
if(_.isNumber(d)){ return(_.timestamp() + d); }
if(d === undefined){ d = _.date(); }
return(d.getTime());
};
_.lc = function(s){
return(s.toLowerCase());
};
_.isoDate = function(d){
if(d === undefined){ d = _.date(); }
return(_.moment(d).format("YYYY-MM-DD"));
};
_.ms = function(n){
if(n === undefined){ return(0); }
else{ return(n); }
};
_.ms.second = function(n){
if(n === undefined){ n = 1; }
return(n * _.ms(1000));
};
_.ms.minute = function(n){
if(n === undefined){ n = 1; }
return(n * _.ms.second(60));
};
_.ms.hour = function(n){
if(n === undefined){ n = 1; }
return(n * _.ms.minute(60));
};
_.ms.day = function(n){
if(n === undefined){ n = 1; }
return(n * _.ms.hour(24));
};
_.ms.week = function(n){
if(n === undefined){ n = 1; }
return(n * _.ms.day(7));
};
_.minutes = function(n){
if(n === undefined){ return(0); }
else{ return(n); }
}
_.minutes.hour = function(n){
if(n === undefined){ n = 1; }
return(n * _.minutes(60));
};
_.minutes.day = function(n){
if(n === undefined){ n = 1; }
return(n * _.minutes.hour(24));
};
_.minutes.week = function(n){
if(n === undefined){ n = 1; }
return(n * _.minutes.day(7));
};
_.minutes.timeString = function(min){
var hours = Math.floor(min / 60);
var minutes = min % 60;
var amPm = "AM";
if(hours >= 12){ amPm = "PM"; }
if(hours > 12){
hours -= 12;
}
if(minutes < 10){
minutes = "0" + minutes;
}
return(hours + ":" + minutes + " " + amPm);
};
var oldMax = _.max;
_.max = function(a, b){
if(_.isNumber(a) && _.isNumber(b)){
if(a > b){ return(a); }
else{ return(b); }
}else{ return(oldMax.apply(_, arguments)); }
};
var oldMin = _.min;
_.min = function(a, b){
if(_.isNumber(a) && _.isNumber(b)){
if(a < b){ return(a); }
else{ return(b); }
}else{ return(oldMin.apply(_, arguments)); }
};
_.concat = function(){ return(Array.prototype.concat.apply([], arguments)); };
_.fatal = function(){ throw(new Error("Fatal Error: " + _.format.apply(null, arguments))); };
_.jsonClone = function(o){
return(_.parse(_.stringify(o)));
};
_.regex = function(str){ return(new RegExp(str)); };
_.onceEvery = function(val, mod, hit, miss){
if((val % mod) === 0 && hit){ hit(); }
else if(miss){ miss(); }
};
_.render = function(templateName){
return(function(template, hash){
var f = null;
if(_.isString(template)){
f = _.hb.compile(template);
if(!templateName){ templateName = template; }
_.render.templates[templateName] = f;
}else if(_.isObject(template)){
hash = template;
template = null;
if(templateName){ f = _.render.templates[templateName]; }
}
if(!f){ _.fatal("no template found. template: " + template + " templateName: " + templateName); }
if(hash){ return(f(hash)); }
else{ return(f); }
});
};
_.render.templates = {};
_.mixin({
noop: function(){},
byteUnits : function(val){
var unit = "B";
if(val > 1024){
val /= 1024;
unit = "KB"
}
if(val > 1024){
val /= 1024;
unit = "MB"
}
if(val > 1024){
val /= 1024;
unit = "GB"
}
if(val > 1024){
val /= 1024;
unit = "TB"
}
return(val + " " + unit);
},
stringify : function(){ return(JSON.stringify.apply(null, arguments)); },

@@ -16,3 +167,13 @@ parse : function(){ return(JSON.parse.apply(null, arguments)); },

},
get: function(obj, key){
get: function(obj, key, defaultValue){
if(_.isFunction(obj)){ return(obj()); }
if(key === undefined){ return(obj); }
if(defaultValue !== undefined){
if(!obj[key]){
obj[key] = defaultValue;
return(obj[key]);
}else{
return(obj[key]);
}
}
if(obj[key] !== undefined){

@@ -64,2 +225,13 @@ if(_.isFunction(obj[key])){ return(obj[key]()); }

},
uiLock : function(f){
var running = false;
var eventLock = function(e){
if(running){ return e.preventDefault(); }
else{
running = true;
f.call(this, e, function(){ running = false; });
}
};
return(eventLock);
},
asyncLock : function(f, lockTest, lockModify, lockRelease){

@@ -89,3 +261,3 @@ var running = false;

args.push(lockRelease);
f.apply(null, args);
f.apply(this, args);
}

@@ -142,3 +314,3 @@

var callComplete = function(){ process.nextTick(complete) };
var callComplete = function(){ _.nextTick(complete) };
if(!complete){ callComplete = function(){}; }

@@ -269,4 +441,8 @@

toNumber : function(n){
return(n - 0);
n = n - 0;
if(isNaN(n)){ return(null); }
else{ return(n); }
},
n : function(n){ return(_.toNumber(n)); },
s : function(n){ return(n + ""); },
formatNumber: function(nStr){

@@ -535,2 +711,546 @@ nStr += '';

});
// taken from the nodejs source
_.format = (function(){
var formatRegExp = /%[sdj%]/g;
return(function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
});
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
_extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 4;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// This could be a boxed primitive (new String(), etc.), check valueOf()
// NOTE: Avoid calling `valueOf` on `Date` instance because it will return
// a number which, when object has some additional user-stored `keys`,
// will be printed out.
var formatted;
var raw = value;
try {
// the .valueOf() call can fail for a multitude of reasons
if (!isDate(value))
raw = value.valueOf();
} catch (e) {
// ignore...
}
if (isString(raw)) {
// for boxed Strings, we have to remove the 0-n indexed entries,
// since they just noisey up the output and are redundant
keys = keys.filter(function(key) {
return !(key >= 0 && key < raw.length);
});
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
// now check the `raw` value to handle boxed primitives
if (isString(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[String: ' + formatted + ']', 'string');
}
if (isNumber(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[Number: ' + formatted + ']', 'number');
}
if (isBoolean(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
// Make boxed primitive Strings look like such
if (isString(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[String: ' + formatted + ']';
}
// Make boxed primitive Numbers look like such
if (isNumber(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[Number: ' + formatted + ']';
}
// Make boxed primitive Booleans look like such
if (isBoolean(raw)) {
formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[Boolean: ' + formatted + ']';
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value)) {
// Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
// so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
if (value === 0 && 1 / value < 0)
return ctx.stylize('-0', 'number');
return ctx.stylize('' + value, 'number');
}
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatPrimitiveNoColor(ctx, value) {
var stylize = ctx.stylize;
ctx.stylize = stylizeNoColor;
var str = formatPrimitive(ctx, value);
ctx.stylize = stylize;
return str;
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'")
.replace(/\\\\/g, '\\');
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var length = output.reduce(function(prev, cur) {
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isString(arg) {
return typeof arg === 'string';
}
function isSymbol(arg) {
return typeof arg === 'symbol';
}
function isUndefined(arg) {
return arg === void 0;
}
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
function isFunction(arg) {
return typeof arg === 'function';
}
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
function isBuffer(arg) {
return arg instanceof Buffer;
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
/*
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
*/
var _extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
})();
};

@@ -537,0 +1257,0 @@

6

lib/dry.js

@@ -26,6 +26,6 @@

if(!Array.isArray(types)){ types = [types]; }
if(!_.isArray(types)){ types = [types]; }
if(!(nullOk && val === null)){
if(!(val && typeof(val) === 'object' && val.Type && _.exists(types, val.Type, true))){
if(!(val && _.isObject(val) && val.Type && _.exists(types, val.Type, true))){
messages.push("Expected any of the following types: [" + types + "]");

@@ -43,3 +43,3 @@ }

if(!Array.isArray(val)){
if(!_.isArray(val)){
messages.push('Expected array, found object');

@@ -46,0 +46,0 @@ return(messages);

@@ -10,3 +10,3 @@

var that = this;
if(typeof(tag) === 'function'){
if(_.isFunction(tag)){
callback = tag;

@@ -38,9 +38,7 @@ tag = "";

}else{
var handlers = that._events[event];
if(that._events && that._events[event]){
that._events[event] = _.filter(that._events[event], function(val){
if(typeof(callback) === 'function'){
if(_.isFunction(callback)){
return(val.handler !== callback);
}else if(typeof(callback) === 'string'){
}else if(_.isString(callback)){
return(val.tag.toLowerCase() !== callback.toLowerCase());

@@ -47,0 +45,0 @@ }

exports.mixin = function(_){
var log = function(){
if(arguments.length && _.isObject(arguments[0])){
var args = _.toArray(arguments);
var options = args.unshift();
}else{
console.log.apply(console, arguments);
}
return({
debug: log,
info: log,
notice: log,
warning: log,
error: log,
crit: log,
alert: log,
emerg: log,
});
};
var logNs = [];
// var options = { level: 'info' };
var options = { level: 'debug' };
var log = function(){
return(log);
function print(){
var args = _.toArray(arguments);
var ns = logNs.join(".");
if(ns){ ns += ": "; }
args.unshift(ns);
console.log(_.format.apply(null, args));
}
if(arguments.length){
var args = _.toArray(arguments);
if(_.isObject(arguments[0])){
_.extend(options, args.unshift());
}
print.apply(this, args);
}
var loggers = {};
var logPriorities = ['emerg', 'alert', 'crit', 'error', 'warning', 'notice', 'info', 'debug'];
var ignore = false;
_.each(logPriorities, function(logName){
if(ignore){ loggers[logName] = _.noop; }
else{ loggers[logName] = log; }
if(options.level.toLowerCase() == logName.toLowerCase()){ ignore = true; }
});
return(loggers);
};
log.push = function(ns){ logNs.push(ns); };
log.pop = function(){ return(logNs.pop()); };
log.wrap = function(ns, f){
return(function(){
log.push(ns);
var val = f.apply(this, arguments);
log.pop();
return(val);
});
};
return(log);
};

@@ -7,10 +7,51 @@

var child_process = require('child_process');
var mustache = require('mustache');
exports.mixin = function(_){
_.nextTick = process.nextTick;
_.test = require('assert');
_.test.eq = function(){
return(_.test.deepEqual.apply(null, arguments));
};
_.render.templateRoot = function(root){
if(root){
_.render._templateRoot = root;
}else{
if(_.render._templateRoot){ return(_.render._templateRoot); }
else{ return(""); }
}
};
_.render.loadDirectory = function(rootPath){
function pattern(fileName){
var include = _.fs.glob.matchFile(fileName, "*.mu") || _.fs.glob.matchFile(fileName, "*.hb")
_.log().debug(fileName, ":", include);
return(include);
}
var files = _.fs.find(rootPath, { pattern : pattern });
_.each(files, function(filePath){
_.render.loadFile(filePath);
});
};
_.render.loadFile = function(templateName, filePath){
if(!filePath){
filePath = templateName;
templateName = _.fs.path.basename(templateName);
templateName = templateName.replace(_.regex(".mu$"), "");
templateName = templateName.replace(_.regex(".hb$"), "");
}
filePath = _.fs.path.join(_.render.templateRoot(), filePath);
var template = _.fs.readFile(filePath);
if(template && template.length && template[template.length-1] == "\n"){
template = template.substr(0, [template.length-1]);
}
_.log().debug(templateName, "(0, 20):", _.stringify(template).substr(0, 20));
_.render(templateName)(template);
return(templateName);
};
_.mixin({
render : function(template, hash){
return(mustache.render(template, hash))
},
wget : function(url, destPath, callback){

@@ -76,6 +117,13 @@ var wget = 'wget -O ' + destPath + ' ' + url;

_.dry = require('./dry.js').mixin(_);
_.test = require('./test.js').mixin(_);
require('./dry.server.js').mixin(_);
_.html = require('./html.js').mixin(_);
_.log = require('./log.js').mixin(_);
_.ns = require('./ns.js').mixin(_);
_.hb = require('handlebars')
_.moment = require('moment');
_.eventEmitter = require('./eventEmitter.js').mixin(_);
_.eventEmitter(_);
_.hook = require('./hook.js').mixin(_);
_.events = {};
_.eventEmitter(_.events);
require('./log.server.tjs').mixin(_);

@@ -82,0 +130,0 @@ _.getFirst = function(obj){

{
"name":"dry-underscore",
"version":"0.4.4",
"version":"0.4.13",
"main": "./lib/index.js",

@@ -31,7 +31,8 @@ "description": "The DRY Undescore Library",

, "tosource" : ""
, "mustache" : ""
, "tamejs" : ""
, "minimatch" : ""
, "superagent" : ""
, "moment" : ""
, "handlebars" : "1.3.0"
}
}

@@ -6,2 +6,3 @@

var _ = require('../');
var eq = _.test.eq;

@@ -12,3 +13,107 @@ exports.testHasType = testHasType;

exports.testEmptyIterate = testEmptyIterate;
exports.testGet = testGet;
exports.testTest = testTest;
exports.testFormat = testFormat;
exports.testConcat = testConcat;
exports.testMoment = testMoment;
exports.testHandleBars = testHandleBars;
//exports.hashTest = hashTest;
//exports.testFatal = testFatal;
//exports.random = function(){ _.log(_.sha256(_.uuid())); };
/*
exports.testRequest = function(){
_.request('localhost/test', function(req){
_.log(req);
});
};
*/
function testHandleBars(){
var data = {"person": { "name": "Alan" }, "company": {"name": "Rad, Inc." } };
var template = "{{person.name}} - {{company.name}}";
_.time("pre");
eq("Alan - Rad, Inc.", _.render("example")(template, data));
_.time("pre", true);
_.time("post");
eq("Alan - Rad, Inc.", _.render("example")(data));
_.time("post", true);
_.render.loadDirectory("./test/testTemplates");
_.render.loadFile("single", "./test/test.hb");
_.render.loadFile("singleTwo", "./test/test.hb");
eq(_.render("single")({ data: "hello" }), "hello");
eq(_.render("singleTwo")({ data: "hello" }), "hello");
eq(_.render("testTemplate")({ data: "hello" }), "hello");
eq(_.render("testTemplateTwo")({ data: "hello" }), "hello");
};
function testMoment(){
_.log(_.moment().format("YYYY-MM-DD"));
}
function hashTest(){
var iterations = 100 * 1000;
var iterations = 10000;
function testHash(key){
var h = {};
_.time("key length: " + _.byteUnits(key.length));
for(var i = 0; i < iterations; i++){
h[key] = i + (i-1);
}
_.time("key length: " + _.byteUnits(key.length), true);
}
testHash(Array(10).join('a'));
testHash(Array(100).join('a'));
testHash(Array(1000).join('a'));
testHash(Array(10000).join('a'));
testHash(Array(100000).join('a'));
testHash(Array(1000000).join('a'));
}
function testFatal(){
_.fatal("should be pretty: a b c", {'a':'b','c':'d'}, ['a', 'b', 'c', 'd']);
}
function testFormat(){
assert.eql("should be pretty: a b c { a: 'b', c: 'd' } [ 'a', 'b', 'c', 'd' ]", _.format("should be pretty: a b c", {'a':'b','c':'d'}, ['a', 'b', 'c', 'd']));
}
function testConcat(){
assert.deepEqual(_.concat(['a'], 'b', 'c', ['d', 'e']), ['a', 'b', 'c', 'd', 'e']);
}
function testTest(){
var n = 0;
_.test.eq(['a', 'b', 'c'], ['a', 'b', 'c']);
_.test.eq(['a', 'b', 'c'], ['a', 'b', 'c']);
try{ _.test.eq(['c', 'c', 'c'], ['a', 'b', 'c']); }catch(e){ n++; }
_.test.eq([null], [null]);
try{ _.test.eq([0], [false]); }catch(e){ n++; }
try{ _.test.eq([0], [null]); }catch(e){ n++; }
_.test.equal(n, 3);
}
function testGet(){
assert.strictEqual(_.get(function(){ return('a'); }), 'a');
assert.strictEqual(_.get('a'), 'a');
assert.strictEqual(_.get({ 'a': 'b'}, 'a'), 'b');
assert.strictEqual(_.get({ 'a': function(){ return('b'); }}, 'a'), 'b');
assert.strictEqual(_.get({ 'A': 'b'}, 'a'), 'b');
assert.strictEqual(_.get(['a', 'b'], 1), 'b');
assert.strictEqual(_.get(['a', 'b'], 1), 'b');
assert.strictEqual(_.get({ 'A': 'b'}, 'c'), undefined);
assert.strictEqual(_.get(function(){ return('a'); }), 'a');
var z = {'a': 'b'};
_.get(z, 'c', {}).c = 'c';
assert.deepEqual(z, {'a' : 'b', 'c' : {'c' : 'c'}});
}
function testEmptyIterate(beforeExit){

@@ -15,0 +120,0 @@

@@ -22,3 +22,3 @@ var assert = require('assert');

test(_);
test(_.events);
};

@@ -25,0 +25,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc