[UPD] update underscore and underscore.string libraries to latests versions

bzr revid: chs@openerp.com-20131108134931-muit7ym8q7g3ck1u
This commit is contained in:
Christophe Simonis 2013-11-08 14:49:31 +01:00
parent 0a42a9dec9
commit 1ec1125349
2 changed files with 901 additions and 476 deletions

View File

@ -1,12 +1,11 @@
// Underscore.string // Underscore.string
// (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org> // (c) 2010 Esa-Matti Suuronen <esa-matti aet suuronen dot org>
// Underscore.strings is freely distributable under the terms of the MIT license. // Underscore.string is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/epeli/underscore.string // Documentation: https://github.com/epeli/underscore.string
// Some code is borrowed from MooTools and Alexandru Marasteanu. // Some code is borrowed from MooTools and Alexandru Marasteanu.
// Version '2.3.2'
// Version 2.2.0rc !function(root, String){
(function(root){
'use strict'; 'use strict';
// Defining helper functions. // Defining helper functions.
@ -17,35 +16,50 @@
var parseNumber = function(source) { return source * 1 || 0; }; var parseNumber = function(source) { return source * 1 || 0; };
var strRepeat = function(str, qty, separator){ var strRepeat = function(str, qty){
// ~~var — is the fastest available way to convert anything to Integer in javascript. if (qty < 1) return '';
// We'll use it extensively in this lib. var result = '';
str += ''; qty = ~~qty; while (qty > 0) {
for (var repeat = []; qty > 0; repeat[--qty] = str) {} if (qty & 1) result += str;
return repeat.join(separator == null ? '' : separator); qty >>= 1, str += str;
}
return result;
}; };
var slice = function(a){ var slice = [].slice;
return Array.prototype.slice.call(a);
};
var defaultToWhiteSpace = function(characters) { var defaultToWhiteSpace = function(characters) {
if (characters != null) { if (characters == null)
return '[' + _s.escapeRegExp(''+characters) + ']';
}
return '\\s'; return '\\s';
else if (characters.source)
return characters.source;
else
return '[' + _s.escapeRegExp(characters) + ']';
}; };
// Helper for toBoolean
function boolMatch(s, matchers) {
var i, matcher, down = s.toLowerCase();
matchers = [].concat(matchers);
for (i = 0; i < matchers.length; i += 1) {
matcher = matchers[i];
if (!matcher) continue;
if (matcher.test && matcher.test(s)) return true;
if (matcher.toLowerCase() === down) return true;
}
}
var escapeChars = { var escapeChars = {
lt: '<', lt: '<',
gt: '>', gt: '>',
quot: '"', quot: '"',
apos: "'", amp: '&',
amp: '&' apos: "'"
}; };
var reversedEscapeChars = {}; var reversedEscapeChars = {};
for(var key in escapeChars){ reversedEscapeChars[escapeChars[key]] = key; } for(var key in escapeChars) reversedEscapeChars[escapeChars[key]] = key;
reversedEscapeChars["'"] = '#39';
// sprintf() for JavaScript 0.7-beta1 // sprintf() for JavaScript 0.7-beta1
// http://www.diveintojavascript.com/projects/javascript-sprintf // http://www.diveintojavascript.com/projects/javascript-sprintf
@ -175,28 +189,28 @@
var _s = { var _s = {
VERSION: '2.2.0rc', VERSION: '2.3.0',
isBlank: function(str){ isBlank: function(str){
if (str == null) str = '';
return (/^\s*$/).test(str); return (/^\s*$/).test(str);
}, },
stripTags: function(str){ stripTags: function(str){
return (''+str).replace(/<\/?[^>]+>/g, ''); if (str == null) return '';
return String(str).replace(/<\/?[^>]+>/g, '');
}, },
capitalize : function(str){ capitalize : function(str){
str += ''; str = str == null ? '' : String(str);
return str.charAt(0).toUpperCase() + str.substring(1); return str.charAt(0).toUpperCase() + str.slice(1);
}, },
chop: function(str, step){ chop: function(str, step){
str = str+''; if (str == null) return [];
step = ~~step || str.length; str = String(str);
var arr = []; step = ~~step;
for (var i = 0; i < str.length; i += step) return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
arr.push(str.slice(i,i + step));
return arr;
}, },
clean: function(str){ clean: function(str){
@ -204,20 +218,45 @@
}, },
count: function(str, substr){ count: function(str, substr){
str += ''; substr += ''; if (str == null || substr == null) return 0;
return str.split(substr).length - 1;
str = String(str);
substr = String(substr);
var count = 0,
pos = 0,
length = substr.length;
while (true) {
pos = str.indexOf(substr, pos);
if (pos === -1) break;
count++;
pos += length;
}
return count;
}, },
chars: function(str) { chars: function(str) {
return (''+str).split(''); if (str == null) return [];
return String(str).split('');
},
swapCase: function(str) {
if (str == null) return '';
return String(str).replace(/\S/g, function(c){
return c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase();
});
}, },
escapeHTML: function(str) { escapeHTML: function(str) {
return (''+str).replace(/[&<>"']/g, function(match){ return '&' + reversedEscapeChars[match] + ';'; }); if (str == null) return '';
return String(str).replace(/[&<>"']/g, function(m){ return '&' + reversedEscapeChars[m] + ';'; });
}, },
unescapeHTML: function(str) { unescapeHTML: function(str) {
return (''+str).replace(/\&([^;]+);/g, function(entity, entityCode){ if (str == null) return '';
return String(str).replace(/\&([^;]+);/g, function(entity, entityCode){
var match; var match;
if (entityCode in escapeChars) { if (entityCode in escapeChars) {
@ -233,31 +272,8 @@
}, },
escapeRegExp: function(str){ escapeRegExp: function(str){
// From MooTools core 1.2.4 if (str == null) return '';
return str.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
},
insert: function(str, i, substr){
var arr = _s.chars(str);
arr.splice(~~i, 0, ''+substr);
return arr.join('');
},
include: function(str, needle){
return !!~(''+str).indexOf(needle);
},
join: function() {
var args = slice(arguments);
return args.join(args.shift());
},
lines: function(str) {
return (''+str).split("\n");
},
reverse: function(str){
return _s.chars(str).reverse().join('');
}, },
splice: function(str, i, howmany, substr){ splice: function(str, i, howmany, substr){
@ -266,31 +282,62 @@
return arr.join(''); return arr.join('');
}, },
insert: function(str, i, substr){
return _s.splice(str, i, 0, substr);
},
include: function(str, needle){
if (needle === '') return true;
if (str == null) return false;
return String(str).indexOf(needle) !== -1;
},
join: function() {
var args = slice.call(arguments),
separator = args.shift();
if (separator == null) separator = '';
return args.join(separator);
},
lines: function(str) {
if (str == null) return [];
return String(str).split("\n");
},
reverse: function(str){
return _s.chars(str).reverse().join('');
},
startsWith: function(str, starts){ startsWith: function(str, starts){
str += ''; starts += ''; if (starts === '') return true;
return str.length >= starts.length && str.substring(0, starts.length) === starts; if (str == null || starts == null) return false;
str = String(str); starts = String(starts);
return str.length >= starts.length && str.slice(0, starts.length) === starts;
}, },
endsWith: function(str, ends){ endsWith: function(str, ends){
str += ''; ends += ''; if (ends === '') return true;
return str.length >= ends.length && str.substring(str.length - ends.length) === ends; if (str == null || ends == null) return false;
str = String(str); ends = String(ends);
return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
}, },
succ: function(str){ succ: function(str){
str += ''; if (str == null) return '';
var arr = _s.chars(str); str = String(str);
arr.splice(str.length-1, 1, String.fromCharCode(str.charCodeAt(str.length-1) + 1)); return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length-1) + 1);
return arr.join('');
}, },
titleize: function(str){ titleize: function(str){
return (''+str).replace(/\b./g, function(ch){ return ch.toUpperCase(); }); if (str == null) return '';
str = String(str).toLowerCase();
return str.replace(/(?:^|\s|-)\S/g, function(c){ return c.toUpperCase(); });
}, },
camelize: function(str){ camelize: function(str){
return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, chr){ return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, c){ return c ? c.toUpperCase() : ""; });
return chr && chr.toUpperCase();
});
}, },
underscored: function(str){ underscored: function(str){
@ -298,45 +345,41 @@
}, },
dasherize: function(str){ dasherize: function(str){
return _s.trim(str).replace(/[_\s]+/g, '-').replace(/([A-Z])/g, '-$1').replace(/-+/g, '-').toLowerCase(); return _s.trim(str).replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
}, },
classify: function(str){ classify: function(str){
str += ''; return _s.titleize(String(str).replace(/[\W_]/g, ' ')).replace(/\s/g, '');
return _s.titleize(str.replace(/_/g, ' ')).replace(/\s/g, '')
}, },
humanize: function(str){ humanize: function(str){
return _s.capitalize(this.underscored(str).replace(/_id$/,'').replace(/_/g, ' ')); return _s.capitalize(_s.underscored(str).replace(/_id$/,'').replace(/_/g, ' '));
}, },
trim: function(str, characters){ trim: function(str, characters){
str += ''; if (str == null) return '';
if (!characters && nativeTrim) { return nativeTrim.call(str); } if (!characters && nativeTrim) return nativeTrim.call(str);
characters = defaultToWhiteSpace(characters); characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), ''); return String(str).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
}, },
ltrim: function(str, characters){ ltrim: function(str, characters){
str+=''; if (str == null) return '';
if (!characters && nativeTrimLeft) { if (!characters && nativeTrimLeft) return nativeTrimLeft.call(str);
return nativeTrimLeft.call(str);
}
characters = defaultToWhiteSpace(characters); characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp('^' + characters + '+'), ''); return String(str).replace(new RegExp('^' + characters + '+'), '');
}, },
rtrim: function(str, characters){ rtrim: function(str, characters){
str+=''; if (str == null) return '';
if (!characters && nativeTrimRight) { if (!characters && nativeTrimRight) return nativeTrimRight.call(str);
return nativeTrimRight.call(str);
}
characters = defaultToWhiteSpace(characters); characters = defaultToWhiteSpace(characters);
return str.replace(new RegExp(characters + '+$'), ''); return String(str).replace(new RegExp(characters + '+$'), '');
}, },
truncate: function(str, length, truncateStr){ truncate: function(str, length, truncateStr){
str += ''; truncateStr = truncateStr || '...'; if (str == null) return '';
str = String(str); truncateStr = truncateStr || '...';
length = ~~length; length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str; return str.length > length ? str.slice(0, length) + truncateStr : str;
}, },
@ -344,57 +387,53 @@
/** /**
* _s.prune: a more elegant version of truncate * _s.prune: a more elegant version of truncate
* prune extra chars, never leaving a half-chopped word. * prune extra chars, never leaving a half-chopped word.
* @author github.com/sergiokas * @author github.com/rwz
*/ */
prune: function(str, length, pruneStr){ prune: function(str, length, pruneStr){
str += ''; length = ~~length; if (str == null) return '';
pruneStr = pruneStr != null ? ''+pruneStr : '...';
var pruned, borderChar, template = str.replace(/\W/g, function(ch){ str = String(str); length = ~~length;
return (ch.toUpperCase() !== ch.toLowerCase()) ? 'A' : ' '; pruneStr = pruneStr != null ? String(pruneStr) : '...';
});
borderChar = template.charAt(length); if (str.length <= length) return str;
pruned = template.slice(0, length); var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
// Check if we're in the middle of a word if (template.slice(template.length-2).match(/\w\w/))
if (borderChar && borderChar.match(/\S/)) template = template.replace(/\s*\S+$/, '');
pruned = pruned.replace(/\s\S+$/, ''); else
template = _s.rtrim(template.slice(0, template.length-1));
pruned = _s.rtrim(pruned); return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
return (pruned+pruneStr).length > str.length ? str : str.substring(0, pruned.length)+pruneStr;
}, },
words: function(str, delimiter) { words: function(str, delimiter) {
if (_s.isBlank(str)) return [];
return _s.trim(str, delimiter).split(delimiter || /\s+/); return _s.trim(str, delimiter).split(delimiter || /\s+/);
}, },
pad: function(str, length, padStr, type) { pad: function(str, length, padStr, type) {
str += ''; str = str == null ? '' : String(str);
length = ~~length;
var padlen = 0; var padlen = 0;
length = ~~length; if (!padStr)
if (!padStr) {
padStr = ' '; padStr = ' ';
} else if (padStr.length > 1) { else if (padStr.length > 1)
padStr = padStr.charAt(0); padStr = padStr.charAt(0);
}
switch(type) { switch(type) {
case 'right': case 'right':
padlen = (length - str.length); padlen = length - str.length;
return str + strRepeat(padStr, padlen); return str + strRepeat(padStr, padlen);
case 'both': case 'both':
padlen = (length - str.length); padlen = length - str.length;
return strRepeat(padStr, Math.ceil(padlen/2)) + return strRepeat(padStr, Math.ceil(padlen/2)) + str
str + + strRepeat(padStr, Math.floor(padlen/2));
strRepeat(padStr, Math.floor(padlen/2));
default: // 'left' default: // 'left'
padlen = (length - str.length); padlen = length - str.length;
return strRepeat(padStr, padlen) + str; return strRepeat(padStr, padlen) + str;
} }
}, },
@ -419,76 +458,185 @@
}, },
toNumber: function(str, decimals) { toNumber: function(str, decimals) {
str += ''; if (!str) return 0;
var num = parseNumber(parseNumber(str).toFixed(~~decimals)); str = _s.trim(str);
return num === 0 && !str.match(/^0+$/) ? Number.NaN : num; if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
return parseNumber(parseNumber(str).toFixed(~~decimals));
},
numberFormat : function(number, dec, dsep, tsep) {
if (isNaN(number) || number == null) return '';
number = number.toFixed(~~dec);
tsep = typeof tsep == 'string' ? tsep : ',';
var parts = number.split('.'), fnums = parts[0],
decimals = parts[1] ? (dsep || '.') + parts[1] : '';
return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
}, },
strRight: function(str, sep){ strRight: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep; if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.indexOf(sep); var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str; return ~pos ? str.slice(pos+sep.length, str.length) : str;
}, },
strRightBack: function(str, sep){ strRightBack: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep; if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.lastIndexOf(sep); var pos = !sep ? -1 : str.lastIndexOf(sep);
return ~pos ? str.slice(pos+sep.length, str.length) : str; return ~pos ? str.slice(pos+sep.length, str.length) : str;
}, },
strLeft: function(str, sep){ strLeft: function(str, sep){
str += ''; sep = sep != null ? ''+sep : sep; if (str == null) return '';
str = String(str); sep = sep != null ? String(sep) : sep;
var pos = !sep ? -1 : str.indexOf(sep); var pos = !sep ? -1 : str.indexOf(sep);
return ~pos ? str.slice(0, pos) : str; return ~pos ? str.slice(0, pos) : str;
}, },
strLeftBack: function(str, sep){ strLeftBack: function(str, sep){
if (str == null) return '';
str += ''; sep = sep != null ? ''+sep : sep; str += ''; sep = sep != null ? ''+sep : sep;
var pos = str.lastIndexOf(sep); var pos = str.lastIndexOf(sep);
return ~pos ? str.slice(0, pos) : str; return ~pos ? str.slice(0, pos) : str;
}, },
toSentence: function(array, separator, lastSeparator) { toSentence: function(array, separator, lastSeparator, serial) {
separator || (separator = ', '); separator = separator || ', ';
lastSeparator || (lastSeparator = ' and '); lastSeparator = lastSeparator || ' and ';
var length = array.length, str = ''; var a = array.slice(), lastMember = a.pop();
for (var i = 0; i < length; i++) { if (array.length > 2 && serial) lastSeparator = _s.rtrim(separator) + lastSeparator;
str += array[i];
if (i === (length - 2)) { str += lastSeparator; }
else if (i < (length - 1)) { str += separator; }
}
return str; return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
},
toSentenceSerial: function() {
var args = slice.call(arguments);
args[3] = true;
return _s.toSentence.apply(_s, args);
}, },
slugify: function(str) { slugify: function(str) {
var from = "ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź", if (str == null) return '';
to = "aaaaaaceeeeeiiiilnooooouuuunczz",
var from = "ąàáäâãåæăćęèéëêìíïîłńòóöôõøśșțùúüûñçżź",
to = "aaaaaaaaaceeeeeiiiilnoooooosstuuuunczz",
regex = new RegExp(defaultToWhiteSpace(from), 'g'); regex = new RegExp(defaultToWhiteSpace(from), 'g');
str = (''+str).toLowerCase(); str = String(str).toLowerCase().replace(regex, function(c){
var index = from.indexOf(c);
str = str.replace(regex, function(ch){
var index = from.indexOf(ch);
return to.charAt(index) || '-'; return to.charAt(index) || '-';
}); });
return _s.trim(str.replace(/[^\w\s-]/g, '').replace(/[-\s]+/g, '-'), '-'); return _s.dasherize(str.replace(/[^\w\s-]/g, ''));
},
surround: function(str, wrapper) {
return [wrapper, str, wrapper].join('');
},
quote: function(str, quoteChar) {
return _s.surround(str, quoteChar || '"');
},
unquote: function(str, quoteChar) {
quoteChar = quoteChar || '"';
if (str[0] === quoteChar && str[str.length-1] === quoteChar)
return str.slice(1,str.length-1);
else return str;
}, },
exports: function() { exports: function() {
var result = {}; var result = {};
for (var prop in this) { for (var prop in this) {
if (!this.hasOwnProperty(prop) || ~_s.words('include contains reverse').indexOf(prop)) continue; if (!this.hasOwnProperty(prop) || prop.match(/^(?:include|contains|reverse)$/)) continue;
result[prop] = this[prop]; result[prop] = this[prop];
} }
return result; return result;
}, },
repeat: strRepeat repeat: function(str, qty, separator){
if (str == null) return '';
qty = ~~qty;
// using faster implementation if separator is not needed;
if (separator == null) return strRepeat(String(str), qty);
// this one is about 300x slower in Google Chrome
for (var repeat = []; qty > 0; repeat[--qty] = str) {}
return repeat.join(separator);
},
naturalCmp: function(str1, str2){
if (str1 == str2) return 0;
if (!str1) return -1;
if (!str2) return 1;
var cmpRegex = /(\.\d+)|(\d+)|(\D+)/g,
tokens1 = String(str1).toLowerCase().match(cmpRegex),
tokens2 = String(str2).toLowerCase().match(cmpRegex),
count = Math.min(tokens1.length, tokens2.length);
for(var i = 0; i < count; i++) {
var a = tokens1[i], b = tokens2[i];
if (a !== b){
var num1 = parseInt(a, 10);
if (!isNaN(num1)){
var num2 = parseInt(b, 10);
if (!isNaN(num2) && num1 - num2)
return num1 - num2;
}
return a < b ? -1 : 1;
}
}
if (tokens1.length === tokens2.length)
return tokens1.length - tokens2.length;
return str1 < str2 ? -1 : 1;
},
levenshtein: function(str1, str2) {
if (str1 == null && str2 == null) return 0;
if (str1 == null) return String(str2).length;
if (str2 == null) return String(str1).length;
str1 = String(str1); str2 = String(str2);
var current = [], prev, value;
for (var i = 0; i <= str2.length; i++)
for (var j = 0; j <= str1.length; j++) {
if (i && j)
if (str1.charAt(j - 1) === str2.charAt(i - 1))
value = prev;
else
value = Math.min(current[j], current[j - 1], prev) + 1;
else
value = i + j;
prev = current[j];
current[j] = value;
}
return current.pop();
},
toBoolean: function(str, trueValues, falseValues) {
if (typeof str === "number") str = "" + str;
if (typeof str !== "string") return !!str;
str = _s.trim(str);
if (boolMatch(str, trueValues || ["true", "1"])) return true;
if (boolMatch(str, falseValues || ["false", "0"])) return false;
}
}; };
// Aliases // Aliases
@ -500,26 +648,26 @@
_s.rjust = _s.lpad; _s.rjust = _s.lpad;
_s.ljust = _s.rpad; _s.ljust = _s.rpad;
_s.contains = _s.include; _s.contains = _s.include;
_s.q = _s.quote;
_s.toBool = _s.toBoolean;
// Exporting
// CommonJS module is defined // CommonJS module is defined
if (typeof exports !== 'undefined') { if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) { if (typeof module !== 'undefined' && module.exports)
// Export module
module.exports = _s; module.exports = _s;
}
exports._s = _s; exports._s = _s;
}
} else if (typeof define === 'function' && define.amd) {
// Register as a named module with AMD. // Register as a named module with AMD.
define('underscore.string', function() { if (typeof define === 'function' && define.amd)
return _s; define('underscore.string', [], function(){ return _s; });
});
} else {
// Integrate with Underscore.js if defined // Integrate with Underscore.js if defined
// or create our own underscore object. // or create our own underscore object.
root._ = root._ || {}; root._ = root._ || {};
root._.string = root._.str = _s; root._.string = root._.str = _s;
} }(this, String);
}(this || window));

File diff suppressed because it is too large Load Diff