JavaScript is_float function

A JavaScript equivalent of PHP’s is_float

function is_float (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Paulo Freitas
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // +   improved by: WebDevHobo (http://webdevhobo.blogspot.com/)
  // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
  // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
  // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
  // *     example 1: is_float(186.31);
  // *     returns 1: true

  return +mixed_var === mixed_var && (!isFinite(mixed_var) || !!(mixed_var % 1));
}

Example 1
is_float(186.31);

Should return
true

Добавлено: 27 Июля 2018 22:32:20 Добавил: Андрей Ковальчук

JavaScript intval function

A JavaScript equivalent of PHP’s intval

function intval (mixed_var, base) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: stensi
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   input by: Matteo
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Rafał Kukawski (http://kukawski.pl)
  // *     example 1: intval('Kevin van Zonneveld');
  // *     returns 1: 0
  // *     example 2: intval(4.2);
  // *     returns 2: 4
  // *     example 3: intval(42, 8);
  // *     returns 3: 42
  // *     example 4: intval('09');
  // *     returns 4: 9
  // *     example 5: intval('1e', 16);
  // *     returns 5: 30
  var tmp;

  var type = typeof mixed_var;

  if (type === 'boolean') {
    return +mixed_var;
  } else if (type === 'string') {
    tmp = parseInt(mixed_var, base || 10);
    return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
  } else if (type === 'number' && isFinite(mixed_var)) {
    return mixed_var | 0;
  } else {
    return 0;
  }
}

Example 1
intval('Kevin van Zonneveld');

Should return
0

Example 2
intval(4.2);

Should return
4

Example 3
intval(42, 8);

Should return
42

Добавлено: 27 Июля 2018 22:31:42 Добавил: Андрей Ковальчук

JavaScript is_double function

A JavaScript equivalent of PHP’s is_double

function is_double (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Paulo Freitas
  //  -   depends on: is_float
  // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
  // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
  // *     example 1: is_double(186.31);
  // *     returns 1: true
  return this.is_float(mixed_var);
}

Example 1
is_double(186.31);

Should return
true

Добавлено: 27 Июля 2018 22:30:40 Добавил: Андрей Ковальчук

JavaScript is_callable function

A JavaScript equivalent of PHP’s is_callable

function is_callable (v, syntax_only, callable_name) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   input by: François
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // %        note 1: The variable callable_name cannot work as a string variable passed by reference as in PHP (since JavaScript does not support passing strings by reference), but instead will take the name of a global variable and set that instead
  // %        note 2: When used on an object, depends on a constructor property being kept on the object prototype
  // *     example 1: is_callable('is_callable');
  // *     returns 1: true
  // *     example 2: is_callable('bogusFunction', true);
  // *     returns 2: true // gives true because does not do strict checking
  // *     example 3: function SomeClass () {}
  // *     example 3: SomeClass.prototype.someMethod = function (){};
  // *     example 3: var testObj = new SomeClass();
  // *     example 3: is_callable([testObj, 'someMethod'], true, 'myVar');
  // *     example 3: myVar;
  // *     returns 3: 'SomeClass::someMethod'
  // *     example 4: is_callable(function () {});
  // *     returns 4: true

  var name = '',
    obj = {},
    method = '';
  var getFuncName = function (fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
    if (!name) {
      return '(Anonymous)';
    }
    return name[1];
  };
  if (typeof v === 'string') {
    obj = this.window;
    method = v;
    name = v;
  }
  else if (typeof v === 'function') {
    return true;
  }
  else if (Object.prototype.toString.call(v) === '[object Array]' &&
        v.length === 2 && typeof v[0] === 'object' && typeof v[1] === 'string') {
    obj = v[0];
    method = v[1];
    name = (obj.constructor && getFuncName(obj.constructor)) + '::' + method;
  }
  else {
    return false;
  }
  if (syntax_only || typeof obj[method] === 'function') {
    if (callable_name) {
      this.window[callable_name] = name;
    }
    return true;
  }
  return false;
}

Example 1
is_callable('is_callable');

Should return
true

Example 2
is_callable('bogusFunction', true);

Should return
true // gives true because does not do strict checking

Example 3
function SomeClass () {}
SomeClass.prototype.someMethod = function (){};
var testObj = new SomeClass();
is_callable([testObj, 'someMethod'], true, 'myVar');
myVar;

Should return
'SomeClass::someMethod'

Добавлено: 27 Июля 2018 22:29:58 Добавил: Андрей Ковальчук

JavaScript is_buffer function

A JavaScript equivalent of PHP’s is_buffer

function is_buffer (vr) {
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: is_buffer('This could be binary or a regular string as far as JavaScript knows...');
  // *     returns 1: true
  return typeof vr === 'string';
}

Example 1
is_buffer('This could be binary or a regular string as far as JavaScript knows...');

Should return
true

Добавлено: 27 Июля 2018 22:28:43 Добавил: Андрей Ковальчук

JavaScript is_bool function

A JavaScript equivalent of PHP’s is_bool

function is_bool (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Onno Marsman
  // +   improved by: CoursesWeb (http://www.coursesweb.net/)
  // *     example 1: is_bool(false);
  // *     returns 1: true
  // *     example 2: is_bool(0);
  // *     returns 2: false
  return (mixed_var === true || mixed_var === false); // Faster (in FF) than type checking
}

Example 1
is_bool(false);

Should return
true

Example 2
is_bool(0);

Should return
false

Добавлено: 27 Июля 2018 22:28:06 Добавил: Андрей Ковальчук

JavaScript is_binary function

A JavaScript equivalent of PHP’s is_binary

function is_binary (vr) {
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: is_binary('This could be binary as far as JavaScript knows...');
  // *     returns 1: true
  return typeof vr === 'string'; // If it is a string of any kind, it could be binary
}

Example 1
is_binary('This could be binary as far as JavaScript knows...');

Should return
true

Добавлено: 27 Июля 2018 22:27:11 Добавил: Андрей Ковальчук

JavaScript is_array function

A JavaScript equivalent of PHP’s is_array

function is_array (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Legaev Andrey
  // +   bugfixed by: Cord
  // +   bugfixed by: Manish
  // +   improved by: Onno Marsman
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // +   improved by: Nathan Sepulveda
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
  // %        note 1: return true in this function (except for objects which inherit properties, being thus used as objects),
  // %        note 1: unless you do ini_set('phpjs.objectsAsArrays', 0), in which case only genuine JavaScript arrays
  // %        note 1: will return true
  // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
  // *     returns 1: true
  // *     example 2: is_array('Kevin van Zonneveld');
  // *     returns 2: false
  // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
  // *     returns 3: true
  // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
  // *     returns 4: false
  var ini,
    _getFuncName = function (fn) {
      var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
      if (!name) {
        return '(Anonymous)';
      }
      return name[1];
    },
    _isArray = function (mixed_var) {
      // return Object.prototype.toString.call(mixed_var) === '[object Array]';
      // The above works, but let's do the even more stringent approach: (since Object.prototype.toString could be overridden)
      // Null, Not an object, no length property so couldn't be an Array (or String)
      if (!mixed_var || typeof mixed_var !== 'object' || typeof mixed_var.length !== 'number') {
        return false;
      }
      var len = mixed_var.length;
      mixed_var[mixed_var.length] = 'bogus';
      // The only way I can think of to get around this (or where there would be trouble) would be to have an object defined
      // with a custom "length" getter which changed behavior on each call (or a setter to mess up the following below) or a custom
      // setter for numeric properties, but even that would need to listen for specific indexes; but there should be no false negatives
      // and such a false positive would need to rely on later JavaScript innovations like __defineSetter__
      if (len !== mixed_var.length) { // We know it's an array since length auto-changed with the addition of a
      // numeric property at its length end, so safely get rid of our bogus element
        mixed_var.length -= 1;
        return true;
      }
      // Get rid of the property we added onto a non-array object; only possible
      // side-effect is if the user adds back the property later, it will iterate
      // this property in the older order placement in IE (an order which should not
      // be depended on anyways)
      delete mixed_var[mixed_var.length];
      return false;
    };

  if (!mixed_var || typeof mixed_var !== 'object') {
    return false;
  }

  // BEGIN REDUNDANT
  this.php_js = this.php_js || {};
  this.php_js.ini = this.php_js.ini || {};
  // END REDUNDANT

  ini = this.php_js.ini['phpjs.objectsAsArrays'];

  return _isArray(mixed_var) ||
    // Allow returning true unless user has called
    // ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays
    ((!ini || ( // if it's not set to 0 and it's not 'off', check for objects as arrays
    (parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value.toLowerCase() !== 'off')))
    ) && (
    Object.prototype.toString.call(mixed_var) === '[object Object]' && _getFuncName(mixed_var.constructor) === 'Object' // Most likely a literal and intended as assoc. array
    ));
}

Example 1
is_array(['Kevin', 'van', 'Zonneveld']);

Should return
true

Example 2
is_array('Kevin van Zonneveld');

Should return
false

Example 3
is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});

Should return
true

Добавлено: 27 Июля 2018 22:25:43 Добавил: Андрей Ковальчук

JavaScript import_request_variables function

A JavaScript equivalent of PHP’s import_request_variables

function import_request_variables (types, prefix) {
  // http://kevin.vanzonneveld.net
  // +      original by: Jalal Berrami
  // + reimplemented by: Brett Zamir (http://brett-zamir.me)
  // + improved by: Brett Zamir (http://brett-zamir.me)
  // %          note 1: IMPORTANT: You must sanitize user variables passed in via URL in JavaScript as in PHP,
  // %          note 1: especially if you want to use any of these variables in an eval()-like function (not recommended)!
  // *        example 1: document.cookie = 'snack=yummy';
  // *        example 1: import_request_variables('gc', 'pr_');
  // *        results 1: pr_snack === 'yummy'
  // *        example 2: ini_set('phpjs.getVarsObj', $_GET = {}); // Only works in PHP.JS, not PHP (!), though by using ini_set(), it does work as though PHP.JS were an extension to PHP
  // *        example 2: import_request_variables('g'); // Allows $_GET['myRequestVar'] access to query string variables

  var i = 0,
    current = '',
    url = '',
    vars = '',
    arrayBracketPos = -1,
    arrName = '',
    win = this.window,
    requestObj = this.window,
    getObj = false,
    cookieObj = false;
  prefix = prefix || '';

  var that = this;
  var _ini_get = function (ini) {
    if (that.php_js && that.php_js.ini && that.php_js.ini[ini] && that.php_js.ini[ini].local_value) { // Allow designated object to be used instead of window
      return that.php_js.ini[ini].local_value;
    }
    return false;
  };

  requestObj = _ini_get('phpjs.requestVarsObj') || requestObj;
  if (/g/i.test(types)) { // GET
    getObj = _ini_get('phpjs.getVarsObj') || getObj;
    for (i = 0, url = win.location.href, vars = url.substring(url.lastIndexOf('?') + 1, url.length).split('&'); i < vars.length; i++) {
      current = vars[i].split('=');
      current[1] = decodeURIComponent(current[1]);
      arrayBracketPos = current[0].indexOf('[');
      if (arrayBracketPos !== -1) {
        arrName = current[0].substring(0, arrayBracketPos);
        arrName = decodeURIComponent(arrName);
        if (!requestObj[prefix + arrName]) {
          requestObj[prefix + arrName] = [];
        }
        requestObj[prefix + arrName].push(current[1] || null);
        if (getObj) {
          if (!getObj[prefix + arrName]) {
            getObj[prefix + arrName] = [];
          }
          getObj[prefix + arrName].push(current[1] || null);
        }
      } else {
        current[0] = decodeURIComponent(current[0]);
        requestObj[prefix + current[0]] = current[1] || null;
        if (getObj) {
          getObj[prefix + current[0]] = current[1] || null;
        }
      }
    }
  }
  if (/c/i.test(types)) { // COOKIE
    cookieObj = _ini_get('phpjs.cookieVarsObj') || cookieObj;
    for (i = 0, vars = win.document.cookie.split("&"); i < vars.length; i++) {
      current = vars[i].split("=");
      requestObj[prefix + current[0]] = current[1].split(";")[0] || null;
      if (cookieObj) {
        cookieObj[prefix + current[0]] = current[1].split(";")[0] || null;
      }
    }
  }
}

