Advertisement
stuppid_bot

Untitled

Sep 5th, 2014
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // o.hasOwnProperty можно переопределить
  2. function hasOwn(o, p) {
  3.     return Object.prototype.hasOwnProperty.call(o, p);
  4. }
  5.  
  6. function is(t, o) {
  7.     return Object.prototype.toString.call(o) == '[object ' + t + ']';
  8. }
  9.  
  10. function isObject(o) {
  11.     return is('Object', o);
  12. }
  13.  
  14. // NOTE: undefined, NaN, Infinity можно переопределить
  15. // typeof 'foo' == 'string', but typeof String('foo') == 'object'
  16. // Примитивы, которые получают тип 'object' при создании через конструктор
  17. function isNumber(o) {
  18.     return is('Number', o);
  19. }
  20.  
  21. function isString(o) {
  22.     return is('String', o);
  23. }
  24.  
  25. function isBoolean(o) {
  26.     return is('Boolean');
  27. }
  28.  
  29. // встроенная функция всяко быстрее
  30. function isArray(o) {
  31.     return Array.isArray(o);
  32. }
  33.  
  34. function isObjectOrArray(o) {
  35.     return isObject(o) || isArray(o);
  36. }
  37.  
  38. function buildQuery(params) {
  39.     if (!isObjectOrArray(params)) {
  40.         throw new TypeError('must be object or array');
  41.     }
  42.     return build(params);
  43.     function build(data, prefix, undef) {
  44.         var r = []
  45.             , k
  46.             , v;
  47.         for (var k in data) {
  48.             if (hasOwn(data, k)) {
  49.                 v = data[k];
  50.                 k = encodeURIComponent(k);
  51.                 k = prefix === undef ? k : prefix + '[' + k + ']';
  52.                 r.push(isObjectOrArray(v) ? build(v, k) : k + '=' + encodeURIComponent(v))
  53.             }
  54.         }
  55.         return r.join('&');
  56.     }
  57. }
  58.  
  59. buildQuery({
  60.     q: 'тест',
  61.     __ts: new Date().getTime(),
  62. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement