Может кто какие замечания сделает или поможет дописать format
/** * © All rights reserved x9a.ru, 2013 */ String.prototype.repeat = function(n) { var out = ''; while(0 < n--) { out += this; } return out; }; String.prototype.pad = function(requiredLength, paddingStr, paddingType) { paddingType = paddingType ? paddingType.toLowerCase() : ''; paddingStr = paddingStr || ' '; var n = requiredLength - this.length; if (n) { paddingStr = paddingStr.repeat( Math.ceil(n / paddingStr.length) ).substr(0, n); if (paddingType == 'both') { n /= 2; return paddingStr.substr( 0, Math.ceil(n) ) + this + paddingStr.substr( 0, Math.floor(n) ); } if (paddingType == 'left') { return paddingStr + this; } return this + paddingStr; } return this; }; // синтаксис аналогичен printf // 'Привет, %s!'.format('мир') -> "Привет, мир!" // '%.1s.%.1s. %s'.format('Иван', 'Иванович', 'Иванов') -> "И.И. Иванов" String.prototype.format = function() { var i = 0, args = arguments; return this.replace(/%(?:%|(?:(|[+-]+)(|0|'.+?)([1-9]\d*)?(?:\.([1-9]\d*))?)?(s|d|f))/g, function(match, sign, padding, width, precision, type) { if (match == '%%') { return '%'; } var val = args[i++]; if (type == 'd') { val = Math.round(val); } else if (type == 'f') { val = val.toFixed(precision ? precision : 6); } if (/\+/.test(sign) && val > 0) { val = '+' + val; } if (type != 'f' && precision) { val = val.substr(0, precision); } if (width) { val = (val += '').pad(width, padding == '' ? ' ' : padding[0] == "'" ? padding.substr(1) : padding, /-/.test(sign) ? 'right' : 'left'); } return val; }); }; // this.name = 'Вася'; // console.log( 'Привет, ${name}!'.template(this) ); // "Привет, Вася!" String.prototype.template = function(context) { return this.replace(/\$\{(.*?)\}/g, function(match, name) { return context[name]; }); }; Array.prototype.shuffle = function() { var i = 0, j = this.length, n, swap; while (i < j) { n = Math.floor(Math.random() * j); swap = this[n]; this[n] = this[i]; this[i++] = swap; } }; // [1, 2, 3, 4, 5].rand() -> 4 Array.prototype.rand = function() { return this[Math.floor(Math.random() * this.length)]; }; // ещё до хера кода |
querystring = { parse: function(str, sep, eq) { eq = eq || '='; var obj = {}; if (str) { var parts = str.split(sep || '&'), i = 0, j = parts.length; while (i < j) { var temp = parts[i++].split(eq); if (temp[0] !== '') { obj[temp[0]] = temp[1] === undefined ? '' : decodeURIComponent(temp[1]); } } } return obj; }, stringify: function(obj, sep, eq) { sep = sep || '&'; eq = eq || '='; var out = []; for (var i in obj) { out.push( i + (obj[i] !== '' ? eq + encodeURIComponent(obj[i]) : '') ); } return out.join(sep); } }; // ... // ajax.post('handler.php', {a: 'тест'}, {done: function(data) { console.log(data); }}); ajax = new (function(){ /* options = {dataType: 'arraybuffer' || 'blob' || 'document' || 'json' || 'text', done: function(data) {...}, fail: function(code, text) {...} } */ this.request = function(method, url, params, options) { options = options || {}; var req = new XMLHttpRequest; req.responseType = options.dataType || ''; if (options.done || options.fail) { req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status >= 200 && req.status < 300) { if (options.done) { options.done(req.response); } return; } if (options.fail) { options.fail(req.status, req.statusText); } } } } req.open(method, url); if (method.toLowerCase() == 'post') { req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); params = querystring.stringify(params); } req.send(params); }; this.get = function(url, options) { this.request('GET', url, null, options); }; this.post = function(url, params, options) { this.request('POST', url, params, options); }; })(); |
String.prototype.repeat = function(n) { return new Array(n+1).join(this); }; Обычно так делают, для длинных строк вроде как выигрыш идёт. Хотя сейчас везде работу со строками хорошо оптимизировали и уж надо тестить снова. |
Да и строчек кода меньше. спс
|
Кстати я сегодня подумал что javascript не хватает перегрузки операторов, например тот же '%' перегрузить можно бы было и использовать для форматирования строки как в python, типа такого:
console.log('Привет, %s!' % ['мир']); |
http://x9a.ru/js/common.js эти функции используются мной в приложении я для вконтакте пишу сейчас
|
Цитата:
А еслиб в нормальном js существовала перегрузка операторов, вы вообще представляете какой ад бы творился на проектах, которые пишутся не в одиночку?) |
Как в JavaDoc такое оформить?
/* Свойства обьекта options: dataType 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' тип возвращаемых данных enctype аналогично одноименному атрибуту form done function(response) { ... } функция-обработчик, которая вызывается при успешном выполнении запроса fail function(code, text) { ... } функция-обработчик, которая вызывается при возвращении сервером ошибки beforeSend function(request) { ... } функция обработчик, которая вызывается до отправления данных, единственным принимаемым аргументом является объект XMLHttpRequest */ ajax = new (function(){ this.exec = function(method, url, data, options) { options = options || {}; var req = new XMLHttpRequest; if (options.done || options.fail) { req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status >= 200 && req.status < 300) { if (options.done) { options.done(req.response); } return; } if (options.fail) { options.fail(req.status, req.statusText); } } } } req.open(method, url); req.responseType = options.dataType || 'text'; if (options.enctype) { req.setRequestHeader('Content-Type', options.enctype); } if (options.beforeSend) { options.beforeSend(req); } req.send(data); }; this.get = function(url, options) { this.exec('GET', url, null, options); }; this.post = function(url, data, options) { (options = options || {}).enctype = options.enctype === undefined ? 'application/x-www-form-urlencoded' : options.enctype; if (options.enctype.toLowerCase() == 'application/x-www-form-urlencoded') { data = querystring.stringify(data); } this.exec('POST', url, data, options); } })(); |
String.prototype.escape = function() { var specialChars = {'<': 'lt', '>': 'gt', '&': 'amp'}; return this.replace(/[<>&]/g, function(match) { return '&' + specialChars[match] + ';'; }); } |
Можно и так
function () { var specialChars = {'<': 'lt', '>': 'gt', '&': 'amp'}; return this.replace(new RegExp('[' + Object.keys(specialChars).join('') + ']', 'g'), function(match) { return '&' + specialChars[match] + ';'; }); } |
Часовой пояс GMT +3, время: 23:09. |