Добавлено: 27 Июля 2018 22:24:34 Добавил: Андрей Ковальчук

JavaScript gettype function

A JavaScript equivalent of PHP’s gettype

function gettype (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Paulo Freitas
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Douglas Crockford (http://javascript.crockford.com)
  // +   input by: KELAN
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: is_float
  // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
  // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
  // *     example 1: gettype(1);
  // *     returns 1: 'integer'
  // *     example 2: gettype(undefined);
  // *     returns 2: 'undefined'
  // *     example 3: gettype({0: 'Kevin van Zonneveld'});
  // *     returns 3: 'array'
  // *     example 4: gettype('foo');
  // *     returns 4: 'string'
  // *     example 5: gettype({0: function () {return false;}});
  // *     returns 5: 'array'
  var s = typeof mixed_var,
    name;
  var getFuncName = function (fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
    if (!name) {
      return '(Anonymous)';
    }
    return name[1];
  };
  if (s === 'object') {
    if (mixed_var !== null) { // From: http://javascript.crockford.com/remedial.html
      if (typeof mixed_var.length === 'number' && !(mixed_var.propertyIsEnumerable('length')) && typeof mixed_var.splice === 'function') {
        s = 'array';
      } else if (mixed_var.constructor && getFuncName(mixed_var.constructor)) {
        name = getFuncName(mixed_var.constructor);
        if (name === 'Date') {
          s = 'date'; // not in PHP
        } else if (name === 'RegExp') {
          s = 'regexp'; // not in PHP
        } else if (name === 'PHPJS_Resource') { // Check against our own resource constructor
          s = 'resource';
        }
      }
    } else {
      s = 'null';
    }
  } else if (s === 'number') {
    s = this.is_float(mixed_var) ? 'double' : 'integer';
  }
  return s;
}

Example 1
gettype(1);

Should return
'integer'

Example 2
gettype(undefined);

Should return
'undefined'

Example 3
gettype({0: 'Kevin van Zonneveld'});

Should return
'array'

Добавлено: 27 Июля 2018 22:24:00 Добавил: Андрей Ковальчук

JavaScript get_resource_type function

A JavaScript equivalent of PHP’s get_resource_type

function get_resource_type (handle) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: get_resource_type('a');
  // *     returns 1: false
  var getFuncName = function (fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
    if (!name) {
      return '(Anonymous)';
    }
    return name[1];
  };
  if (!handle || typeof handle !== 'object' || !handle.constructor || getFuncName(handle.constructor) !== 'PHPJS_Resource') {
    return false;
  }

  return handle.get_resource_type();
}

Example 1
get_resource_type('a');

Should return
false

Добавлено: 27 Июля 2018 22:22:53 Добавил: Андрей Ковальчук

JavaScript get_defined_vars function

A JavaScript equivalent of PHP’s get_defined_vars

function get_defined_vars () {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // %        note 1: Test case 1: If get_defined_vars can find itself in the defined vars, it worked :)
  // *     example 1: function test_in_array(array, p_val) {for(var i = 0, l = array.length; i < l; i++) {if(array[i] == p_val) return true;} return false;}
  // *     example 1: funcs = get_defined_vars();
  // *     example 1: found = test_in_array(funcs, 'get_defined_vars');
  // *     results 1: found == true
  var i = '',
    arr = [],
    already = {};

  for (i in this.window) {
    try {
      if (typeof this.window[i] === 'object') {
        for (var j in this.window[i]) {
          if (this.window[j] && !already[j]) {
            already[j] = 1;
            arr.push(j);
          }
        }
      } else if (!already[i]) {
        already[i] = 1;
        arr.push(i);
      }
    } catch (e) { // Problems accessing some properties in FF (e.g., sessionStorage)
      if (!already[i]) {
        already[i] = 1;
        arr.push(i);
      }
    }
  }

  return arr;
}

Добавлено: 27 Июля 2018 22:22:13 Добавил: Андрей Ковальчук

JavaScript empty function

A JavaScript equivalent of PHP’s empty

function empty (mixed_var) {
  // Checks if the argument variable is empty
  // undefined, null, false, number 0, empty string,
  // string "0", objects without properties and empty arrays
  // are considered empty
  //
  // http://kevin.vanzonneveld.net
  // +   original by: Philippe Baumann
  // +      input by: Onno Marsman
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      input by: LH
  // +   improved by: Onno Marsman
  // +   improved by: Francesco
  // +   improved by: Marc Jansen
  // +      input by: Stoyan Kyosev (http://www.svest.org/)
  // +   improved by: Rafal Kukawski
  // *     example 1: empty(null);
  // *     returns 1: true
  // *     example 2: empty(undefined);
  // *     returns 2: true
  // *     example 3: empty([]);
  // *     returns 3: true
  // *     example 4: empty({});
  // *     returns 4: true
  // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
  // *     returns 5: false
  var undef, key, i, len;
  var emptyValues = [undef, null, false, 0, "", "0"];

  for (i = 0, len = emptyValues.length; i < len; i++) {
    if (mixed_var === emptyValues[i]) {
      return true;
    }
  }

  if (typeof mixed_var === "object") {
    for (key in mixed_var) {
      // TODO: should we check for own properties only?
      //if (mixed_var.hasOwnProperty(key)) {
      return false;
      //}
    }
    return true;
  }

  return false;
}

Example 1
empty(null);

Should return
true

Example 2
empty(undefined);

Should return
true

Example 3
empty([]);

Should return
true

Добавлено: 27 Июля 2018 22:21:42 Добавил: Андрей Ковальчук

JavaScript floatval function

A JavaScript equivalent of PHP’s floatval

function floatval (mixed_var) {
  // +   original by: Michael White (http://getsprink.com)
  // %        note 1: The native parseFloat() method of JavaScript returns NaN when it encounters a string before an int or float value.
  // *     example 1: floatval('150.03_page-section');
  // *     returns 1: 150.03
  // *     example 2: floatval('page: 3');
  // *     returns 2: 0
  // *     example 2: floatval('-50 + 8');
  // *     returns 2: -50
  return (parseFloat(mixed_var) || 0);
}

Example 1
floatval('150.03_page-section');

Should return
150.03

Example 2
floatval('page: 3');
floatval('-50 + 8');

Should return
0
-50

Добавлено: 27 Июля 2018 22:20:33 Добавил: Андрей Ковальчук

JavaScript doubleval function

A JavaScript equivalent of PHP’s doubleval

function doubleval (mixed_var) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  //  -   depends on: floatval
  // %        note 1: 1.0 is simplified to 1 before it can be accessed by the function, this makes
  // %        note 1: it different from the PHP implementation. We can't fix this unfortunately.
  // *     example 1: doubleval(186);
  // *     returns 1: 186.00
  return this.floatval(mixed_var);
}

Example 1
doubleval(186);

Should return
186.00

Добавлено: 27 Июля 2018 22:19:38 Добавил: Андрей Ковальчук