diff --git a/functions/_phpjs_shared/_phpjs_shared_bc.js b/functions/_phpjs_shared/_phpjs_shared_bc.js index 74049a69a3..7bd6c10f88 100644 --- a/functions/_phpjs_shared/_phpjs_shared_bc.js +++ b/functions/_phpjs_shared/_phpjs_shared_bc.js @@ -1,4 +1,4 @@ -function _phpjs_shared_bc() { +function _phpjs_shared_bc () { // From: http://phpjs.org/functions // + original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // + improved by: Brett Zamir (http://brett-zamir.me) @@ -59,26 +59,26 @@ function _phpjs_shared_bc() { /** * Basic number structure */ - bc_num : function() { - this.n_sign = null; // sign - this.n_len = null; /* (int) The number of digits before the decimal point. */ - this.n_scale = null; /* (int) The number of digits after the decimal point. */ - //this.n_refs = null; /* (int) The number of pointers to this number. */ - //this.n_text = null; /* ?? Linked list for available list. */ - this.n_value = null; /* array as value, where 1.23 = [1,2,3] */ - this.toString = function() { - var r, tmp; - tmp = this.n_value.join(''); + bc_num : function () { + this.n_sign = null // sign + this.n_len = null /* (int) The number of digits before the decimal point. */ + this.n_scale = null /* (int) The number of digits after the decimal point. */ + // this.n_refs = null; /* (int) The number of pointers to this number. */ + // this.n_text = null; /* ?? Linked list for available list. */ + this.n_value = null /* array as value, where 1.23 = [1,2,3] */ + this.toString = function () { + var r, tmp + tmp = this.n_value.join('') // add minus sign (if applicable) then add the integer part - r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len); + r = ((this.n_sign == libbcmath.PLUS) ? '' : this.n_sign) + tmp.substr(0, this.n_len) // if decimal places, add a . and the decimal part if (this.n_scale > 0) { - r += '.' + tmp.substr(this.n_len, this.n_scale); + r += '.' + tmp.substr(this.n_len, this.n_scale) } - return r; - }; + return r + } }, /** @@ -93,35 +93,35 @@ function _phpjs_shared_bc() { * @param {int} scale_min * @return bc_num */ - bc_add : function(n1, n2, scale_min) { - var sum, cmp_res, res_scale; + bc_add : function (n1, n2, scale_min) { + var sum, cmp_res, res_scale if (n1.n_sign === n2.n_sign) { - sum = libbcmath._bc_do_add(n1, n2, scale_min); - sum.n_sign = n1.n_sign; + sum = libbcmath._bc_do_add(n1, n2, scale_min) + sum.n_sign = n1.n_sign } else { /* subtraction must be done. */ - cmp_res = libbcmath._bc_do_compare(n1, n2, false, false); /* Compare magnitudes. */ + cmp_res = libbcmath._bc_do_compare(n1, n2, false, false) /* Compare magnitudes. */ switch (cmp_res) { case -1: /* n1 is less than n2, subtract n1 from n2. */ - sum = libbcmath._bc_do_sub(n2, n1, scale_min); - sum.n_sign = n2.n_sign; - break; + sum = libbcmath._bc_do_sub(n2, n1, scale_min) + sum.n_sign = n2.n_sign + break case 0: /* They are equal! return zero with the correct scale! */ - res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale)); - sum = libbcmath.bc_new_num(1, res_scale); - libbcmath.memset(sum.n_value, 0, 0, res_scale + 1); - break; + res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale)) + sum = libbcmath.bc_new_num(1, res_scale) + libbcmath.memset(sum.n_value, 0, 0, res_scale + 1) + break case 1: /* n2 is less than n1, subtract n2 from n1. */ - sum = libbcmath._bc_do_sub(n1, n2, scale_min); - sum.n_sign = n1.n_sign; + sum = libbcmath._bc_do_sub(n1, n2, scale_min) + sum.n_sign = n1.n_sign } } - return sum; + return sum }, /** @@ -130,58 +130,58 @@ function _phpjs_shared_bc() { * @param {bc_num} n2 * @return int -1, 0, 1 (n1 < n2, ==, n1 > n2) */ - bc_compare : function(n1, n2) { - return libbcmath._bc_do_compare(n1, n2, true, false); + bc_compare : function (n1, n2) { + return libbcmath._bc_do_compare(n1, n2, true, false) }, - _one_mult : function(num, n_ptr, size, digit, result, r_ptr) { - var carry, value; // int - var nptr, rptr; // int pointers + _one_mult : function (num, n_ptr, size, digit, result, r_ptr) { + var carry, value // int + var nptr, rptr // int pointers if (digit === 0) { - libbcmath.memset(result, 0, 0, size); //memset (result, 0, size); + libbcmath.memset(result, 0, 0, size) // memset (result, 0, size); } else { if (digit == 1) { - libbcmath.memcpy(result, r_ptr, num, n_ptr, size); //memcpy (result, num, size); + libbcmath.memcpy(result, r_ptr, num, n_ptr, size) // memcpy (result, num, size); } else { /* Initialize */ - nptr = n_ptr + size - 1; //nptr = (unsigned char *) (num+size-1); - rptr = r_ptr + size - 1; //rptr = (unsigned char *) (result+size-1); - carry = 0; + nptr = n_ptr + size - 1 // nptr = (unsigned char *) (num+size-1); + rptr = r_ptr + size - 1 // rptr = (unsigned char *) (result+size-1); + carry = 0 while (size-- > 0) { - value = num[nptr--] * digit + carry; //value = *nptr-- * digit + carry; - //result[rptr--] = libbcmath.cint(value % libbcmath.BASE); // @CHECK cint //*rptr-- = value % BASE; - result[rptr--] = value % libbcmath.BASE; // @CHECK cint //*rptr-- = value % BASE; - //carry = libbcmath.cint(value / libbcmath.BASE); // @CHECK cint //carry = value / BASE; - carry = Math.floor(value / libbcmath.BASE); // @CHECK cint //carry = value / BASE; + value = num[nptr--] * digit + carry // value = *nptr-- * digit + carry; + // result[rptr--] = libbcmath.cint(value % libbcmath.BASE); // @CHECK cint //*rptr-- = value % BASE; + result[rptr--] = value % libbcmath.BASE // @CHECK cint //*rptr-- = value % BASE; + // carry = libbcmath.cint(value / libbcmath.BASE); // @CHECK cint //carry = value / BASE; + carry = Math.floor(value / libbcmath.BASE) // @CHECK cint //carry = value / BASE; } if (carry !== 0) { - result[rptr] = carry; + result[rptr] = carry } } } }, - bc_divide : function(n1, n2, scale) { - var quot; // bc_num return - var qval; // bc_num - var num1, num2; // string - var ptr1, ptr2, n2ptr, qptr; // int pointers - var scale1, val; // int - var len1, len2, scale2, qdigits, extra, count; // int - var qdig, qguess, borrow, carry; // int - var mval; // string - var zero; // char - var norm; // int - var ptrs; // return object from one_mul + bc_divide : function (n1, n2, scale) { + var quot // bc_num return + var qval // bc_num + var num1, num2 // string + var ptr1, ptr2, n2ptr, qptr // int pointers + var scale1, val // int + var len1, len2, scale2, qdigits, extra, count // int + var qdig, qguess, borrow, carry // int + var mval // string + var zero // char + var norm // int + var ptrs // return object from one_mul /* Test for divide by zero. (return failure) */ if (libbcmath.bc_is_zero(n2)) { - return -1; + return -1 } /* Test for zero divide by anything (return zero) */ if (libbcmath.bc_is_zero(n1)) { - return libbcmath.bc_new_num(1, scale); + return libbcmath.bc_new_num(1, scale) } /* Test for n1 equals n2 (return 1 as n1 nor n2 are zero) @@ -196,10 +196,10 @@ function _phpjs_shared_bc() { // todo: check where scale > 0 too.. can't see why not (ie bc_is_zero - add bc_is_one function) if (n2.n_scale === 0) { if (n2.n_len === 1 && n2.n_value[0] === 1) { - qval = libbcmath.bc_new_num(n1.n_len, scale); //qval = bc_new_num (n1->n_len, scale); - qval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS); - libbcmath.memset(qval.n_value, n1.n_len, 0, scale); //memset (&qval->n_value[n1->n_len],0,scale); - libbcmath.memcpy(qval.n_value, 0, n1.n_value, 0, n1.n_len + libbcmath.MIN(n1.n_scale, scale)); //memcpy (qval->n_value, n1->n_value, n1->n_len + MIN(n1->n_scale,scale)); + qval = libbcmath.bc_new_num(n1.n_len, scale) // qval = bc_new_num (n1->n_len, scale); + qval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS) + libbcmath.memset(qval.n_value, n1.n_len, 0, scale) // memset (&qval->n_value[n1->n_len],0,scale); + libbcmath.memcpy(qval.n_value, 0, n1.n_value, 0, n1.n_len + libbcmath.MIN(n1.n_scale, scale)) // memcpy (qval->n_value, n1->n_value, n1->n_len + MIN(n1->n_scale,scale)); // can we return here? not in c src, but can't see why-not. // return qval; } @@ -207,172 +207,172 @@ function _phpjs_shared_bc() { /* Set up the divide. Move the decimal point on n1 by n2's scale. Remember, zeros on the end of num2 are wasted effort for dividing. */ - scale2 = n2.n_scale; //scale2 = n2->n_scale; - n2ptr = n2.n_len + scale2 - 1; //n2ptr = (unsigned char *) n2.n_value+n2.n_len+scale2-1; + scale2 = n2.n_scale // scale2 = n2->n_scale; + n2ptr = n2.n_len + scale2 - 1 // n2ptr = (unsigned char *) n2.n_value+n2.n_len+scale2-1; while ((scale2 > 0) && (n2.n_value[n2ptr--] === 0)) { - scale2--; + scale2-- } - len1 = n1.n_len + scale2; - scale1 = n1.n_scale - scale2; + len1 = n1.n_len + scale2 + scale1 = n1.n_scale - scale2 if (scale1 < scale) { - extra = scale - scale1; + extra = scale - scale1 } else { - extra = 0; + extra = 0 } - num1 = libbcmath.safe_emalloc(1, n1.n_len + n1.n_scale, extra + 2); //num1 = (unsigned char *) safe_emalloc (1, n1.n_len+n1.n_scale, extra+2); + num1 = libbcmath.safe_emalloc(1, n1.n_len + n1.n_scale, extra + 2) // num1 = (unsigned char *) safe_emalloc (1, n1.n_len+n1.n_scale, extra+2); if (num1 === null) { - libbcmath.bc_out_of_memory(); + libbcmath.bc_out_of_memory() } - libbcmath.memset(num1, 0, 0, n1.n_len + n1.n_scale + extra + 2); //memset (num1, 0, n1->n_len+n1->n_scale+extra+2); - libbcmath.memcpy(num1, 1, n1.n_value, 0, n1.n_len + n1.n_scale); //memcpy (num1+1, n1.n_value, n1.n_len+n1.n_scale); - len2 = n2.n_len + scale2; // len2 = n2->n_len + scale2; - num2 = libbcmath.safe_emalloc(1, len2, 1); //num2 = (unsigned char *) safe_emalloc (1, len2, 1); + libbcmath.memset(num1, 0, 0, n1.n_len + n1.n_scale + extra + 2) // memset (num1, 0, n1->n_len+n1->n_scale+extra+2); + libbcmath.memcpy(num1, 1, n1.n_value, 0, n1.n_len + n1.n_scale) // memcpy (num1+1, n1.n_value, n1.n_len+n1.n_scale); + len2 = n2.n_len + scale2 // len2 = n2->n_len + scale2; + num2 = libbcmath.safe_emalloc(1, len2, 1) // num2 = (unsigned char *) safe_emalloc (1, len2, 1); if (num2 === null) { - libbcmath.bc_out_of_memory(); + libbcmath.bc_out_of_memory() } - libbcmath.memcpy(num2, 0, n2.n_value, 0, len2); //memcpy (num2, n2.n_value, len2); - num2[len2] = 0; // *(num2+len2) = 0; - n2ptr = 0; //n2ptr = num2; + libbcmath.memcpy(num2, 0, n2.n_value, 0, len2) // memcpy (num2, n2.n_value, len2); + num2[len2] = 0 // *(num2+len2) = 0; + n2ptr = 0 // n2ptr = num2; while (num2[n2ptr] === 0) { // while (*n2ptr == 0) - n2ptr++; - len2--; + n2ptr++ + len2-- } /* Calculate the number of quotient digits. */ if (len2 > len1 + scale) { - qdigits = scale + 1; - zero = true; + qdigits = scale + 1 + zero = true } else { - zero = false; + zero = false if (len2 > len1) { - qdigits = scale + 1; /* One for the zero integer part. */ + qdigits = scale + 1 /* One for the zero integer part. */ } else { - qdigits = len1 - len2 + scale + 1; + qdigits = len1 - len2 + scale + 1 } } /* Allocate and zero the storage for the quotient. */ - qval = libbcmath.bc_new_num(qdigits - scale, scale); //qval = bc_new_num (qdigits-scale,scale); - libbcmath.memset(qval.n_value, 0, 0, qdigits); //memset (qval->n_value, 0, qdigits); + qval = libbcmath.bc_new_num(qdigits - scale, scale) // qval = bc_new_num (qdigits-scale,scale); + libbcmath.memset(qval.n_value, 0, 0, qdigits) // memset (qval->n_value, 0, qdigits); /* Allocate storage for the temporary storage mval. */ - mval = libbcmath.safe_emalloc(1, len2, 1); //mval = (unsigned char *) safe_emalloc (1, len2, 1); + mval = libbcmath.safe_emalloc(1, len2, 1) // mval = (unsigned char *) safe_emalloc (1, len2, 1); if (mval === null) { - libbcmath.bc_out_of_memory(); + libbcmath.bc_out_of_memory() } /* Now for the full divide algorithm. */ if (!zero) { /* Normalize */ - //norm = libbcmath.cint(10 / (libbcmath.cint(n2.n_value[n2ptr]) + 1)); //norm = 10 / ((int)*n2ptr + 1); - norm = Math.floor(10 / (n2.n_value[n2ptr] + 1)); //norm = 10 / ((int)*n2ptr + 1); + // norm = libbcmath.cint(10 / (libbcmath.cint(n2.n_value[n2ptr]) + 1)); //norm = 10 / ((int)*n2ptr + 1); + norm = Math.floor(10 / (n2.n_value[n2ptr] + 1)) // norm = 10 / ((int)*n2ptr + 1); if (norm != 1) { - libbcmath._one_mult(num1, 0, len1 + scale1 + extra + 1, norm, num1, 0); //libbcmath._one_mult(num1, len1+scale1+extra+1, norm, num1); - libbcmath._one_mult(n2.n_value, n2ptr, len2, norm, n2.n_value, n2ptr); //libbcmath._one_mult(n2ptr, len2, norm, n2ptr); + libbcmath._one_mult(num1, 0, len1 + scale1 + extra + 1, norm, num1, 0) // libbcmath._one_mult(num1, len1+scale1+extra+1, norm, num1); + libbcmath._one_mult(n2.n_value, n2ptr, len2, norm, n2.n_value, n2ptr) // libbcmath._one_mult(n2ptr, len2, norm, n2ptr); // @CHECK Is the pointer affected by the call? if so, maybe need to adjust points on return? } /* Initialize divide loop. */ - qdig = 0; + qdig = 0 if (len2 > len1) { - qptr = len2 - len1; //qptr = (unsigned char *) qval.n_value+len2-len1; + qptr = len2 - len1 // qptr = (unsigned char *) qval.n_value+len2-len1; } else { - qptr = 0; //qptr = (unsigned char *) qval.n_value; + qptr = 0 // qptr = (unsigned char *) qval.n_value; } /* Loop */ while (qdig <= len1 + scale - len2) { /* Calculate the quotient digit guess. */ if (n2.n_value[n2ptr] == num1[qdig]) { - qguess = 9; + qguess = 9 } else { - qguess = Math.floor((num1[qdig] * 10 + num1[qdig + 1]) / n2.n_value[n2ptr]); + qguess = Math.floor((num1[qdig] * 10 + num1[qdig + 1]) / n2.n_value[n2ptr]) } /* Test qguess. */ - if (n2.n_value[n2ptr + 1] * qguess > (num1[qdig] * 10 + num1[qdig + 1] - n2.n_value[n2ptr] * qguess) * 10 + num1[qdig + 2]) { //if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2]) { - qguess--; /* And again. */ - if (n2.n_value[n2ptr + 1] * qguess > (num1[qdig] * 10 + num1[qdig + 1] - n2.n_value[n2ptr] * qguess) * 10 + num1[qdig + 2]) { //if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2]) - qguess--; + if (n2.n_value[n2ptr + 1] * qguess > (num1[qdig] * 10 + num1[qdig + 1] - n2.n_value[n2ptr] * qguess) * 10 + num1[qdig + 2]) { // if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2]) { + qguess-- /* And again. */ + if (n2.n_value[n2ptr + 1] * qguess > (num1[qdig] * 10 + num1[qdig + 1] - n2.n_value[n2ptr] * qguess) * 10 + num1[qdig + 2]) { // if (n2ptr[1]*qguess > (num1[qdig]*10 + num1[qdig+1] - *n2ptr*qguess)*10 + num1[qdig+2]) + qguess-- } } /* Multiply and subtract. */ - borrow = 0; + borrow = 0 if (qguess !== 0) { - mval[0] = 0; //*mval = 0; // @CHECK is this to fix ptr2 < 0? - libbcmath._one_mult(n2.n_value, n2ptr, len2, qguess, mval, 1); //_one_mult (n2ptr, len2, qguess, mval+1); // @CHECK - ptr1 = qdig + len2; //(unsigned char *) num1+qdig+len2; - ptr2 = len2; //(unsigned char *) mval+len2; + mval[0] = 0 //* mval = 0; // @CHECK is this to fix ptr2 < 0? + libbcmath._one_mult(n2.n_value, n2ptr, len2, qguess, mval, 1) // _one_mult (n2ptr, len2, qguess, mval+1); // @CHECK + ptr1 = qdig + len2 // (unsigned char *) num1+qdig+len2; + ptr2 = len2 // (unsigned char *) mval+len2; // @CHECK: Does a negative pointer return null? // ptr2 can be < 0 here as ptr1 = len2, thus count < len2+1 will always fail ? for (count = 0; count < len2 + 1; count++) { if (ptr2 < 0) { - //val = libbcmath.cint(num1[ptr1]) - 0 - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; - val = num1[ptr1] - 0 - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; + // val = libbcmath.cint(num1[ptr1]) - 0 - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; + val = num1[ptr1] - 0 - borrow // val = (int) *ptr1 - (int) *ptr2-- - borrow; } else { - //val = libbcmath.cint(num1[ptr1]) - libbcmath.cint(mval[ptr2--]) - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; - val = num1[ptr1] - mval[ptr2--] - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; + // val = libbcmath.cint(num1[ptr1]) - libbcmath.cint(mval[ptr2--]) - borrow; //val = (int) *ptr1 - (int) *ptr2-- - borrow; + val = num1[ptr1] - mval[ptr2--] - borrow // val = (int) *ptr1 - (int) *ptr2-- - borrow; } if (val < 0) { - val += 10; - borrow = 1; + val += 10 + borrow = 1 } else { - borrow = 0; + borrow = 0 } - num1[ptr1--] = val; + num1[ptr1--] = val } } /* Test for negative result. */ if (borrow == 1) { - qguess--; - ptr1 = qdig + len2; //(unsigned char *) num1+qdig+len2; - ptr2 = len2 - 1; //(unsigned char *) n2ptr+len2-1; - carry = 0; + qguess-- + ptr1 = qdig + len2 // (unsigned char *) num1+qdig+len2; + ptr2 = len2 - 1 // (unsigned char *) n2ptr+len2-1; + carry = 0 for (count = 0; count < len2; count++) { if (ptr2 < 0) { - //val = libbcmath.cint(num1[ptr1]) + 0 + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; - val = num1[ptr1] + 0 + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; + // val = libbcmath.cint(num1[ptr1]) + 0 + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; + val = num1[ptr1] + 0 + carry // val = (int) *ptr1 + (int) *ptr2-- + carry; } else { - //val = libbcmath.cint(num1[ptr1]) + libbcmath.cint(n2.n_value[ptr2--]) + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; - val = num1[ptr1] + n2.n_value[ptr2--] + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; + // val = libbcmath.cint(num1[ptr1]) + libbcmath.cint(n2.n_value[ptr2--]) + carry; //val = (int) *ptr1 + (int) *ptr2-- + carry; + val = num1[ptr1] + n2.n_value[ptr2--] + carry // val = (int) *ptr1 + (int) *ptr2-- + carry; } if (val > 9) { - val -= 10; - carry = 1; + val -= 10 + carry = 1 } else { - carry = 0; + carry = 0 } - num1[ptr1--] = val; //*ptr1-- = val; + num1[ptr1--] = val //* ptr1-- = val; } if (carry == 1) { - //num1[ptr1] = libbcmath.cint((num1[ptr1] + 1) % 10); // *ptr1 = (*ptr1 + 1) % 10; // @CHECK - num1[ptr1] = (num1[ptr1] + 1) % 10; // *ptr1 = (*ptr1 + 1) % 10; // @CHECK + // num1[ptr1] = libbcmath.cint((num1[ptr1] + 1) % 10); // *ptr1 = (*ptr1 + 1) % 10; // @CHECK + num1[ptr1] = (num1[ptr1] + 1) % 10 // *ptr1 = (*ptr1 + 1) % 10; // @CHECK } } /* We now know the quotient digit. */ - qval.n_value[qptr++] = qguess; //*qptr++ = qguess; - qdig++; + qval.n_value[qptr++] = qguess //* qptr++ = qguess; + qdig++ } } /* Clean up and return the number. */ - qval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS); + qval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS) if (libbcmath.bc_is_zero(qval)) { - qval.n_sign = libbcmath.PLUS; + qval.n_sign = libbcmath.PLUS } - libbcmath._bc_rm_leading_zeros(qval); + libbcmath._bc_rm_leading_zeros(qval) - return qval; + return qval - //return 0; /* Everything is OK. */ + // return 0; /* Everything is OK. */ }, MUL_BASE_DIGITS : 80, MUL_SMALL_DIGITS : (this.MUL_BASE_DIGITS / 4), - //#define MUL_SMALL_DIGITS mul_base_digits/4 + // #define MUL_SMALL_DIGITS mul_base_digits/4 /* The multiply routine. N2 times N1 is put int PROD with the scale of the result being MIN(N2 scale+N1 scale, MAX (SCALE, N2 scale, N1 scale)). @@ -382,68 +382,68 @@ function _phpjs_shared_bc() { * @param n2 bc_num * @param scale [int] optional */ - bc_multiply : function(n1, n2, scale) { - var pval; // bc_num - var len1, len2; // int - var full_scale, prod_scale; // int + bc_multiply : function (n1, n2, scale) { + var pval // bc_num + var len1, len2 // int + var full_scale, prod_scale // int // Initialize things. - len1 = n1.n_len + n1.n_scale; - len2 = n2.n_len + n2.n_scale; - full_scale = n1.n_scale + n2.n_scale; - prod_scale = libbcmath.MIN(full_scale, libbcmath.MAX(scale, libbcmath.MAX(n1.n_scale, n2.n_scale))); + len1 = n1.n_len + n1.n_scale + len2 = n2.n_len + n2.n_scale + full_scale = n1.n_scale + n2.n_scale + prod_scale = libbcmath.MIN(full_scale, libbcmath.MAX(scale, libbcmath.MAX(n1.n_scale, n2.n_scale))) - //pval = libbcmath.bc_init_num(); // allow pass by ref + // pval = libbcmath.bc_init_num(); // allow pass by ref // Do the multiply - pval = libbcmath._bc_rec_mul(n1, len1, n2, len2, full_scale); + pval = libbcmath._bc_rec_mul(n1, len1, n2, len2, full_scale) // Assign to prod and clean up the number. - pval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS); - //pval.n_value = pval.n_ptr; // @FIX - pval.n_len = len2 + len1 + 1 - full_scale; - pval.n_scale = prod_scale; - libbcmath._bc_rm_leading_zeros(pval); + pval.n_sign = (n1.n_sign == n2.n_sign ? libbcmath.PLUS : libbcmath.MINUS) + // pval.n_value = pval.n_ptr; // @FIX + pval.n_len = len2 + len1 + 1 - full_scale + pval.n_scale = prod_scale + libbcmath._bc_rm_leading_zeros(pval) if (libbcmath.bc_is_zero(pval)) { - pval.n_sign = libbcmath.PLUS; + pval.n_sign = libbcmath.PLUS } - //bc_free_num (prod); - return pval; + // bc_free_num (prod); + return pval }, - new_sub_num : function(length, scale, value) { - var temp = new libbcmath.bc_num(); - temp.n_sign = libbcmath.PLUS; - temp.n_len = length; - temp.n_scale = scale; - temp.n_value = value; - return temp; + new_sub_num : function (length, scale, value) { + var temp = new libbcmath.bc_num() + temp.n_sign = libbcmath.PLUS + temp.n_len = length + temp.n_scale = scale + temp.n_value = value + return temp }, - _bc_simp_mul : function(n1, n1len, n2, n2len, full_scale) { - var prod; // bc_num - var n1ptr, n2ptr, pvptr; // char *n1ptr, *n2ptr, *pvptr; - var n1end, n2end; //char *n1end, *n2end; /* To the end of n1 and n2. */ - var indx, sum, prodlen; //int indx, sum, prodlen; - prodlen = n1len + n2len + 1; + _bc_simp_mul : function (n1, n1len, n2, n2len, full_scale) { + var prod // bc_num + var n1ptr, n2ptr, pvptr // char *n1ptr, *n2ptr, *pvptr; + var n1end, n2end // char *n1end, *n2end; /* To the end of n1 and n2. */ + var indx, sum, prodlen // int indx, sum, prodlen; + prodlen = n1len + n2len + 1 - prod = libbcmath.bc_new_num(prodlen, 0); + prod = libbcmath.bc_new_num(prodlen, 0) - n1end = n1len - 1; //(char *) (n1->n_value + n1len - 1); - n2end = n2len - 1; //(char *) (n2->n_value + n2len - 1); - pvptr = prodlen - 1; //(char *) ((*prod)->n_value + prodlen - 1); - sum = 0; + n1end = n1len - 1 // (char *) (n1->n_value + n1len - 1); + n2end = n2len - 1 // (char *) (n2->n_value + n2len - 1); + pvptr = prodlen - 1 // (char *) ((*prod)->n_value + prodlen - 1); + sum = 0 // Here is the loop... for (indx = 0; indx < prodlen - 1; indx++) { - n1ptr = n1end - libbcmath.MAX(0, indx - n2len + 1); //(char *) (n1end - MAX(0, indx-n2len+1)); - n2ptr = n2end - libbcmath.MIN(indx, n2len - 1); //(char *) (n2end - MIN(indx, n2len-1)); + n1ptr = n1end - libbcmath.MAX(0, indx - n2len + 1) // (char *) (n1end - MAX(0, indx-n2len+1)); + n2ptr = n2end - libbcmath.MIN(indx, n2len - 1) // (char *) (n2end - MIN(indx, n2len-1)); while ((n1ptr >= 0) && (n2ptr <= n2end)) { - sum += n1.n_value[n1ptr--] * n2.n_value[n2ptr++]; //sum += *n1ptr-- * *n2ptr++; + sum += n1.n_value[n1ptr--] * n2.n_value[n2ptr++] // sum += *n1ptr-- * *n2ptr++; } - prod.n_value[pvptr--] = Math.floor(sum % libbcmath.BASE); //*pvptr-- = sum % BASE; - sum = Math.floor(sum / libbcmath.BASE); //sum = sum / BASE; + prod.n_value[pvptr--] = Math.floor(sum % libbcmath.BASE) //* pvptr-- = sum % BASE; + sum = Math.floor(sum / libbcmath.BASE) // sum = sum / BASE; } - prod.n_value[pvptr] = sum; //*pvptr = sum; - return prod; + prod.n_value[pvptr] = sum //* pvptr = sum; + return prod }, @@ -451,66 +451,66 @@ function _phpjs_shared_bc() { multiply algorithm. Note: if sub is called, accum must be larger that what is being subtracted. Also, accum and val must have n_scale = 0. (e.g. they must look like integers. *) */ - _bc_shift_addsub : function(accum, val, shift, sub) { - var accp, valp; //signed char *accp, *valp; - var count, carry; //int count, carry; - count = val.n_len; + _bc_shift_addsub : function (accum, val, shift, sub) { + var accp, valp // signed char *accp, *valp; + var count, carry // int count, carry; + count = val.n_len if (val.n_value[0] === 0) { - count--; + count-- } - //assert (accum->n_len+accum->n_scale >= shift+count); + // assert (accum->n_len+accum->n_scale >= shift+count); if (accum.n_len + accum.n_scale < shift + count) { - throw new Error('len + scale < shift + count'); // ?? I think that's what assert does :) + throw new Error('len + scale < shift + count') // ?? I think that's what assert does :) } // Set up pointers and others - accp = accum.n_len + accum.n_scale - shift - 1; // (signed char *)(accum->n_value + accum->n_len + accum->n_scale - shift - 1); - valp = val.n_len = 1; //(signed char *)(val->n_value + val->n_len - 1); - carry = 0; + accp = accum.n_len + accum.n_scale - shift - 1 // (signed char *)(accum->n_value + accum->n_len + accum->n_scale - shift - 1); + valp = val.n_len = 1 // (signed char *)(val->n_value + val->n_len - 1); + carry = 0 if (sub) { // Subtraction, carry is really borrow. while (count--) { - accum.n_value[accp] -= val.n_value[valp--] + carry; //*accp -= *valp-- + carry; - if (accum.n_value[accp] < 0) { //if (*accp < 0) - carry = 1; - accum.n_value[accp--] += libbcmath.BASE; //*accp-- += BASE; + accum.n_value[accp] -= val.n_value[valp--] + carry //* accp -= *valp-- + carry; + if (accum.n_value[accp] < 0) { // if (*accp < 0) + carry = 1 + accum.n_value[accp--] += libbcmath.BASE //* accp-- += BASE; } else { - carry = 0; - accp--; + carry = 0 + accp-- } } while (carry) { - accum.n_value[accp] -= carry; //*accp -= carry; - if (accum.n_value[accp] < 0) { //if (*accp < 0) - accum.n_value[accp--] += libbcmath.BASE; // *accp-- += BASE; + accum.n_value[accp] -= carry //* accp -= carry; + if (accum.n_value[accp] < 0) { // if (*accp < 0) + accum.n_value[accp--] += libbcmath.BASE // *accp-- += BASE; } else { - carry = 0; + carry = 0 } } } else { // Addition while (count--) { - accum.n_value[accp] += val.n_value[valp--] + carry; //*accp += *valp-- + carry; - if (accum.n_value[accp] > (libbcmath.BASE - 1)) { //if (*accp > (BASE-1)) - carry = 1; - accum.n_value[accp--] -= libbcmath.BASE; //*accp-- -= BASE; + accum.n_value[accp] += val.n_value[valp--] + carry //* accp += *valp-- + carry; + if (accum.n_value[accp] > (libbcmath.BASE - 1)) { // if (*accp > (BASE-1)) + carry = 1 + accum.n_value[accp--] -= libbcmath.BASE //* accp-- -= BASE; } else { - carry = 0; - accp--; + carry = 0 + accp-- } } while (carry) { - accum.n_value[accp] += carry; //*accp += carry; - if (accum.n_value[accp] > (libbcmath.BASE - 1)) { //if (*accp > (BASE-1)) - accum.n_value[accp--] -= libbcmath.BASE; //*accp-- -= BASE; + accum.n_value[accp] += carry //* accp += carry; + if (accum.n_value[accp] > (libbcmath.BASE - 1)) { // if (*accp > (BASE-1)) + accum.n_value[accp--] -= libbcmath.BASE //* accp-- -= BASE; } else { - carry = 0; + carry = 0 } } } - return true; // accum is the pass-by-reference return + return true // accum is the pass-by-reference return }, /* Recursive divide and conquer multiply algorithm. @@ -521,98 +521,98 @@ function _phpjs_shared_bc() { B is the base of storage, number of digits in u1,u0 close to equal. */ - _bc_rec_mul : function(u, ulen, v, vlen, full_scale) { - var prod; // @return - var u0, u1, v0, v1; //bc_num - var u0len, v0len; //int - var m1, m2, m3, d1, d2; //bc_num - var n, prodlen, m1zero; // int - var d1len, d2len; // int + _bc_rec_mul : function (u, ulen, v, vlen, full_scale) { + var prod // @return + var u0, u1, v0, v1 // bc_num + var u0len, v0len // int + var m1, m2, m3, d1, d2 // bc_num + var n, prodlen, m1zero // int + var d1len, d2len // int // Base case? if ((ulen + vlen) < libbcmath.MUL_BASE_DIGITS || ulen < libbcmath.MUL_SMALL_DIGITS || vlen < libbcmath.MUL_SMALL_DIGITS) { - return libbcmath._bc_simp_mul(u, ulen, v, vlen, full_scale); + return libbcmath._bc_simp_mul(u, ulen, v, vlen, full_scale) } // Calculate n -- the u and v split point in digits. - n = Math.floor((libbcmath.MAX(ulen, vlen) + 1) / 2); + n = Math.floor((libbcmath.MAX(ulen, vlen) + 1) / 2) // Split u and v. if (ulen < n) { - u1 = libbcmath.bc_init_num(); //u1 = bc_copy_num (BCG(_zero_)); - u0 = libbcmath.new_sub_num(ulen, 0, u.n_value); + u1 = libbcmath.bc_init_num() // u1 = bc_copy_num (BCG(_zero_)); + u0 = libbcmath.new_sub_num(ulen, 0, u.n_value) } else { - u1 = libbcmath.new_sub_num(ulen - n, 0, u.n_value); - u0 = libbcmath.new_sub_num(n, 0, u.n_value + ulen - n); + u1 = libbcmath.new_sub_num(ulen - n, 0, u.n_value) + u0 = libbcmath.new_sub_num(n, 0, u.n_value + ulen - n) } if (vlen < n) { - v1 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_)); - v0 = libbcmath.new_sub_num(vlen, 0, v.n_value); + v1 = libbcmath.bc_init_num() // bc_copy_num (BCG(_zero_)); + v0 = libbcmath.new_sub_num(vlen, 0, v.n_value) } else { - v1 = libbcmath.new_sub_num(vlen - n, 0, v.n_value); - v0 = libbcmath.new_sub_num(n, 0, v.n_value + vlen - n); + v1 = libbcmath.new_sub_num(vlen - n, 0, v.n_value) + v0 = libbcmath.new_sub_num(n, 0, v.n_value + vlen - n) } - libbcmath._bc_rm_leading_zeros(u1); - libbcmath._bc_rm_leading_zeros(u0); - u0len = u0.n_len; - libbcmath._bc_rm_leading_zeros(v1); - libbcmath._bc_rm_leading_zeros(v0); - v0len = v0.n_len; + libbcmath._bc_rm_leading_zeros(u1) + libbcmath._bc_rm_leading_zeros(u0) + u0len = u0.n_len + libbcmath._bc_rm_leading_zeros(v1) + libbcmath._bc_rm_leading_zeros(v0) + v0len = v0.n_len - m1zero = libbcmath.bc_is_zero(u1) || libbcmath.bc_is_zero(v1); + m1zero = libbcmath.bc_is_zero(u1) || libbcmath.bc_is_zero(v1) // Calculate sub results ... - d1 = libbcmath.bc_init_num(); // needed? - d2 = libbcmath.bc_init_num(); // needed? - d1 = libbcmath.bc_sub(u1, u0, 0); - d1len = d1.n_len; + d1 = libbcmath.bc_init_num() // needed? + d2 = libbcmath.bc_init_num() // needed? + d1 = libbcmath.bc_sub(u1, u0, 0) + d1len = d1.n_len - d2 = libbcmath.bc_sub(v0, v1, 0); - d2len = d2.n_len; + d2 = libbcmath.bc_sub(v0, v1, 0) + d2len = d2.n_len // Do recursive multiplies and shifted adds. if (m1zero) { - m1 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_)); + m1 = libbcmath.bc_init_num() // bc_copy_num (BCG(_zero_)); } else { - //m1 = libbcmath.bc_init_num(); //allow pass-by-ref - m1 = libbcmath._bc_rec_mul(u1, u1.n_len, v1, v1.n_len, 0); + // m1 = libbcmath.bc_init_num(); //allow pass-by-ref + m1 = libbcmath._bc_rec_mul(u1, u1.n_len, v1, v1.n_len, 0) } if (libbcmath.bc_is_zero(d1) || libbcmath.bc_is_zero(d2)) { - m2 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_)); + m2 = libbcmath.bc_init_num() // bc_copy_num (BCG(_zero_)); } else { - //m2 = libbcmath.bc_init_num(); //allow pass-by-ref - m2 = libbcmath._bc_rec_mul(d1, d1len, d2, d2len, 0); + // m2 = libbcmath.bc_init_num(); //allow pass-by-ref + m2 = libbcmath._bc_rec_mul(d1, d1len, d2, d2len, 0) } if (libbcmath.bc_is_zero(u0) || libbcmath.bc_is_zero(v0)) { - m3 = libbcmath.bc_init_num(); //bc_copy_num (BCG(_zero_)); + m3 = libbcmath.bc_init_num() // bc_copy_num (BCG(_zero_)); } else { - //m3 = libbcmath.bc_init_num(); //allow pass-by-ref - m3 = libbcmath._bc_rec_mul(u0, u0.n_len, v0, v0.n_len, 0); + // m3 = libbcmath.bc_init_num(); //allow pass-by-ref + m3 = libbcmath._bc_rec_mul(u0, u0.n_len, v0, v0.n_len, 0) } // Initialize product - prodlen = ulen + vlen + 1; - prod = libbcmath.bc_new_num(prodlen, 0); + prodlen = ulen + vlen + 1 + prod = libbcmath.bc_new_num(prodlen, 0) if (!m1zero) { - libbcmath._bc_shift_addsub(prod, m1, 2 * n, 0); - libbcmath._bc_shift_addsub(prod, m1, n, 0); + libbcmath._bc_shift_addsub(prod, m1, 2 * n, 0) + libbcmath._bc_shift_addsub(prod, m1, n, 0) } - libbcmath._bc_shift_addsub(prod, m3, n, 0); - libbcmath._bc_shift_addsub(prod, m3, 0, 0); - libbcmath._bc_shift_addsub(prod, m2, n, d1.n_sign != d2.n_sign); + libbcmath._bc_shift_addsub(prod, m3, n, 0) + libbcmath._bc_shift_addsub(prod, m3, 0, 0) + libbcmath._bc_shift_addsub(prod, m2, n, d1.n_sign != d2.n_sign) - return prod; + return prod // Now clean up! - //bc_free_num (&u1); - //bc_free_num (&u0); - //bc_free_num (&v1); - //bc_free_num (&m1); - //bc_free_num (&v0); - //bc_free_num (&m2); - //bc_free_num (&m3); - //bc_free_num (&d1); - //bc_free_num (&d2); + // bc_free_num (&u1); + // bc_free_num (&u0); + // bc_free_num (&v1); + // bc_free_num (&m1); + // bc_free_num (&v0); + // bc_free_num (&m2); + // bc_free_num (&m3); + // bc_free_num (&d1); + // bc_free_num (&d2); }, @@ -624,15 +624,15 @@ function _phpjs_shared_bc() { * @param {boolean} ignore_last * @return -1, 0, 1 (see bc_compare) */ - _bc_do_compare : function(n1, n2, use_sign, ignore_last) { - var n1ptr, n2ptr; // int - var count; // int + _bc_do_compare : function (n1, n2, use_sign, ignore_last) { + var n1ptr, n2ptr // int + var count // int /* First, compare signs. */ if (use_sign && (n1.n_sign != n2.n_sign)) { if (n1.n_sign == libbcmath.PLUS) { - return (1); /* Positive N1 > Negative N2 */ + return (1) /* Positive N1 > Negative N2 */ } else { - return (-1); /* Negative N1 < Positive N1 */ + return (-1) /* Negative N1 < Positive N1 */ } } @@ -640,47 +640,47 @@ function _phpjs_shared_bc() { if (n1.n_len != n2.n_len) { if (n1.n_len > n2.n_len) { /* Magnitude of n1 > n2. */ if (!use_sign || (n1.n_sign == libbcmath.PLUS)) { - return (1); + return (1) } else { - return (-1); + return (-1) } } else { /* Magnitude of n1 < n2. */ if (!use_sign || (n1.n_sign == libbcmath.PLUS)) { - return (-1); + return (-1) } else { - return (1); + return (1) } } } /* If we get here, they have the same number of integer digits. check the integer part and the equal length part of the fraction. */ - count = n1.n_len + Math.min(n1.n_scale, n2.n_scale); - n1ptr = 0; - n2ptr = 0; + count = n1.n_len + Math.min(n1.n_scale, n2.n_scale) + n1ptr = 0 + n2ptr = 0 while ((count > 0) && (n1.n_value[n1ptr] == n2.n_value[n2ptr])) { - n1ptr++; - n2ptr++; - count--; + n1ptr++ + n2ptr++ + count-- } if (ignore_last && (count == 1) && (n1.n_scale == n2.n_scale)) { - return (0); + return (0) } if (count !== 0) { if (n1.n_value[n1ptr] > n2.n_value[n2ptr]) { /* Magnitude of n1 > n2. */ if (!use_sign || n1.n_sign == libbcmath.PLUS) { - return (1); + return (1) } else { - return (-1); + return (-1) } } else { /* Magnitude of n1 < n2. */ if (!use_sign || n1.n_sign == libbcmath.PLUS) { - return (-1); + return (-1) } else { - return (1); + return (1) } } } @@ -691,9 +691,9 @@ function _phpjs_shared_bc() { for (count = (n1.n_scale - n2.n_scale); count > 0; count--) { if (n1.n_value[n1ptr++] !== 0) { /* Magnitude of n1 > n2. */ if (!use_sign || n1.n_sign == libbcmath.PLUS) { - return (1); + return (1) } else { - return (-1); + return (-1) } } } @@ -701,9 +701,9 @@ function _phpjs_shared_bc() { for (count = (n2.n_scale - n1.n_scale); count > 0; count--) { if (n2.n_value[n2ptr++] !== 0) { /* Magnitude of n1 < n2. */ if (!use_sign || n1.n_sign == libbcmath.PLUS) { - return (-1); + return (-1) } else { - return (1); + return (1) } } } @@ -711,7 +711,7 @@ function _phpjs_shared_bc() { } /* They must be equal! */ - return (0); + return (0) }, @@ -719,53 +719,53 @@ function _phpjs_shared_bc() { /* Here is the full subtract routine that takes care of negative numbers. N2 is subtracted from N1 and the result placed in RESULT. SCALE_MIN is the minimum scale for the result. */ - bc_sub : function(n1, n2, scale_min) { - var diff; // bc_num - var cmp_res, res_scale; //int + bc_sub : function (n1, n2, scale_min) { + var diff // bc_num + var cmp_res, res_scale // int if (n1.n_sign != n2.n_sign) { - diff = libbcmath._bc_do_add(n1, n2, scale_min); - diff.n_sign = n1.n_sign; + diff = libbcmath._bc_do_add(n1, n2, scale_min) + diff.n_sign = n1.n_sign } else { /* subtraction must be done. */ /* Compare magnitudes. */ - cmp_res = libbcmath._bc_do_compare(n1, n2, false, false); + cmp_res = libbcmath._bc_do_compare(n1, n2, false, false) switch (cmp_res) { case -1: /* n1 is less than n2, subtract n1 from n2. */ - diff = libbcmath._bc_do_sub(n2, n1, scale_min); - diff.n_sign = (n2.n_sign == libbcmath.PLUS ? libbcmath.MINUS : libbcmath.PLUS); - break; + diff = libbcmath._bc_do_sub(n2, n1, scale_min) + diff.n_sign = (n2.n_sign == libbcmath.PLUS ? libbcmath.MINUS : libbcmath.PLUS) + break case 0: /* They are equal! return zero! */ - res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale)); - diff = libbcmath.bc_new_num(1, res_scale); - libbcmath.memset(diff.n_value, 0, 0, res_scale + 1); - break; + res_scale = libbcmath.MAX(scale_min, libbcmath.MAX(n1.n_scale, n2.n_scale)) + diff = libbcmath.bc_new_num(1, res_scale) + libbcmath.memset(diff.n_value, 0, 0, res_scale + 1) + break case 1: /* n2 is less than n1, subtract n2 from n1. */ - diff = libbcmath._bc_do_sub(n1, n2, scale_min); - diff.n_sign = n1.n_sign; - break; + diff = libbcmath._bc_do_sub(n1, n2, scale_min) + diff.n_sign = n1.n_sign + break } } /* Clean up and return. */ - //bc_free_num (result); - //*result = diff; - return diff; + // bc_free_num (result); + //* result = diff; + return diff }, - _bc_do_add : function(n1, n2, scale_min) { - var sum; // bc_num - var sum_scale, sum_digits; // int - var n1ptr, n2ptr, sumptr; // int - var carry, n1bytes, n2bytes; // int - var tmp; // int + _bc_do_add : function (n1, n2, scale_min) { + var sum // bc_num + var sum_scale, sum_digits // int + var n1ptr, n2ptr, sumptr // int + var carry, n1bytes, n2bytes // int + var tmp // int // Prepare sum. - sum_scale = libbcmath.MAX(n1.n_scale, n2.n_scale); - sum_digits = libbcmath.MAX(n1.n_len, n2.n_len) + 1; - sum = libbcmath.bc_new_num(sum_digits, libbcmath.MAX(sum_scale, scale_min)); + sum_scale = libbcmath.MAX(n1.n_scale, n2.n_scale) + sum_digits = libbcmath.MAX(n1.n_len, n2.n_len) + 1 + sum = libbcmath.bc_new_num(sum_digits, libbcmath.MAX(sum_scale, scale_min)) /* Not needed? @@ -778,91 +778,91 @@ function _phpjs_shared_bc() { */ // Start with the fraction part. Initialize the pointers. - n1bytes = n1.n_scale; - n2bytes = n2.n_scale; - n1ptr = (n1.n_len + n1bytes - 1); - n2ptr = (n2.n_len + n2bytes - 1); - sumptr = (sum_scale + sum_digits - 1); + n1bytes = n1.n_scale + n2bytes = n2.n_scale + n1ptr = (n1.n_len + n1bytes - 1) + n2ptr = (n2.n_len + n2bytes - 1) + sumptr = (sum_scale + sum_digits - 1) // Add the fraction part. First copy the longer fraction (ie when adding 1.2345 to 1 we know .2345 is correct already) . if (n1bytes != n2bytes) { if (n1bytes > n2bytes) { // n1 has more dp then n2 while (n1bytes > n2bytes) { - sum.n_value[sumptr--] = n1.n_value[n1ptr--]; + sum.n_value[sumptr--] = n1.n_value[n1ptr--] // *sumptr-- = *n1ptr--; - n1bytes--; + n1bytes-- } } else { // n2 has more dp then n1 while (n2bytes > n1bytes) { - sum.n_value[sumptr--] = n2.n_value[n2ptr--]; + sum.n_value[sumptr--] = n2.n_value[n2ptr--] // *sumptr-- = *n2ptr--; - n2bytes--; + n2bytes-- } } } // Now add the remaining fraction part and equal size integer parts. - n1bytes += n1.n_len; - n2bytes += n2.n_len; - carry = 0; + n1bytes += n1.n_len + n2bytes += n2.n_len + carry = 0 while ((n1bytes > 0) && (n2bytes > 0)) { // add the two numbers together - tmp = n1.n_value[n1ptr--] + n2.n_value[n2ptr--] + carry; + tmp = n1.n_value[n1ptr--] + n2.n_value[n2ptr--] + carry // *sumptr = *n1ptr-- + *n2ptr-- + carry; // check if they are >= 10 (impossible to be more then 18) if (tmp >= libbcmath.BASE) { - carry = 1; - tmp -= libbcmath.BASE; // yep, subtract 10, add a carry + carry = 1 + tmp -= libbcmath.BASE // yep, subtract 10, add a carry } else { - carry = 0; + carry = 0 } - sum.n_value[sumptr] = tmp; - sumptr--; - n1bytes--; - n2bytes--; + sum.n_value[sumptr] = tmp + sumptr-- + n1bytes-- + n2bytes-- } // Now add carry the [rest of the] longer integer part. if (n1bytes === 0) { // n2 is a bigger number then n1 while (n2bytes-- > 0) { - tmp = n2.n_value[n2ptr--] + carry; + tmp = n2.n_value[n2ptr--] + carry // *sumptr = *n2ptr-- + carry; if (tmp >= libbcmath.BASE) { - carry = 1; - tmp -= libbcmath.BASE; + carry = 1 + tmp -= libbcmath.BASE } else { - carry = 0; + carry = 0 } - sum.n_value[sumptr--] = tmp; + sum.n_value[sumptr--] = tmp } } else { // n1 is bigger then n2.. while (n1bytes-- > 0) { - tmp = n1.n_value[n1ptr--] + carry; + tmp = n1.n_value[n1ptr--] + carry // *sumptr = *n1ptr-- + carry; if (tmp >= libbcmath.BASE) { - carry = 1; - tmp -= libbcmath.BASE; + carry = 1 + tmp -= libbcmath.BASE } else { - carry = 0; + carry = 0 } - sum.n_value[sumptr--] = tmp; + sum.n_value[sumptr--] = tmp } } // Set final carry. if (carry == 1) { - sum.n_value[sumptr] += 1; + sum.n_value[sumptr] += 1 // *sumptr += 1; } // Adjust sum and return. - libbcmath._bc_rm_leading_zeros(sum); - return sum; + libbcmath._bc_rm_leading_zeros(sum) + return sum }, /** @@ -883,18 +883,18 @@ function _phpjs_shared_bc() { * @param {int} scale_min * @return bc_num */ - _bc_do_sub : function(n1, n2, scale_min) { - var diff; //bc_num - var diff_scale, diff_len; // int - var min_scale, min_len; // int - var n1ptr, n2ptr, diffptr; // int - var borrow, count, val; // int + _bc_do_sub : function (n1, n2, scale_min) { + var diff // bc_num + var diff_scale, diff_len // int + var min_scale, min_len // int + var n1ptr, n2ptr, diffptr // int + var borrow, count, val // int // Allocate temporary storage. - diff_len = libbcmath.MAX(n1.n_len, n2.n_len); - diff_scale = libbcmath.MAX(n1.n_scale, n2.n_scale); - min_len = libbcmath.MIN(n1.n_len, n2.n_len); - min_scale = libbcmath.MIN(n1.n_scale, n2.n_scale); - diff = libbcmath.bc_new_num(diff_len, libbcmath.MAX(diff_scale, scale_min)); + diff_len = libbcmath.MAX(n1.n_len, n2.n_len) + diff_scale = libbcmath.MAX(n1.n_scale, n2.n_scale) + min_len = libbcmath.MIN(n1.n_len, n2.n_len) + min_scale = libbcmath.MIN(n1.n_scale, n2.n_scale) + diff = libbcmath.bc_new_num(diff_len, libbcmath.MAX(diff_scale, scale_min)) /* Not needed? // Zero extra digits made by scale_min. @@ -907,68 +907,68 @@ function _phpjs_shared_bc() { */ // Initialize the subtract. - n1ptr = (n1.n_len + n1.n_scale - 1); - n2ptr = (n2.n_len + n2.n_scale - 1); - diffptr = (diff_len + diff_scale - 1); + n1ptr = (n1.n_len + n1.n_scale - 1) + n2ptr = (n2.n_len + n2.n_scale - 1) + diffptr = (diff_len + diff_scale - 1) // Subtract the numbers. - borrow = 0; + borrow = 0 // Take care of the longer scaled number. if (n1.n_scale != min_scale) { // n1 has the longer scale for (count = n1.n_scale - min_scale; count > 0; count--) { - diff.n_value[diffptr--] = n1.n_value[n1ptr--]; + diff.n_value[diffptr--] = n1.n_value[n1ptr--] // *diffptr-- = *n1ptr--; } } else { // n2 has the longer scale for (count = n2.n_scale - min_scale; count > 0; count--) { - val = 0 - n2.n_value[n2ptr--] - borrow; - //val = - *n2ptr-- - borrow; + val = 0 - n2.n_value[n2ptr--] - borrow + // val = - *n2ptr-- - borrow; if (val < 0) { - val += libbcmath.BASE; - borrow = 1; + val += libbcmath.BASE + borrow = 1 } else { - borrow = 0; + borrow = 0 } - diff.n_value[diffptr--] = val; - //*diffptr-- = val; + diff.n_value[diffptr--] = val + //* diffptr-- = val; } } // Now do the equal length scale and integer parts. for (count = 0; count < min_len + min_scale; count++) { - val = n1.n_value[n1ptr--] - n2.n_value[n2ptr--] - borrow; - //val = *n1ptr-- - *n2ptr-- - borrow; + val = n1.n_value[n1ptr--] - n2.n_value[n2ptr--] - borrow + // val = *n1ptr-- - *n2ptr-- - borrow; if (val < 0) { - val += libbcmath.BASE; - borrow = 1; + val += libbcmath.BASE + borrow = 1 } else { - borrow = 0; + borrow = 0 } - diff.n_value[diffptr--] = val; - //*diffptr-- = val; + diff.n_value[diffptr--] = val + //* diffptr-- = val; } // If n1 has more digits then n2, we now do that subtract. if (diff_len != min_len) { for (count = diff_len - min_len; count > 0; count--) { - val = n1.n_value[n1ptr--] - borrow; + val = n1.n_value[n1ptr--] - borrow // val = *n1ptr-- - borrow; if (val < 0) { - val += libbcmath.BASE; - borrow = 1; + val += libbcmath.BASE + borrow = 1 } else { - borrow = 0; + borrow = 0 } - diff.n_value[diffptr--] = val; + diff.n_value[diffptr--] = val } } // Clean up and return. - libbcmath._bc_rm_leading_zeros(diff); - return diff; + libbcmath._bc_rm_leading_zeros(diff) + return diff }, /** @@ -977,155 +977,155 @@ function _phpjs_shared_bc() { * @param {int} scale * @return bc_num */ - bc_new_num : function(length, scale) { - var temp; // bc_num - temp = new libbcmath.bc_num(); - temp.n_sign = libbcmath.PLUS; - temp.n_len = length; - temp.n_scale = scale; - temp.n_value = libbcmath.safe_emalloc(1, length + scale, 0); - libbcmath.memset(temp.n_value, 0, 0, length + scale); - return temp; + bc_new_num : function (length, scale) { + var temp // bc_num + temp = new libbcmath.bc_num() + temp.n_sign = libbcmath.PLUS + temp.n_len = length + temp.n_scale = scale + temp.n_value = libbcmath.safe_emalloc(1, length + scale, 0) + libbcmath.memset(temp.n_value, 0, 0, length + scale) + return temp }, - safe_emalloc : function(size, len, extra) { - return Array((size * len) + extra); + safe_emalloc : function (size, len, extra) { + return Array((size * len) + extra) }, /** * Create a new number */ - bc_init_num : function() { - return new libbcmath.bc_new_num(1, 0); + bc_init_num : function () { + return new libbcmath.bc_new_num(1, 0) }, - _bc_rm_leading_zeros : function(num) { /* We can move n_value to point to the first non zero digit! */ + _bc_rm_leading_zeros : function (num) { /* We can move n_value to point to the first non zero digit! */ while ((num.n_value[0] === 0) && (num.n_len > 1)) { - num.n_value.shift(); - num.n_len--; + num.n_value.shift() + num.n_len-- } }, /** * Convert to bc_num detecting scale */ - php_str2num : function(str) { - var p; - p = str.indexOf('.'); + php_str2num : function (str) { + var p + p = str.indexOf('.') if (p == -1) { - return libbcmath.bc_str2num(str, 0); + return libbcmath.bc_str2num(str, 0) } else { - return libbcmath.bc_str2num(str, (str.length - p)); + return libbcmath.bc_str2num(str, (str.length - p)) } }, - CH_VAL : function(c) { - return c - '0'; //?? + CH_VAL : function (c) { + return c - '0' // ?? }, - BCD_CHAR : function(d) { - return d + '0'; // ?? + BCD_CHAR : function (d) { + return d + '0' // ?? }, - isdigit : function(c) { - return (isNaN(parseInt(c, 10)) ? false : true); + isdigit : function (c) { + return (isNaN(parseInt(c, 10)) ? false : true) }, - bc_str2num : function(str_in, scale) { - var str, num, ptr, digits, strscale, zero_int, nptr; + bc_str2num : function (str_in, scale) { + var str, num, ptr, digits, strscale, zero_int, nptr // remove any non-expected characters /* Check for valid number and count digits. */ - str = str_in.split(''); // convert to array - ptr = 0; // str - digits = 0; - strscale = 0; - zero_int = false; + str = str_in.split('') // convert to array + ptr = 0 // str + digits = 0 + strscale = 0 + zero_int = false if ((str[ptr] === '+') || (str[ptr] === '-')) { - ptr++; /* Sign */ + ptr++ /* Sign */ } while (str[ptr] === '0') { - ptr++; /* Skip leading zeros. */ + ptr++ /* Skip leading zeros. */ } - //while (libbcmath.isdigit(str[ptr])) { - while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) { - ptr++; - digits++; /* digits */ + // while (libbcmath.isdigit(str[ptr])) { + while ((str[ptr]) % 1 === 0) { // libbcmath.isdigit(str[ptr])) { + ptr++ + digits++ /* digits */ } if (str[ptr] === '.') { - ptr++; /* decimal point */ + ptr++ /* decimal point */ } - //while (libbcmath.isdigit(str[ptr])) { - while ((str[ptr]) % 1 === 0) { //libbcmath.isdigit(str[ptr])) { - ptr++; - strscale++; /* digits */ + // while (libbcmath.isdigit(str[ptr])) { + while ((str[ptr]) % 1 === 0) { // libbcmath.isdigit(str[ptr])) { + ptr++ + strscale++ /* digits */ } if ((str[ptr]) || (digits + strscale === 0)) { // invalid number, return 0 - return libbcmath.bc_init_num(); - //*num = bc_copy_num (BCG(_zero_)); + return libbcmath.bc_init_num() + //* num = bc_copy_num (BCG(_zero_)); } /* Adjust numbers and allocate storage and initialize fields. */ - strscale = libbcmath.MIN(strscale, scale); + strscale = libbcmath.MIN(strscale, scale) if (digits === 0) { - zero_int = true; - digits = 1; + zero_int = true + digits = 1 } - num = libbcmath.bc_new_num(digits, strscale); + num = libbcmath.bc_new_num(digits, strscale) /* Build the whole number. */ - ptr = 0; // str + ptr = 0 // str if (str[ptr] === '-') { - num.n_sign = libbcmath.MINUS; - //(*num)->n_sign = MINUS; - ptr++; + num.n_sign = libbcmath.MINUS + // (*num)->n_sign = MINUS; + ptr++ } else { - num.n_sign = libbcmath.PLUS; - //(*num)->n_sign = PLUS; + num.n_sign = libbcmath.PLUS + // (*num)->n_sign = PLUS; if (str[ptr] === '+') { - ptr++; + ptr++ } } while (str[ptr] === '0') { - ptr++; /* Skip leading zeros. */ + ptr++ /* Skip leading zeros. */ } - nptr = 0; //(*num)->n_value; + nptr = 0 // (*num)->n_value; if (zero_int) { - num.n_value[nptr++] = 0; - digits = 0; + num.n_value[nptr++] = 0 + digits = 0 } for (; digits > 0; digits--) { - num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]); - //*nptr++ = CH_VAL(*ptr++); + num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]) + //* nptr++ = CH_VAL(*ptr++); } /* Build the fractional part. */ if (strscale > 0) { - ptr++; /* skip the decimal point! */ + ptr++ /* skip the decimal point! */ for (; strscale > 0; strscale--) { - num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]); + num.n_value[nptr++] = libbcmath.CH_VAL(str[ptr++]) } } - return num; + return num }, - cint : function(v) { + cint : function (v) { if (typeof v === 'undefined') { - v = 0; + v = 0 } - var x = parseInt(v, 10); + var x = parseInt(v, 10) if (isNaN(x)) { - x = 0; + x = 0 } - return x; + return x }, /** @@ -1133,8 +1133,8 @@ function _phpjs_shared_bc() { * @param {int} a * @param {int} b */ - MIN : function(a, b) { - return ((a > b) ? b : a); + MIN : function (a, b) { + return ((a > b) ? b : a) }, /** @@ -1142,16 +1142,16 @@ function _phpjs_shared_bc() { * @param {int} a * @param {int} b */ - MAX : function(a, b) { - return ((a > b) ? a : b); + MAX : function (a, b) { + return ((a > b) ? a : b) }, /** * Basic odd function * @param {int} a */ - ODD : function(a) { - return (a & 1); + ODD : function (a) { + return (a & 1) }, /** @@ -1161,10 +1161,10 @@ function _phpjs_shared_bc() { * @param {string} chr char to fill * @param {int} len length to fill */ - memset : function(r, ptr, chr, len) { - var i; + memset : function (r, ptr, chr, len) { + var i for (i = 0; i < len; i++) { - r[ptr + i] = chr; + r[ptr + i] = chr } }, @@ -1173,12 +1173,12 @@ function _phpjs_shared_bc() { * Obviously can't work like c does, so we've added an "offset" param so you could do memcpy(dest+1, src, len) as memcpy(dest, 1, src, len) * Also only works on arrays */ - memcpy : function(dest, ptr, src, srcptr, len) { - var i; + memcpy : function (dest, ptr, src, srcptr, len) { + var i for (i = 0; i < len; i++) { - dest[ptr + i] = src[srcptr + i]; + dest[ptr + i] = src[srcptr + i] } - return true; + return true }, @@ -1187,29 +1187,29 @@ function _phpjs_shared_bc() { * @param {bc_num} num number to check * @return boolean true when zero, false when not zero. */ - bc_is_zero : function(num) { - var count; // int - var nptr; // int + bc_is_zero : function (num) { + var count // int + var nptr // int /* Quick check. */ - //if (num == BCG(_zero_)) return TRUE; + // if (num == BCG(_zero_)) return TRUE; /* Initialize */ - count = num.n_len + num.n_scale; - nptr = 0; //num->n_value; + count = num.n_len + num.n_scale + nptr = 0 // num->n_value; /* The check */ while ((count > 0) && (num.n_value[nptr++] === 0)) { - count--; + count-- } if (count !== 0) { - return false; + return false } else { - return true; + return true } }, - bc_out_of_memory : function() { - throw new Error('(BC) Out of memory'); + bc_out_of_memory : function () { + throw new Error('(BC) Out of memory') } - }; - return libbcmath; + } + return libbcmath } diff --git a/functions/array/array.js b/functions/array/array.js index e5f21bd1f0..a89c0883ed 100644 --- a/functions/array/array.js +++ b/functions/array/array.js @@ -1,4 +1,4 @@ -function array() { +function array () { // discuss at: http://phpjs.org/functions/array/ // original by: d3x // improved by: Brett Zamir (http://brett-zamir.me) @@ -10,29 +10,29 @@ function array() { // returns 2: [0,'A',2] try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } var arrInst, e, __, that = this, - PHPJS_Array = function PHPJS_Array() {}; + PHPJS_Array = function PHPJS_Array () {} mainArgs = arguments, p = this.php_js, - _indexOf = function(value, from, strict) { + _indexOf = function (value, from, strict) { var i = from || 0, nonstrict = !strict, - length = this.length; + length = this.length while (i < length) { if (this[i] === value || (nonstrict && this[i] == value)) { - return i; + return i } - i++; + i++ } - return -1; - }; + return -1 + } // BEGIN REDUNDANT if (!p.Relator) { - p.Relator = (function() { + p.Relator = (function () { // Used this functional class for giving privacy to the class we are creating // Code adapted from http://www.devpro.it/code/192.html // Relator explained at http://webreflection.blogspot.com/2008/07/javascript-relator-object-aka.html @@ -41,44 +41,43 @@ function array() { // 2) In constructor, put: var _ = __.constructor(this); // 3) At top of each prototype method, put: var _ = __.method(this); // 4) Use like: _.privateVar = 5; - function _indexOf(value) { + function _indexOf (value) { var i = 0, - length = this.length; + length = this.length while (i < length) { if (this[i] === value) { - return i; + return i } - i++; + i++ } - return -1; + return -1 } - function Relator() { + function Relator () { var Stack = [], - Array = []; + Array = [] if (!Stack.indexOf) { - Stack.indexOf = _indexOf; + Stack.indexOf = _indexOf } return { // create a new relator - $ : function() { - return Relator(); + $: function () { + return Relator() }, - constructor : function(that) { - var i = Stack.indexOf(that); - ~ - i ? Array[i] : Array[Stack.push(that) - 1] = {}; + constructor: function (that) { + var i = Stack.indexOf(that) + ~i ? Array[i] : Array[Stack.push(that) - 1] = {} this.method(that) - .that = that; - return this.method(that); + .that = that + return this.method(that) }, - method : function(that) { - return Array[Stack.indexOf(that)]; + method: function (that) { + return Array[Stack.indexOf(that)] } - }; + } } - return Relator(); - }()); + return Relator() + }()) } // END REDUNDANT @@ -86,163 +85,163 @@ function array() { if (!p.PHPJS_Array) { // We keep this Relator outside the class in case adding prototype methods below // Prototype methods added elsewhere can also use this ArrayRelator to share these "pseudo-global mostly-private" variables - __ = p.ArrayRelator = p.ArrayRelator || p.Relator.$(); + __ = p.ArrayRelator = p.ArrayRelator || p.Relator.$() // We could instead allow arguments of {key:XX, value:YY} but even more cumbersome to write - p.PHPJS_Array = function PHPJS_Array() { + p.PHPJS_Array = function PHPJS_Array () { var _ = __.constructor(this), args = arguments, i = 0, - argl, p; + argl, p args = (args.length === 1 && args[0] && typeof args[0] === 'object' && // If first and only arg is an array, use that (Don't depend on this) - args[0].length && !args[0].propertyIsEnumerable('length')) ? args[0] : args; + args[0].length && !args[0].propertyIsEnumerable('length')) ? args[0] : args if (!_.objectChain) { - _.objectChain = args; - _.object = {}; - _.keys = []; - _.values = []; + _.objectChain = args + _.object = {} + _.keys = [] + _.values = [] } for (argl = args.length; i < argl; i++) { for (p in args[i]) { // Allow for access by key; use of private members to store sequence allows these to be iterated via for...in (but for read-only use, with hasOwnProperty or function filtering to avoid prototype methods, and per ES, potentially out of order) - this[p] = _.object[p] = args[i][p]; + this[p] = _.object[p] = args[i][p] // Allow for easier access by prototype methods - _.keys[_.keys.length] = p; - _.values[_.values.length] = args[i][p]; - break; + _.keys[_.keys.length] = p + _.values[_.values.length] = args[i][p] + break } } - }; - e = p.PHPJS_Array.prototype; - e.change_key_case = function(cs) { + } + e = p.PHPJS_Array.prototype + e.change_key_case = function (cs) { var _ = __.method(this), oldkey, newkey, i = 0, kl = _.keys.length, - case_fn = (!cs || cs === 'CASE_LOWER') ? 'toLowerCase' : 'toUpperCase'; + case_fn = (!cs || cs === 'CASE_LOWER') ? 'toLowerCase' : 'toUpperCase' while (i < kl) { - oldkey = _.keys[i]; - newkey = _.keys[i] = _.keys[i][case_fn](); + oldkey = _.keys[i] + newkey = _.keys[i] = _.keys[i][case_fn]() if (oldkey !== newkey) { // Break reference before deleting - this[oldkey] = _.object[oldkey] = _.objectChain[i][oldkey] = null; - delete this[oldkey]; - delete _.object[oldkey]; - delete _.objectChain[i][oldkey]; + this[oldkey] = _.object[oldkey] = _.objectChain[i][oldkey] = null + delete this[oldkey] + delete _.object[oldkey] + delete _.objectChain[i][oldkey] // Fix: should we make a deep copy? - this[newkey] = _.object[newkey] = _.objectChain[i][newkey] = _.values[i]; + this[newkey] = _.object[newkey] = _.objectChain[i][newkey] = _.values[i] } - i++; + i++ } - return this; - }; - e.flip = function() { + return this + } + e.flip = function () { var _ = __.method(this), i = 0, - kl = _.keys.length; + kl = _.keys.length while (i < kl) { - oldkey = _.keys[i]; - newkey = _.values[i]; + oldkey = _.keys[i] + newkey = _.values[i] if (oldkey !== newkey) { // Break reference before deleting - this[oldkey] = _.object[oldkey] = _.objectChain[i][oldkey] = null; - delete this[oldkey]; - delete _.object[oldkey]; - delete _.objectChain[i][oldkey]; - this[newkey] = _.object[newkey] = _.objectChain[i][newkey] = oldkey; - _.keys[i] = newkey; + this[oldkey] = _.object[oldkey] = _.objectChain[i][oldkey] = null + delete this[oldkey] + delete _.object[oldkey] + delete _.objectChain[i][oldkey] + this[newkey] = _.object[newkey] = _.objectChain[i][newkey] = oldkey + _.keys[i] = newkey } - i++; + i++ } - return this; - }; - e.walk = function(funcname, userdata) { + return this + } + e.walk = function (funcname, userdata) { var _ = __.method(this), obj, func, ini, i = 0, - kl = 0; + kl = 0 try { if (typeof funcname === 'function') { for (i = 0, kl = _.keys.length; i < kl; i++) { if (arguments.length > 1) { - funcname(_.values[i], _.keys[i], userdata); + funcname(_.values[i], _.keys[i], userdata) } else { - funcname(_.values[i], _.keys[i]); + funcname(_.values[i], _.keys[i]) } } } else if (typeof funcname === 'string') { - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; - ini = this.php_js.ini['phpjs.no-eval']; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} + ini = this.php_js.ini['phpjs.no-eval'] if (ini && ( parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value .toLowerCase() !== 'off') )) { if (arguments.length > 1) { for (i = 0, kl = _.keys.length; i < kl; i++) { - this.window[funcname](_.values[i], _.keys[i], userdata); + this.window[funcname](_.values[i], _.keys[i], userdata) } } else { for (i = 0, kl = _.keys.length; i < kl; i++) { - this.window[funcname](_.values[i], _.keys[i]); + this.window[funcname](_.values[i], _.keys[i]) } } } else { if (arguments.length > 1) { for (i = 0, kl = _.keys.length; i < kl; i++) { - eval(funcname + '(_.values[i], _.keys[i], userdata)'); + eval(funcname + '(_.values[i], _.keys[i], userdata)') } } else { for (i = 0, kl = _.keys.length; i < kl; i++) { - eval(funcname + '(_.values[i], _.keys[i])'); + eval(funcname + '(_.values[i], _.keys[i])') } } } } else if (funcname && typeof funcname === 'object' && funcname.length === 2) { - obj = funcname[0]; - func = funcname[1]; + obj = funcname[0] + func = funcname[1] if (arguments.length > 1) { for (i = 0, kl = _.keys.length; i < kl; i++) { - obj[func](_.values[i], _.keys[i], userdata); + obj[func](_.values[i], _.keys[i], userdata) } } else { for (i = 0, kl = _.keys.length; i < kl; i++) { - obj[func](_.values[i], _.keys[i]); + obj[func](_.values[i], _.keys[i]) } } } else { - return false; + return false } } catch (e) { - return false; + return false } - return this; - }; + return this + } // Here we'll return actual arrays since most logical and practical for these functions to do this - e.keys = function(search_value, argStrict) { + e.keys = function (search_value, argStrict) { var _ = __.method(this), pos, search = typeof search_value !== 'undefined', tmp_arr = [], - strict = !!argStrict; + strict = !!argStrict if (!search) { - return _.keys; + return _.keys } while ((pos = _indexOf(_.values, pos, strict)) !== -1) { - tmp_arr[tmp_arr.length] = _.keys[pos]; + tmp_arr[tmp_arr.length] = _.keys[pos] } - return tmp_arr; - }; - e.values = function() { - var _ = __.method(this); - return _.values; - }; + return tmp_arr + } + e.values = function () { + var _ = __.method(this) + return _.values + } // Return non-object, non-array values, since most sensible - e.search = function(needle, argStrict) { + e.search = function (needle, argStrict) { var _ = __.method(this), strict = !!argStrict, haystack = _.values, - i, vl, val, flags; + i, vl, val, flags if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp if (!strict) { @@ -250,96 +249,96 @@ function array() { flags = 'i' + (needle.global ? 'g' : '') + (needle.multiline ? 'm' : '') + // sticky is FF only - (needle.sticky ? 'y' : ''); - needle = new RegExp(needle.source, flags); + (needle.sticky ? 'y' : '') + needle = new RegExp(needle.source, flags) } for (i = 0, vl = haystack.length; i < vl; i++) { - val = haystack[i]; + val = haystack[i] if (needle.test(val)) { - return _.keys[i]; + return _.keys[i] } } - return false; + return false } for (i = 0, vl = haystack.length; i < vl; i++) { - val = haystack[i]; + val = haystack[i] if ((strict && val === needle) || (!strict && val == needle)) { - return _.keys[i]; + return _.keys[i] } } - return false; - }; - e.sum = function() { + return false + } + e.sum = function () { var _ = __.method(this), sum = 0, i = 0, - kl = _.keys.length; + kl = _.keys.length while (i < kl) { if (!isNaN(parseFloat(_.values[i]))) { - sum += parseFloat(_.values[i]); + sum += parseFloat(_.values[i]) } - i++; + i++ } - return sum; - }; + return sum + } // Experimental functions - e.foreach = function(handler) { + e.foreach = function (handler) { var _ = __.method(this), i = 0, - kl = _.keys.length; + kl = _.keys.length while (i < kl) { if (handler.length === 1) { // only pass the value - handler(_.values[i]); + handler(_.values[i]) } else { - handler(_.keys[i], _.values[i]); + handler(_.keys[i], _.values[i]) } - i++; + i++ } - return this; - }; - e.list = function() { + return this + } + e.list = function () { var key, _ = __.method(this), i = 0, - argl = arguments.length; + argl = arguments.length while (i < argl) { - key = _.keys[i]; + key = _.keys[i] if (key && key.length === parseInt(key, 10) .toString() .length && // Key represents an int parseInt(key, 10) < argl) { // Key does not exceed arguments - that.window[arguments[key]] = _.values[key]; + that.window[arguments[key]] = _.values[key] } - i++; + i++ } - return this; - }; + return this + } // Parallel functionality and naming of built-in JavaScript array methods - e.forEach = function(handler) { + e.forEach = function (handler) { var _ = __.method(this), i = 0, - kl = _.keys.length; + kl = _.keys.length while (i < kl) { - handler(_.values[i], _.keys[i], this); - i++; + handler(_.values[i], _.keys[i], this) + i++ } - return this; - }; + return this + } // Our own custom convenience functions - e.$object = function() { - var _ = __.method(this); - return _.object; - }; - e.$objectChain = function() { - var _ = __.method(this); - return _.objectChain; - }; + e.$object = function () { + var _ = __.method(this) + return _.object + } + e.$objectChain = function () { + var _ = __.method(this) + return _.objectChain + } } - PHPJS_Array.prototype = p.PHPJS_Array.prototype; - arrInst = new PHPJS_Array(); - p.PHPJS_Array.apply(arrInst, mainArgs); - return arrInst; + PHPJS_Array.prototype = p.PHPJS_Array.prototype + arrInst = new PHPJS_Array() + p.PHPJS_Array.apply(arrInst, mainArgs) + return arrInst } - return Array.prototype.slice.call(mainArgs); -} \ No newline at end of file + return Array.prototype.slice.call(mainArgs) +} diff --git a/functions/array/array_change_key_case.js b/functions/array/array_change_key_case.js index f0dd44bf86..df9d7fe534 100644 --- a/functions/array/array_change_key_case.js +++ b/functions/array/array_change_key_case.js @@ -1,4 +1,4 @@ -function array_change_key_case(array, cs) { +function array_change_key_case (array, cs) { // discuss at: http://phpjs.org/functions/array_change_key_case/ // original by: Ates Goral (http://magnetiq.com) // improved by: marrtins @@ -21,22 +21,22 @@ function array_change_key_case(array, cs) { // example 7: newArr.splice(1, 1); // returns 7: {b: 1} - var case_fn, key, tmp_ar = {}; + var case_fn, key, tmp_ar = {} if (Object.prototype.toString.call(array) === '[object Array]') { - return array; + return array } if (array && typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array - return array.change_key_case(cs); + return array.change_key_case(cs) } if (array && typeof array === 'object') { - case_fn = (!cs || cs === 'CASE_LOWER') ? 'toLowerCase' : 'toUpperCase'; + case_fn = (!cs || cs === 'CASE_LOWER') ? 'toLowerCase' : 'toUpperCase' for (key in array) { - tmp_ar[key[case_fn]()] = array[key]; + tmp_ar[key[case_fn]()] = array[key] } - return tmp_ar; + return tmp_ar } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/array/array_chunk.js b/functions/array/array_chunk.js index c9ca4d9fef..37893ff16f 100644 --- a/functions/array/array_chunk.js +++ b/functions/array/array_chunk.js @@ -1,4 +1,4 @@ -function array_chunk(input, size, preserve_keys) { +function array_chunk (input, size, preserve_keys) { // discuss at: http://phpjs.org/functions/array_chunk/ // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // improved by: Brett Zamir (http://brett-zamir.me) @@ -16,40 +16,40 @@ function array_chunk(input, size, preserve_keys) { i = 0, c = -1, l = input.length || 0, - n = []; + n = [] if (size < 1) { - return null; + return null } if (Object.prototype.toString.call(input) === '[object Array]') { if (preserve_keys) { while (i < l) { - (x = i % size) ? n[c][i] = input[i]: n[++c] = {}, n[c][i] = input[i]; - i++; + (x = i % size) ? n[c][i] = input[i] : n[++c] = {}, n[c][i] = input[i] + i++ } } else { while (i < l) { - (x = i % size) ? n[c][x] = input[i]: n[++c] = [input[i]]; - i++; + (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]] + i++ } } } else { if (preserve_keys) { for (p in input) { if (input.hasOwnProperty(p)) { - (x = i % size) ? n[c][p] = input[p]: n[++c] = {}, n[c][p] = input[p]; - i++; + (x = i % size) ? n[c][p] = input[p] : n[++c] = {}, n[c][p] = input[p] + i++ } } } else { for (p in input) { if (input.hasOwnProperty(p)) { - (x = i % size) ? n[c][x] = input[p]: n[++c] = [input[p]]; - i++; + (x = i % size) ? n[c][x] = input[p] : n[++c] = [input[p]] + i++ } } } } - return n; -} \ No newline at end of file + return n +} diff --git a/functions/array/array_combine.js b/functions/array/array_combine.js index 0823e891a2..29c778efc7 100644 --- a/functions/array/array_combine.js +++ b/functions/array/array_combine.js @@ -1,4 +1,4 @@ -function array_combine(keys, values) { +function array_combine (keys, values) { // discuss at: http://phpjs.org/functions/array_combine/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Brett Zamir (http://brett-zamir.me) @@ -7,23 +7,23 @@ function array_combine(keys, values) { var new_array = {}, keycount = keys && keys.length, - i = 0; + i = 0 // input sanitation if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count - return false; + return false } // number of elements does not match if (keycount != values.length) { - return false; + return false } for (i = 0; i < keycount; i++) { - new_array[keys[i]] = values[i]; + new_array[keys[i]] = values[i] } - return new_array; -} \ No newline at end of file + return new_array +} diff --git a/functions/array/array_count_values.js b/functions/array/array_count_values.js index 453a737789..dc89431020 100644 --- a/functions/array/array_count_values.js +++ b/functions/array/array_count_values.js @@ -1,4 +1,4 @@ -function array_count_values(array) { +function array_count_values (array) { // discuss at: http://phpjs.org/functions/array_count_values/ // original by: Ates Goral (http://magnetiq.com) // improved by: Michael White (http://getsprink.com) @@ -15,42 +15,42 @@ function array_count_values(array) { var tmp_arr = {}, key = '', - t = ''; + t = '' - var __getType = function(obj) { + var __getType = function (obj) { // Objects are php associative arrays. - var t = typeof obj; - t = t.toLowerCase(); + var t = typeof obj + t = t.toLowerCase() if (t === 'object') { - t = 'array'; + t = 'array' } - return t; - }; + return t + } - var __countValue = function(tmp_arr, value) { + var __countValue = function (tmp_arr, value) { switch (typeof value) { - case 'number': - if (Math.floor(value) !== value) { - return; - } + case 'number': + if (Math.floor(value) !== value) { + return + } // Fall-through - case 'string': - if (value in tmp_arr && tmp_arr.hasOwnProperty(value)) { - ++tmp_arr[value]; - } else { - tmp_arr[value] = 1; - } + case 'string': + if (value in tmp_arr && tmp_arr.hasOwnProperty(value)) { + ++tmp_arr[value] + } else { + tmp_arr[value] = 1 + } } - }; + } - t = __getType(array); + t = __getType(array) if (t === 'array') { for (key in array) { if (array.hasOwnProperty(key)) { - __countValue.call(this, tmp_arr, array[key]); + __countValue.call(this, tmp_arr, array[key]) } } } - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/array/array_diff.js b/functions/array/array_diff.js index 5ff10df76b..dc47b1349c 100644 --- a/functions/array/array_diff.js +++ b/functions/array/array_diff.js @@ -1,4 +1,4 @@ -function array_diff(arr1) { +function array_diff (arr1) { // discuss at: http://phpjs.org/functions/array_diff/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Sanjoy Roy @@ -11,20 +11,20 @@ function array_diff(arr1) { k1 = '', i = 1, k = '', - arr = {}; + arr = {} arr1keys: for (k1 in arr1) { for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1]) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_diff_assoc.js b/functions/array/array_diff_assoc.js index 521191d258..43007eb658 100644 --- a/functions/array/array_diff_assoc.js +++ b/functions/array/array_diff_assoc.js @@ -1,4 +1,4 @@ -function array_diff_assoc(arr1) { +function array_diff_assoc (arr1) { // discuss at: http://phpjs.org/functions/array_diff_assoc/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: 0m3r @@ -11,20 +11,20 @@ function array_diff_assoc(arr1) { k1 = '', i = 1, k = '', - arr = {}; + arr = {} arr1keys: for (k1 in arr1) { for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1] && k === k1) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_diff_key.js b/functions/array/array_diff_key.js index 679d25dc49..eb1e7e1537 100644 --- a/functions/array/array_diff_key.js +++ b/functions/array/array_diff_key.js @@ -1,4 +1,4 @@ -function array_diff_key(arr1) { +function array_diff_key (arr1) { // discuss at: http://phpjs.org/functions/array_diff_key/ // original by: Ates Goral (http://magnetiq.com) // revised by: Brett Zamir (http://brett-zamir.me) @@ -13,20 +13,20 @@ function array_diff_key(arr1) { k1 = '', i = 1, k = '', - arr = {}; + arr = {} arr1keys: for (k1 in arr1) { for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (k === k1) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_diff_uassoc.js b/functions/array/array_diff_uassoc.js index f657893a86..aa6ba6fd4e 100644 --- a/functions/array/array_diff_uassoc.js +++ b/functions/array/array_diff_uassoc.js @@ -1,4 +1,4 @@ -function array_diff_uassoc(arr1) { +function array_diff_uassoc (arr1) { // discuss at: http://phpjs.org/functions/array_diff_uassoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -12,22 +12,22 @@ function array_diff_uassoc(arr1) { arr = {}, i = 1, k1 = '', - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1] && cb(k, k1) === 0) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_diff_ukey.js b/functions/array/array_diff_ukey.js index 7a9847d91d..8179db8e62 100644 --- a/functions/array/array_diff_ukey.js +++ b/functions/array/array_diff_ukey.js @@ -1,4 +1,4 @@ -function array_diff_ukey(arr1) { +function array_diff_ukey (arr1) { // discuss at: http://phpjs.org/functions/array_diff_ukey/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {blue: 1, red: 2, green: 3, purple: 4} @@ -12,23 +12,23 @@ function array_diff_ukey(arr1) { arr = {}, i = 1, k1 = '', - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb(k, k1) === 0) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_fill.js b/functions/array/array_fill.js index d02c01f93e..c6269e9797 100644 --- a/functions/array/array_fill.js +++ b/functions/array/array_fill.js @@ -1,17 +1,17 @@ -function array_fill(start_index, num, mixed_val) { +function array_fill (start_index, num, mixed_val) { // discuss at: http://phpjs.org/functions/array_fill/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: array_fill(5, 6, 'banana'); // returns 1: { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' } - var key, tmp_arr = {}; + var key, tmp_arr = {} if (!isNaN(start_index) && !isNaN(num)) { for (key = 0; key < num; key++) { - tmp_arr[(key + start_index)] = mixed_val; + tmp_arr[(key + start_index)] = mixed_val } } - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/array/array_fill_keys.js b/functions/array/array_fill_keys.js index e932ae7046..e586e50da6 100644 --- a/functions/array/array_fill_keys.js +++ b/functions/array/array_fill_keys.js @@ -1,4 +1,4 @@ -function array_fill_keys(keys, value) { +function array_fill_keys (keys, value) { // discuss at: http://phpjs.org/functions/array_fill_keys/ // original by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Brett Zamir (http://brett-zamir.me) @@ -7,11 +7,11 @@ function array_fill_keys(keys, value) { // returns 1: {"foo": "banana", 5: "banana", 10: "banana", "bar": "banana"} var retObj = {}, - key = ''; + key = '' for (key in keys) { - retObj[keys[key]] = value; + retObj[keys[key]] = value } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/array/array_filter.js b/functions/array/array_filter.js index 04c676e0c2..75a520fa4e 100644 --- a/functions/array/array_filter.js +++ b/functions/array/array_filter.js @@ -1,4 +1,4 @@ -function array_filter(arr, func) { +function array_filter (arr, func) { // discuss at: http://phpjs.org/functions/array_filter/ // original by: Brett Zamir (http://brett-zamir.me) // input by: max4ever @@ -14,22 +14,22 @@ function array_filter(arr, func) { // returns 3: {"a":1, "c":-1}; var retObj = {}, - k; + k - func = func || function(v) { - return v; - }; + func = func || function (v) { + return v + } // Fix: Issue #73 if (Object.prototype.toString.call(arr) === '[object Array]') { - retObj = []; + retObj = [] } for (k in arr) { if (func(arr[k])) { - retObj[k] = arr[k]; + retObj[k] = arr[k] } } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/array/array_flip.js b/functions/array/array_flip.js index ab97547e99..a313bc232f 100644 --- a/functions/array/array_flip.js +++ b/functions/array/array_flip.js @@ -1,4 +1,4 @@ -function array_flip(trans) { +function array_flip (trans) { // discuss at: http://phpjs.org/functions/array_flip/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Pier Paolo Ramon (http://www.mastersoup.com/) @@ -11,19 +11,19 @@ function array_flip(trans) { // example 2: array_flip(array({a: 0}, {b: 1}, {c: 2}))[1]; // returns 2: 'b' - var key, tmp_ar = {}; + var key, tmp_ar = {} // Duck-type check for our own array()-created PHPJS_Array if (trans && typeof trans === 'object' && trans.change_key_case) { - return trans.flip(); + return trans.flip() } for (key in trans) { if (!trans.hasOwnProperty(key)) { - continue; + continue } - tmp_ar[trans[key]] = key; + tmp_ar[trans[key]] = key } - return tmp_ar; -} \ No newline at end of file + return tmp_ar +} diff --git a/functions/array/array_intersect.js b/functions/array/array_intersect.js index ea68b654ae..d5222ed58f 100644 --- a/functions/array/array_intersect.js +++ b/functions/array/array_intersect.js @@ -1,4 +1,4 @@ -function array_intersect(arr1) { +function array_intersect (arr1) { // discuss at: http://phpjs.org/functions/array_intersect/ // original by: Brett Zamir (http://brett-zamir.me) // note: These only output associative arrays (would need to be @@ -15,24 +15,24 @@ function array_intersect(arr1) { k1 = '', arr = {}, i = 0, - k = ''; + k = '' arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1]) { if (i === arglm1) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_intersect_assoc.js b/functions/array/array_intersect_assoc.js index d442d92948..442a413963 100644 --- a/functions/array/array_intersect_assoc.js +++ b/functions/array/array_intersect_assoc.js @@ -1,4 +1,4 @@ -function array_intersect_assoc(arr1) { +function array_intersect_assoc (arr1) { // discuss at: http://phpjs.org/functions/array_intersect_assoc/ // original by: Brett Zamir (http://brett-zamir.me) // note: These only output associative arrays (would need to be @@ -14,24 +14,24 @@ function array_intersect_assoc(arr1) { k1 = '', arr = {}, i = 0, - k = ''; + k = '' arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1] && k === k1) { if (i === arglm1) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_intersect_key.js b/functions/array/array_intersect_key.js index de30865909..6323c74ab3 100644 --- a/functions/array/array_intersect_key.js +++ b/functions/array/array_intersect_key.js @@ -1,4 +1,4 @@ -function array_intersect_key(arr1) { +function array_intersect_key (arr1) { // discuss at: http://phpjs.org/functions/array_intersect_key/ // original by: Brett Zamir (http://brett-zamir.me) // note: These only output associative arrays (would need to be @@ -14,30 +14,30 @@ function array_intersect_key(arr1) { k1 = '', arr = {}, i = 0, - k = ''; + k = '' arr1keys: for (k1 in arr1) { if (!arr1.hasOwnProperty(k1)) { - continue; + continue } arrs: for (i = 1; i < argl; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (!arr.hasOwnProperty(k)) { - continue; + continue } if (k === k1) { if (i === arglm1) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_intersect_uassoc.js b/functions/array/array_intersect_uassoc.js index 60ca14660f..ffe9820eea 100644 --- a/functions/array/array_intersect_uassoc.js +++ b/functions/array/array_intersect_uassoc.js @@ -1,4 +1,4 @@ -function array_intersect_uassoc(arr1) { +function array_intersect_uassoc (arr1) { // discuss at: http://phpjs.org/functions/array_intersect_uassoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -13,27 +13,27 @@ function array_intersect_uassoc(arr1) { k1 = '', i = 1, arr = {}, - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (arr[k] === arr1[k1] && cb(k, k1) === 0) { if (i === arglm2) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_intersect_ukey.js b/functions/array/array_intersect_ukey.js index cb58d0bdd4..deed41aed7 100644 --- a/functions/array/array_intersect_ukey.js +++ b/functions/array/array_intersect_ukey.js @@ -1,4 +1,4 @@ -function array_intersect_ukey(arr1) { +function array_intersect_ukey (arr1) { // discuss at: http://phpjs.org/functions/array_intersect_ukey/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {blue: 1, red: 2, green: 3, purple: 4} @@ -13,27 +13,27 @@ function array_intersect_ukey(arr1) { k1 = '', i = 1, arr = {}, - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb(k, k1) === 0) { if (i === arglm2) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_key_exists.js b/functions/array/array_key_exists.js index b598ef993a..2a390a21f8 100644 --- a/functions/array/array_key_exists.js +++ b/functions/array/array_key_exists.js @@ -1,4 +1,4 @@ -function array_key_exists(key, search) { +function array_key_exists (key, search) { // discuss at: http://phpjs.org/functions/array_key_exists/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Felix Geisendoerfer (http://www.debuggable.com/felix) @@ -6,8 +6,8 @@ function array_key_exists(key, search) { // returns 1: true if (!search || (search.constructor !== Array && search.constructor !== Object)) { - return false; + return false } - return key in search; -} \ No newline at end of file + return key in search +} diff --git a/functions/array/array_keys.js b/functions/array/array_keys.js index 3f5ef46e0f..f6b5aa8c1a 100644 --- a/functions/array/array_keys.js +++ b/functions/array/array_keys.js @@ -1,4 +1,4 @@ -function array_keys(input, search_value, argStrict) { +function array_keys (input, search_value, argStrict) { // discuss at: http://phpjs.org/functions/array_keys/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Brett Zamir (http://brett-zamir.me) @@ -14,29 +14,29 @@ function array_keys(input, search_value, argStrict) { tmp_arr = [], strict = !!argStrict, include = true, - key = ''; + key = '' if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array - return input.keys(search_value, argStrict); + return input.keys(search_value, argStrict) } for (key in input) { if (input.hasOwnProperty(key)) { - include = true; + include = true if (search) { if (strict && input[key] !== search_value) { - include = false; + include = false } else if (input[key] != search_value) { - include = false; + include = false } } if (include) { - tmp_arr[tmp_arr.length] = key; + tmp_arr[tmp_arr.length] = key } } } - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/array/array_map.js b/functions/array/array_map.js index 4eb2a35c76..e71e39bc8f 100644 --- a/functions/array/array_map.js +++ b/functions/array/array_map.js @@ -1,4 +1,4 @@ -function array_map(callback) { +function array_map (callback) { // discuss at: http://phpjs.org/functions/array_map/ // original by: Andrea Giammarchi (http://webreflection.blogspot.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -18,33 +18,33 @@ function array_map(callback) { k = 1, m = 0, tmp = [], - tmp_ar = []; + tmp_ar = [] while (i < j) { while (k < argc) { - tmp[m++] = argv[k++][i]; + tmp[m++] = argv[k++][i] } - m = 0; - k = 1; + m = 0 + k = 1 if (callback) { if (typeof callback === 'string') { - cb = glbl[callback]; + cb = glbl[callback] } else if (typeof callback === 'object' && callback.length) { - obj = typeof callback[0] === 'string' ? glbl[callback[0]] : callback[0]; + obj = typeof callback[0] === 'string' ? glbl[callback[0]] : callback[0] if (typeof obj === 'undefined') { - throw 'Object not found: ' + callback[0]; + throw 'Object not found: ' + callback[0] } - cb = typeof callback[1] === 'string' ? obj[callback[1]] : callback[1]; + cb = typeof callback[1] === 'string' ? obj[callback[1]] : callback[1] } - tmp_ar[i++] = cb.apply(obj, tmp); + tmp_ar[i++] = cb.apply(obj, tmp) } else { - tmp_ar[i++] = tmp; + tmp_ar[i++] = tmp } - tmp = []; + tmp = [] } - return tmp_ar; -} \ No newline at end of file + return tmp_ar +} diff --git a/functions/array/array_merge.js b/functions/array/array_merge.js index b64524dbd2..92b2ca30b8 100644 --- a/functions/array/array_merge.js +++ b/functions/array/array_merge.js @@ -1,4 +1,4 @@ -function array_merge() { +function array_merge () { // discuss at: http://phpjs.org/functions/array_merge/ // original by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Nate @@ -23,40 +23,40 @@ function array_merge() { i = 0, ct = 0, toStr = Object.prototype.toString, - retArr = true; + retArr = true for (i = 0; i < argl; i++) { if (toStr.call(args[i]) !== '[object Array]') { - retArr = false; - break; + retArr = false + break } } if (retArr) { - retArr = []; + retArr = [] for (i = 0; i < argl; i++) { - retArr = retArr.concat(args[i]); + retArr = retArr.concat(args[i]) } - return retArr; + return retArr } for (i = 0, ct = 0; i < argl; i++) { - arg = args[i]; + arg = args[i] if (toStr.call(arg) === '[object Array]') { for (j = 0, argil = arg.length; j < argil; j++) { - retObj[ct++] = arg[j]; + retObj[ct++] = arg[j] } } else { for (k in arg) { if (arg.hasOwnProperty(k)) { if (parseInt(k, 10) + '' === k) { - retObj[ct++] = arg[k]; + retObj[ct++] = arg[k] } else { - retObj[k] = arg[k]; + retObj[k] = arg[k] } } } } } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/array/array_merge_recursive.js b/functions/array/array_merge_recursive.js index a07da8656f..17aba4d65c 100644 --- a/functions/array/array_merge_recursive.js +++ b/functions/array/array_merge_recursive.js @@ -1,4 +1,4 @@ -function array_merge_recursive(arr1, arr2) { +function array_merge_recursive (arr1, arr2) { // discuss at: http://phpjs.org/functions/array_merge_recursive/ // original by: Subhasis Deb // input by: Brett Zamir (http://brett-zamir.me) @@ -9,26 +9,26 @@ function array_merge_recursive(arr1, arr2) { // example 1: array_merge_recursive(arr1, arr2) // returns 1: {'color': {'favorite': {0: 'red', 1: 'green'}, 0: 'blue'}, 1: 5, 1: 10} - var idx = ''; + var idx = '' if (arr1 && Object.prototype.toString.call(arr1) === '[object Array]' && arr2 && Object.prototype.toString.call(arr2) === '[object Array]') { for (idx in arr2) { - arr1.push(arr2[idx]); + arr1.push(arr2[idx]) } } else if ((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))) { for (idx in arr2) { if (idx in arr1) { if (typeof arr1[idx] === 'object' && typeof arr2 === 'object') { - arr1[idx] = this.array_merge(arr1[idx], arr2[idx]); + arr1[idx] = this.array_merge(arr1[idx], arr2[idx]) } else { - arr1[idx] = arr2[idx]; + arr1[idx] = arr2[idx] } } else { - arr1[idx] = arr2[idx]; + arr1[idx] = arr2[idx] } } } - return arr1; -} \ No newline at end of file + return arr1 +} diff --git a/functions/array/array_multisort.js b/functions/array/array_multisort.js index eed4a32bae..7689c58956 100644 --- a/functions/array/array_multisort.js +++ b/functions/array/array_multisort.js @@ -1,4 +1,4 @@ -function array_multisort(arr) { +function array_multisort (arr) { // discuss at: http://phpjs.org/functions/array_multisort/ // original by: Theriault // example 1: array_multisort([1, 2, 1, 2, 1, 2], [1, 2, 3, 4, 5, 6]); @@ -16,195 +16,195 @@ function array_multisort(arr) { // bits: HGFE DCBA // args: Holds pointer to arguments for reassignment - var g, i, j, k, l, sal, vkey, elIndex, lastSorts, tmpArray, zlast; + var g, i, j, k, l, sal, vkey, elIndex, lastSorts, tmpArray, zlast - var sortFlag = [0]; - var thingsToSort = []; - var nLastSort = []; - var lastSort = []; + var sortFlag = [0] + var thingsToSort = [] + var nLastSort = [] + var lastSort = [] // possibly redundant - var args = arguments; + var args = arguments var flags = { - 'SORT_REGULAR' : 16, - 'SORT_NUMERIC' : 17, - 'SORT_STRING' : 18, - 'SORT_ASC' : 32, - 'SORT_DESC' : 40 - }; + 'SORT_REGULAR': 16, + 'SORT_NUMERIC': 17, + 'SORT_STRING': 18, + 'SORT_ASC': 32, + 'SORT_DESC': 40 + } - var sortDuplicator = function(a, b) { - return nLastSort.shift(); - }; + var sortDuplicator = function (a, b) { + return nLastSort.shift() + } var sortFunctions = [ [ - function(a, b) { - lastSort.push(a > b ? 1 : (a < b ? -1 : 0)); - return a > b ? 1 : (a < b ? -1 : 0); + function (a, b) { + lastSort.push(a > b ? 1 : (a < b ? -1 : 0)) + return a > b ? 1 : (a < b ? -1 : 0) }, - function(a, b) { - lastSort.push(b > a ? 1 : (b < a ? -1 : 0)); - return b > a ? 1 : (b < a ? -1 : 0); + function (a, b) { + lastSort.push(b > a ? 1 : (b < a ? -1 : 0)) + return b > a ? 1 : (b < a ? -1 : 0) } ], [ - function(a, b) { - lastSort.push(a - b); - return a - b; + function (a, b) { + lastSort.push(a - b) + return a - b }, - function(a, b) { - lastSort.push(b - a); - return b - a; + function (a, b) { + lastSort.push(b - a) + return b - a } ], [ - function(a, b) { - lastSort.push((a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0)); - return (a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0); + function (a, b) { + lastSort.push((a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0)) + return (a + '') > (b + '') ? 1 : ((a + '') < (b + '') ? -1 : 0) }, - function(a, b) { - lastSort.push((b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0)); - return (b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0); + function (a, b) { + lastSort.push((b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0)) + return (b + '') > (a + '') ? 1 : ((b + '') < (a + '') ? -1 : 0) } ] - ]; + ] var sortArrs = [ [] - ]; + ] var sortKeys = [ [] - ]; + ] // Store first argument into sortArrs and sortKeys if an Object. // First Argument should be either a Javascript Array or an Object, otherwise function would return FALSE like in PHP if (Object.prototype.toString.call(arr) === '[object Array]') { - sortArrs[0] = arr; + sortArrs[0] = arr } else if (arr && typeof arr === 'object') { for (i in arr) { if (arr.hasOwnProperty(i)) { - sortKeys[0].push(i); - sortArrs[0].push(arr[i]); + sortKeys[0].push(i) + sortArrs[0].push(arr[i]) } } } else { - return false; + return false } // arrMainLength: Holds the length of the first array. All other arrays must be of equal length, otherwise function would return FALSE like in PHP // // sortComponents: Holds 2 indexes per every section of the array that can be sorted. As this is the start, the whole array can be sorted. - var arrMainLength = sortArrs[0].length; - var sortComponents = [0, arrMainLength]; + var arrMainLength = sortArrs[0].length + var sortComponents = [0, arrMainLength] // Loop through all other arguments, checking lengths and sort flags of arrays and adding them to the above variables. - var argl = arguments.length; + var argl = arguments.length for (j = 1; j < argl; j++) { if (Object.prototype.toString.call(arguments[j]) === '[object Array]') { - sortArrs[j] = arguments[j]; - sortFlag[j] = 0; + sortArrs[j] = arguments[j] + sortFlag[j] = 0 if (arguments[j].length !== arrMainLength) { - return false; + return false } } else if (arguments[j] && typeof arguments[j] === 'object') { - sortKeys[j] = []; - sortArrs[j] = []; - sortFlag[j] = 0; + sortKeys[j] = [] + sortArrs[j] = [] + sortFlag[j] = 0 for (i in arguments[j]) { if (arguments[j].hasOwnProperty(i)) { - sortKeys[j].push(i); - sortArrs[j].push(arguments[j][i]); + sortKeys[j].push(i) + sortArrs[j].push(arguments[j][i]) } } if (sortArrs[j].length !== arrMainLength) { - return false; + return false } } else if (typeof arguments[j] === 'string') { - var lFlag = sortFlag.pop(); + var lFlag = sortFlag.pop() // Keep extra parentheses around latter flags check to avoid minimization leading to CDATA closer if (typeof flags[arguments[j]] === 'undefined' || ((((flags[arguments[j]]) >>> 4) & (lFlag >>> 4)) > 0)) { - return false; + return false } - sortFlag.push(lFlag + flags[arguments[j]]); + sortFlag.push(lFlag + flags[arguments[j]]) } else { - return false; + return false } } for (i = 0; i !== arrMainLength; i++) { - thingsToSort.push(true); + thingsToSort.push(true) } // Sort all the arrays.... for (i in sortArrs) { if (sortArrs.hasOwnProperty(i)) { - lastSorts = []; - tmpArray = []; - elIndex = 0; - nLastSort = []; - lastSort = []; + lastSorts = [] + tmpArray = [] + elIndex = 0 + nLastSort = [] + lastSort = [] // If there are no sortComponents, then no more sorting is neeeded. Copy the array back to the argument. if (sortComponents.length === 0) { if (Object.prototype.toString.call(arguments[i]) === '[object Array]') { - args[i] = sortArrs[i]; + args[i] = sortArrs[i] } else { for (k in arguments[i]) { if (arguments[i].hasOwnProperty(k)) { - delete arguments[i][k]; + delete arguments[i][k] } } - sal = sortArrs[i].length; + sal = sortArrs[i].length for (j = 0, vkey = 0; j < sal; j++) { - vkey = sortKeys[i][j]; - args[i][vkey] = sortArrs[i][j]; + vkey = sortKeys[i][j] + args[i][vkey] = sortArrs[i][j] } } - delete sortArrs[i]; - delete sortKeys[i]; - continue; + delete sortArrs[i] + delete sortKeys[i] + continue } // Sort function for sorting. Either sorts asc or desc, regular/string or numeric. - var sFunction = sortFunctions[(sortFlag[i] & 3)][((sortFlag[i] & 8) > 0) ? 1 : 0]; + var sFunction = sortFunctions[(sortFlag[i] & 3)][((sortFlag[i] & 8) > 0) ? 1 : 0] // Sort current array. for (l = 0; l !== sortComponents.length; l += 2) { - tmpArray = sortArrs[i].slice(sortComponents[l], sortComponents[l + 1] + 1); - tmpArray.sort(sFunction); + tmpArray = sortArrs[i].slice(sortComponents[l], sortComponents[l + 1] + 1) + tmpArray.sort(sFunction) // Is there a better way to copy an array in Javascript? - lastSorts[l] = [].concat(lastSort); - elIndex = sortComponents[l]; + lastSorts[l] = [].concat(lastSort) + elIndex = sortComponents[l] for (g in tmpArray) { if (tmpArray.hasOwnProperty(g)) { - sortArrs[i][elIndex] = tmpArray[g]; - elIndex++; + sortArrs[i][elIndex] = tmpArray[g] + elIndex++ } } } // Duplicate the sorting of the current array on future arrays. - sFunction = sortDuplicator; + sFunction = sortDuplicator for (j in sortArrs) { if (sortArrs.hasOwnProperty(j)) { if (sortArrs[j] === sortArrs[i]) { - continue; + continue } for (l = 0; l !== sortComponents.length; l += 2) { - tmpArray = sortArrs[j].slice(sortComponents[l], sortComponents[l + 1] + 1); + tmpArray = sortArrs[j].slice(sortComponents[l], sortComponents[l + 1] + 1) // alert(l + ':' + nLastSort); - nLastSort = [].concat(lastSorts[l]); - tmpArray.sort(sFunction); - elIndex = sortComponents[l]; + nLastSort = [].concat(lastSorts[l]) + tmpArray.sort(sFunction) + elIndex = sortComponents[l] for (g in tmpArray) { if (tmpArray.hasOwnProperty(g)) { - sortArrs[j][elIndex] = tmpArray[g]; - elIndex++; + sortArrs[j][elIndex] = tmpArray[g] + elIndex++ } } } @@ -215,14 +215,14 @@ function array_multisort(arr) { for (j in sortKeys) { if (sortKeys.hasOwnProperty(j)) { for (l = 0; l !== sortComponents.length; l += 2) { - tmpArray = sortKeys[j].slice(sortComponents[l], sortComponents[l + 1] + 1); - nLastSort = [].concat(lastSorts[l]); - tmpArray.sort(sFunction); - elIndex = sortComponents[l]; + tmpArray = sortKeys[j].slice(sortComponents[l], sortComponents[l + 1] + 1) + nLastSort = [].concat(lastSorts[l]) + tmpArray.sort(sFunction) + elIndex = sortComponents[l] for (g in tmpArray) { if (tmpArray.hasOwnProperty(g)) { - sortKeys[j][elIndex] = tmpArray[g]; - elIndex++; + sortKeys[j][elIndex] = tmpArray[g] + elIndex++ } } } @@ -230,57 +230,57 @@ function array_multisort(arr) { } // Generate the next sortComponents - zlast = null; - sortComponents = []; + zlast = null + sortComponents = [] for (j in sortArrs[i]) { if (sortArrs[i].hasOwnProperty(j)) { if (!thingsToSort[j]) { if ((sortComponents.length & 1)) { - sortComponents.push(j - 1); + sortComponents.push(j - 1) } - zlast = null; - continue; + zlast = null + continue } if (!(sortComponents.length & 1)) { if (zlast !== null) { if (sortArrs[i][j] === zlast) { - sortComponents.push(j - 1); + sortComponents.push(j - 1) } else { - thingsToSort[j] = false; + thingsToSort[j] = false } } - zlast = sortArrs[i][j]; + zlast = sortArrs[i][j] } else { if (sortArrs[i][j] !== zlast) { - sortComponents.push(j - 1); - zlast = sortArrs[i][j]; + sortComponents.push(j - 1) + zlast = sortArrs[i][j] } } } } if (sortComponents.length & 1) { - sortComponents.push(j); + sortComponents.push(j) } if (Object.prototype.toString.call(arguments[i]) === '[object Array]') { - args[i] = sortArrs[i]; + args[i] = sortArrs[i] } else { for (j in arguments[i]) { if (arguments[i].hasOwnProperty(j)) { - delete arguments[i][j]; + delete arguments[i][j] } } - sal = sortArrs[i].length; + sal = sortArrs[i].length for (j = 0, vkey = 0; j < sal; j++) { - vkey = sortKeys[i][j]; - args[i][vkey] = sortArrs[i][j]; + vkey = sortKeys[i][j] + args[i][vkey] = sortArrs[i][j] } } - delete sortArrs[i]; - delete sortKeys[i]; + delete sortArrs[i] + delete sortKeys[i] } } - return true; -} \ No newline at end of file + return true +} diff --git a/functions/array/array_pad.js b/functions/array/array_pad.js index c37a66ecb2..8479e26095 100644 --- a/functions/array/array_pad.js +++ b/functions/array/array_pad.js @@ -1,4 +1,4 @@ -function array_pad(input, pad_size, pad_value) { +function array_pad (input, pad_size, pad_value) { // discuss at: http://phpjs.org/functions/array_pad/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: array_pad([ 7, 8, 9 ], 2, 'a'); @@ -14,21 +14,21 @@ function array_pad(input, pad_size, pad_value) { newArray = [], newLength, diff = 0, - i = 0; + i = 0 if (Object.prototype.toString.call(input) === '[object Array]' && !isNaN(pad_size)) { - newLength = ((pad_size < 0) ? (pad_size * -1) : pad_size); - diff = newLength - input.length; + newLength = ((pad_size < 0) ? (pad_size * -1) : pad_size) + diff = newLength - input.length if (diff > 0) { for (i = 0; i < diff; i++) { - newArray[i] = pad_value; + newArray[i] = pad_value } - pad = ((pad_size < 0) ? newArray.concat(input) : input.concat(newArray)); + pad = ((pad_size < 0) ? newArray.concat(input) : input.concat(newArray)) } else { - pad = input; + pad = input } } - return pad; -} \ No newline at end of file + return pad +} diff --git a/functions/array/array_pop.js b/functions/array/array_pop.js index eb94486920..a93fadfbb1 100644 --- a/functions/array/array_pop.js +++ b/functions/array/array_pop.js @@ -1,4 +1,4 @@ -function array_pop(inputArr) { +function array_pop (inputArr) { // discuss at: http://phpjs.org/functions/array_pop/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -20,28 +20,28 @@ function array_pop(inputArr) { // returns 2: {firstName: 'Kevin'} var key = '', - lastKey = ''; + lastKey = '' if (inputArr.hasOwnProperty('length')) { // Indexed if (!inputArr.length) { // Done popping, are we? - return null; + return null } - return inputArr.pop(); + return inputArr.pop() } else { // Associative for (key in inputArr) { if (inputArr.hasOwnProperty(key)) { - lastKey = key; + lastKey = key } } if (lastKey) { - var tmp = inputArr[lastKey]; - delete(inputArr[lastKey]); - return tmp; + var tmp = inputArr[lastKey] + delete (inputArr[lastKey]) + return tmp } else { - return null; + return null } } -} \ No newline at end of file +} diff --git a/functions/array/array_product.js b/functions/array/array_product.js index 83700f4301..5f9e583f4f 100644 --- a/functions/array/array_product.js +++ b/functions/array/array_product.js @@ -1,4 +1,4 @@ -function array_product(input) { +function array_product (input) { // discuss at: http://phpjs.org/functions/array_product/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: array_product([ 2, 4, 6, 8 ]); @@ -6,16 +6,16 @@ function array_product(input) { var idx = 0, product = 1, - il = 0; + il = 0 if (Object.prototype.toString.call(input) !== '[object Array]') { - return null; + return null } - il = input.length; + il = input.length while (idx < il) { - product *= (!isNaN(input[idx]) ? input[idx] : 0); - idx++; + product *= (!isNaN(input[idx]) ? input[idx] : 0) + idx++ } - return product; -} \ No newline at end of file + return product +} diff --git a/functions/array/array_push.js b/functions/array/array_push.js index c372bbb5de..35ceff0482 100644 --- a/functions/array/array_push.js +++ b/functions/array/array_push.js @@ -1,4 +1,4 @@ -function array_push(inputArr) { +function array_push (inputArr) { // discuss at: http://phpjs.org/functions/array_push/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Brett Zamir (http://brett-zamir.me) @@ -17,26 +17,26 @@ function array_push(inputArr) { allDigits = /^\d$/, size = 0, highestIdx = 0, - len = 0; + len = 0 if (inputArr.hasOwnProperty('length')) { for (i = 1; i < argc; i++) { - inputArr[inputArr.length] = argv[i]; + inputArr[inputArr.length] = argv[i] } - return inputArr.length; + return inputArr.length } // Associative (object) for (pr in inputArr) { if (inputArr.hasOwnProperty(pr)) { - ++len; + ++len if (pr.search(allDigits) !== -1) { - size = parseInt(pr, 10); - highestIdx = size > highestIdx ? size : highestIdx; + size = parseInt(pr, 10) + highestIdx = size > highestIdx ? size : highestIdx } } } for (i = 1; i < argc; i++) { - inputArr[++highestIdx] = argv[i]; + inputArr[++highestIdx] = argv[i] } - return len + i - 1; -} \ No newline at end of file + return len + i - 1 +} diff --git a/functions/array/array_rand.js b/functions/array/array_rand.js index ec3c031241..6650182ce4 100644 --- a/functions/array/array_rand.js +++ b/functions/array/array_rand.js @@ -1,38 +1,38 @@ -function array_rand(input, num_req) { +function array_rand (input, num_req) { // discuss at: http://phpjs.org/functions/array_rand/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: array_rand( ['Kevin'], 1 ); // returns 1: 0 - var indexes = []; - var ticks = num_req || 1; - var checkDuplicate = function(input, value) { + var indexes = [] + var ticks = num_req || 1 + var checkDuplicate = function (input, value) { var exist = false, index = 0, - il = input.length; + il = input.length while (index < il) { if (input[index] === value) { - exist = true; - break; + exist = true + break } - index++; + index++ } - return exist; - }; + return exist + } if (Object.prototype.toString.call(input) === '[object Array]' && ticks <= input.length) { while (true) { - var rand = Math.floor((Math.random() * input.length)); + var rand = Math.floor((Math.random() * input.length)) if (indexes.length === ticks) { - break; + break } if (!checkDuplicate(indexes, rand)) { - indexes.push(rand); + indexes.push(rand) } } } else { - indexes = null; + indexes = null } - return ((ticks == 1) ? indexes.join() : indexes); -} \ No newline at end of file + return ((ticks == 1) ? indexes.join() : indexes) +} diff --git a/functions/array/array_reduce.js b/functions/array/array_reduce.js index 83c6254595..4118aefa12 100644 --- a/functions/array/array_reduce.js +++ b/functions/array/array_reduce.js @@ -1,25 +1,25 @@ -function array_reduce(a_input, callback) { +function array_reduce (a_input, callback) { // discuss at: http://phpjs.org/functions/array_reduce/ // original by: Alfonso Jimenez (http://www.alfonsojimenez.com) // note: Takes a function as an argument, not a function's name // example 1: array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;}); // returns 1: 15 - var lon = a_input.length; + var lon = a_input.length var res = 0, - i = 0; - var tmp = []; + i = 0 + var tmp = [] for (i = 0; i < lon; i += 2) { - tmp[0] = a_input[i]; + tmp[0] = a_input[i] if (a_input[(i + 1)]) { - tmp[1] = a_input[(i + 1)]; + tmp[1] = a_input[(i + 1)] } else { - tmp[1] = 0; + tmp[1] = 0 } - res += callback.apply(null, tmp); - tmp = []; + res += callback.apply(null, tmp) + tmp = [] } - return res; -} \ No newline at end of file + return res +} diff --git a/functions/array/array_replace.js b/functions/array/array_replace.js index 91a146f5f6..e8a0d3ecb3 100644 --- a/functions/array/array_replace.js +++ b/functions/array/array_replace.js @@ -1,4 +1,4 @@ -function array_replace(arr) { +function array_replace (arr) { // discuss at: http://phpjs.org/functions/array_replace/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: array_replace(["orange", "banana", "apple", "raspberry"], {0 : "pineapple", 4 : "cherry"}, {0:"grape"}); @@ -7,21 +7,21 @@ function array_replace(arr) { var retObj = {}, i = 0, p = '', - argl = arguments.length; + argl = arguments.length if (argl < 2) { - throw new Error('There should be at least 2 arguments passed to array_replace()'); + throw new Error('There should be at least 2 arguments passed to array_replace()') } // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself for (p in arr) { - retObj[p] = arr[p]; + retObj[p] = arr[p] } for (i = 1; i < argl; i++) { for (p in arguments[i]) { - retObj[p] = arguments[i][p]; + retObj[p] = arguments[i][p] } } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/array/array_replace_recursive.js b/functions/array/array_replace_recursive.js index d1202e42e8..6ce2513d75 100644 --- a/functions/array/array_replace_recursive.js +++ b/functions/array/array_replace_recursive.js @@ -1,4 +1,4 @@ -function array_replace_recursive(arr) { +function array_replace_recursive (arr) { // discuss at: http://phpjs.org/functions/array_replace_recursive/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: array_replace_recursive({'citrus' : ["orange"], 'berries' : ["blackberry", "raspberry"]}, {'citrus' : ['pineapple'], 'berries' : ['blueberry']}); @@ -7,25 +7,25 @@ function array_replace_recursive(arr) { var retObj = {}, i = 0, p = '', - argl = arguments.length; + argl = arguments.length if (argl < 2) { - throw new Error('There should be at least 2 arguments passed to array_replace_recursive()'); + throw new Error('There should be at least 2 arguments passed to array_replace_recursive()') } // Although docs state that the arguments are passed in by reference, it seems they are not altered, but rather the copy that is returned (just guessing), so we make a copy here, instead of acting on arr itself for (p in arr) { - retObj[p] = arr[p]; + retObj[p] = arr[p] } for (i = 1; i < argl; i++) { for (p in arguments[i]) { if (retObj[p] && typeof retObj[p] === 'object') { - retObj[p] = this.array_replace_recursive(retObj[p], arguments[i][p]); + retObj[p] = this.array_replace_recursive(retObj[p], arguments[i][p]) } else { - retObj[p] = arguments[i][p]; + retObj[p] = arguments[i][p] } } } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/array/array_reverse.js b/functions/array/array_reverse.js index 241372d8fe..9e7ddf304f 100644 --- a/functions/array/array_reverse.js +++ b/functions/array/array_reverse.js @@ -1,4 +1,4 @@ -function array_reverse(array, preserve_keys) { +function array_reverse (array, preserve_keys) { // discuss at: http://phpjs.org/functions/array_reverse/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Karol Kowalski @@ -7,36 +7,36 @@ function array_reverse(array, preserve_keys) { var isArray = Object.prototype.toString.call(array) === '[object Array]', tmp_arr = preserve_keys ? {} : [], - key; + key if (isArray && !preserve_keys) { return array.slice(0) - .reverse(); + .reverse() } if (preserve_keys) { - var keys = []; + var keys = [] for (key in array) { // if (array.hasOwnProperty(key)) { - keys.push(key); + keys.push(key) // } } - var i = keys.length; + var i = keys.length while (i--) { - key = keys[i]; + key = keys[i] // FIXME: don't rely on browsers keeping keys in insertion order // it's implementation specific // eg. the result will differ from expected in Google Chrome - tmp_arr[key] = array[key]; + tmp_arr[key] = array[key] } } else { for (key in array) { // if (array.hasOwnProperty(key)) { - tmp_arr.unshift(array[key]); + tmp_arr.unshift(array[key]) // } } } - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/array/array_search.js b/functions/array/array_search.js index d5a272bf7a..aa9d1caaf5 100644 --- a/functions/array/array_search.js +++ b/functions/array/array_search.js @@ -1,4 +1,4 @@ -function array_search(needle, haystack, argStrict) { +function array_search (needle, haystack, argStrict) { // discuss at: http://phpjs.org/functions/array_search/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Brett Zamir (http://brett-zamir.me) @@ -13,11 +13,11 @@ function array_search(needle, haystack, argStrict) { // returns 2: '3' var strict = !!argStrict, - key = ''; + key = '' if (haystack && typeof haystack === 'object' && haystack.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array - return haystack.search(needle, argStrict); + return haystack.search(needle, argStrict) } if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp @@ -26,26 +26,26 @@ function array_search(needle, haystack, argStrict) { var flags = 'i' + (needle.global ? 'g' : '') + (needle.multiline ? 'm' : '') + // sticky is FF only - (needle.sticky ? 'y' : ''); - needle = new RegExp(needle.source, flags); + (needle.sticky ? 'y' : '') + needle = new RegExp(needle.source, flags) } for (key in haystack) { if (haystack.hasOwnProperty(key)) { if (needle.test(haystack[key])) { - return key; + return key } } } - return false; + return false } for (key in haystack) { if (haystack.hasOwnProperty(key)) { if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { - return key; + return key } } } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/array/array_shift.js b/functions/array/array_shift.js index 6fa50719b4..75c9ce6ea2 100644 --- a/functions/array/array_shift.js +++ b/functions/array/array_shift.js @@ -1,4 +1,4 @@ -function array_shift(inputArr) { +function array_shift (inputArr) { // discuss at: http://phpjs.org/functions/array_shift/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Martijn Wieringa @@ -11,27 +11,27 @@ function array_shift(inputArr) { pr = '', allDigits = /^\d$/, int_ct = -1, - _checkToUpIndices = function(arr, ct, key) { + _checkToUpIndices = function (arr, ct, key) { // Deal with situation, e.g., if encounter index 4 and try to set it to 0, but 0 exists later in loop (need to // increment all subsequent (skipping current key, since we need its value below) until find unused) if (arr[ct] !== undefined) { - var tmp = ct; - ct += 1; + var tmp = ct + ct += 1 if (ct === key) { - ct += 1; + ct += 1 } - ct = _checkToUpIndices(arr, ct, key); - arr[ct] = arr[tmp]; - delete arr[tmp]; + ct = _checkToUpIndices(arr, ct, key) + arr[ct] = arr[tmp] + delete arr[tmp] } - return ct; - }; + return ct + } if (inputArr.length === 0) { - return null; + return null } if (inputArr.length > 0) { - return inputArr.shift(); + return inputArr.shift() } /* @@ -63,4 +63,4 @@ function array_shift(inputArr) { } return shift; */ -} \ No newline at end of file +} diff --git a/functions/array/array_slice.js b/functions/array/array_slice.js index e61143fb33..1e854250b7 100644 --- a/functions/array/array_slice.js +++ b/functions/array/array_slice.js @@ -1,4 +1,4 @@ -function array_slice(arr, offst, lgth, preserve_keys) { +function array_slice (arr, offst, lgth, preserve_keys) { // discuss at: http://phpjs.org/functions/array_slice/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: is_int @@ -11,61 +11,61 @@ function array_slice(arr, offst, lgth, preserve_keys) { // returns 2: {2: 'c', 3: 'd'} /* - if ('callee' in arr && 'length' in arr) { - arr = Array.prototype.slice.call(arr); - } - */ + if ('callee' in arr && 'length' in arr) { + arr = Array.prototype.slice.call(arr); + } + */ - var key = ''; + var key = '' if (Object.prototype.toString.call(arr) !== '[object Array]' || (preserve_keys && offst !== 0)) { // Assoc. array as input or if required as output var lgt = 0, - newAssoc = {}; + newAssoc = {} for (key in arr) { - //if (key !== 'length') { - lgt += 1; - newAssoc[key] = arr[key]; - //} + // if (key !== 'length') { + lgt += 1 + newAssoc[key] = arr[key] + // } } - arr = newAssoc; + arr = newAssoc - offst = (offst < 0) ? lgt + offst : offst; - lgth = lgth === undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth; + offst = (offst < 0) ? lgt + offst : offst + lgth = lgth === undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth - var assoc = {}; + var assoc = {} var start = false, it = -1, arrlgth = 0, - no_pk_idx = 0; + no_pk_idx = 0 for (key in arr) { - ++it; + ++it if (arrlgth >= lgth) { - break; + break } if (it == offst) { - start = true; + start = true } if (!start) { - continue; - }++arrlgth; + continue + }++arrlgth if (this.is_int(key) && !preserve_keys) { - assoc[no_pk_idx++] = arr[key]; + assoc[no_pk_idx++] = arr[key] } else { - assoc[key] = arr[key]; + assoc[key] = arr[key] } } // Make as array-like object (though length will not be dynamic) - //assoc.length = arrlgth; - return assoc; + // assoc.length = arrlgth; + return assoc } if (lgth === undefined) { - return arr.slice(offst); + return arr.slice(offst) } else if (lgth >= 0) { - return arr.slice(offst, offst + lgth); + return arr.slice(offst, offst + lgth) } else { - return arr.slice(offst, lgth); + return arr.slice(offst, lgth) } -} \ No newline at end of file +} diff --git a/functions/array/array_splice.js b/functions/array/array_splice.js index 250f8bb83e..2208e38978 100644 --- a/functions/array/array_splice.js +++ b/functions/array/array_splice.js @@ -1,4 +1,4 @@ -function array_splice(arr, offst, lgth, replacement) { +function array_splice (arr, offst, lgth, replacement) { // discuss at: http://phpjs.org/functions/array_splice/ // original by: Brett Zamir (http://brett-zamir.me) // input by: Theriault @@ -20,33 +20,33 @@ function array_splice(arr, offst, lgth, replacement) { // example 3: array_splice(input, -1, 1, ["black", "maroon"]); // returns 3: ["yellow"] - var _checkToUpIndices = function(arr, ct, key) { + var _checkToUpIndices = function (arr, ct, key) { // Deal with situation, e.g., if encounter index 4 and try to set it to 0, but 0 exists later in loop (need to // increment all subsequent (skipping current key, since we need its value below) until find unused) if (arr[ct] !== undefined) { - var tmp = ct; - ct += 1; + var tmp = ct + ct += 1 if (ct === key) { - ct += 1; + ct += 1 } - ct = _checkToUpIndices(arr, ct, key); - arr[ct] = arr[tmp]; - delete arr[tmp]; + ct = _checkToUpIndices(arr, ct, key) + arr[ct] = arr[tmp] + delete arr[tmp] } - return ct; - }; + return ct + } if (replacement && typeof replacement !== 'object') { - replacement = [replacement]; + replacement = [replacement] } if (lgth === undefined) { - lgth = offst >= 0 ? arr.length - offst : -offst; + lgth = offst >= 0 ? arr.length - offst : -offst } else if (lgth < 0) { - lgth = (offst >= 0 ? arr.length - offst : -offst) + lgth; + lgth = (offst >= 0 ? arr.length - offst : -offst) + lgth } if (Object.prototype.toString.call(arr) !== '[object Array]') { - /*if (arr.length !== undefined) { + /* if (arr.length !== undefined) { // Deal with array-like objects as input delete arr.length; }*/ @@ -55,58 +55,58 @@ function array_splice(arr, offst, lgth, replacement) { rmvd = [], rmvdObj = {}, repl_ct = -1, - int_ct = -1; + int_ct = -1 var returnArr = true, rmvd_ct = 0, rmvd_lgth = 0, - key = ''; + key = '' // rmvdObj.length = 0; for (key in arr) { // Can do arr.__count__ in some browsers - lgt += 1; + lgt += 1 } - offst = (offst >= 0) ? offst : lgt + offst; + offst = (offst >= 0) ? offst : lgt + offst for (key in arr) { - ct += 1; + ct += 1 if (ct < offst) { if (this.is_int(key)) { - int_ct += 1; + int_ct += 1 if (parseInt(key, 10) === int_ct) { // Key is already numbered ok, so don't need to change key for value - continue; + continue } // Deal with situation, e.g., - _checkToUpIndices(arr, int_ct, key); + _checkToUpIndices(arr, int_ct, key) // if encounter index 4 and try to set it to 0, but 0 exists later in loop - arr[int_ct] = arr[key]; - delete arr[key]; + arr[int_ct] = arr[key] + delete arr[key] } - continue; + continue } if (returnArr && this.is_int(key)) { - rmvd.push(arr[key]); + rmvd.push(arr[key]) // PHP starts over here too - rmvdObj[rmvd_ct++] = arr[key]; + rmvdObj[rmvd_ct++] = arr[key] } else { - rmvdObj[key] = arr[key]; - returnArr = false; + rmvdObj[key] = arr[key] + returnArr = false } - rmvd_lgth += 1; + rmvd_lgth += 1 // rmvdObj.length += 1; if (replacement && replacement[++repl_ct]) { - arr[key] = replacement[repl_ct]; + arr[key] = replacement[repl_ct] } else { - delete arr[key]; + delete arr[key] } } // Make (back) into an array-like object // arr.length = lgt - rmvd_lgth + (replacement ? replacement.length : 0); - return returnArr ? rmvd : rmvdObj; + return returnArr ? rmvd : rmvdObj } if (replacement) { - replacement.unshift(offst, lgth); - return Array.prototype.splice.apply(arr, replacement); + replacement.unshift(offst, lgth) + return Array.prototype.splice.apply(arr, replacement) } - return arr.splice(offst, lgth); -} \ No newline at end of file + return arr.splice(offst, lgth) +} diff --git a/functions/array/array_sum.js b/functions/array/array_sum.js index a52b939251..4ecba5402a 100644 --- a/functions/array/array_sum.js +++ b/functions/array/array_sum.js @@ -1,4 +1,4 @@ -function array_sum(array) { +function array_sum (array) { // discuss at: http://phpjs.org/functions/array_sum/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Nate @@ -11,23 +11,23 @@ function array_sum(array) { // example 2: array_sum(total); // returns 2: 67.2 - var key, sum = 0; + var key, sum = 0 if (array && typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array - return array.sum.apply(array, Array.prototype.slice.call(arguments, 0)); + return array.sum.apply(array, Array.prototype.slice.call(arguments, 0)) } // input sanitation if (typeof array !== 'object') { - return null; + return null } for (key in array) { if (!isNaN(parseFloat(array[key]))) { - sum += parseFloat(array[key]); + sum += parseFloat(array[key]) } } - return sum; -} \ No newline at end of file + return sum +} diff --git a/functions/array/array_udiff.js b/functions/array/array_udiff.js index 7da518cd59..cab94cb1bf 100644 --- a/functions/array/array_udiff.js +++ b/functions/array/array_udiff.js @@ -1,4 +1,4 @@ -function array_udiff(arr1) { +function array_udiff (arr1) { // discuss at: http://phpjs.org/functions/array_udiff/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -12,22 +12,22 @@ function array_udiff(arr1) { arr = '', i = 1, k1 = '', - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb(arr[k], arr1[k1]) === 0) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_udiff_assoc.js b/functions/array/array_udiff_assoc.js index f089ca4456..9fe7afb9a5 100644 --- a/functions/array/array_udiff_assoc.js +++ b/functions/array/array_udiff_assoc.js @@ -1,4 +1,4 @@ -function array_udiff_assoc(arr1) { +function array_udiff_assoc (arr1) { // discuss at: http://phpjs.org/functions/array_udiff_assoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: array_udiff_assoc({0: 'kevin', 1: 'van', 2: 'Zonneveld'}, {0: 'Kevin', 4: 'van', 5: 'Zonneveld'}, function (f_string1, f_string2){var string1 = (f_string1+'').toLowerCase(); var string2 = (f_string2+'').toLowerCase(); if (string1 > string2) return 1; if (string1 == string2) return 0; return -1;}); @@ -10,22 +10,22 @@ function array_udiff_assoc(arr1) { arr = {}, i = 1, k1 = '', - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb(arr[k], arr1[k1]) === 0 && k === k1) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_udiff_uassoc.js b/functions/array/array_udiff_uassoc.js index e7477e49f9..6ca6e580f3 100644 --- a/functions/array/array_udiff_uassoc.js +++ b/functions/array/array_udiff_uassoc.js @@ -1,4 +1,4 @@ -function array_udiff_uassoc(arr1) { +function array_udiff_uassoc (arr1) { // discuss at: http://phpjs.org/functions/array_udiff_uassoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -14,25 +14,25 @@ function array_udiff_uassoc(arr1) { k1 = '', i = 1, k = '', - arr = {}; + arr = {} cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb cb0 = (typeof cb0 === 'string') ? this.window[cb0] : (Object.prototype.toString.call(cb0) === '[object Array]') ? - this.window[cb0[0]][cb0[1]] : cb0; + this.window[cb0[0]][cb0[1]] : cb0 arr1keys: for (k1 in arr1) { for (i = 1; i < arglm2; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb0(arr[k], arr1[k1]) === 0 && cb(k, k1) === 0) { // If it reaches here, it was found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_uintersect.js b/functions/array/array_uintersect.js index 579e033ab8..7c63bc6eee 100644 --- a/functions/array/array_uintersect.js +++ b/functions/array/array_uintersect.js @@ -1,4 +1,4 @@ -function array_uintersect(arr1) { +function array_uintersect (arr1) { // discuss at: http://phpjs.org/functions/array_uintersect/ // original by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Demosthenes Koptsis @@ -14,27 +14,27 @@ function array_uintersect(arr1) { k1 = '', i = 1, arr = {}, - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb(arr[k], arr1[k1]) === 0) { if (i === arglm2) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_uintersect_assoc.js b/functions/array/array_uintersect_assoc.js index 4a0c9a6dbd..230adab9ab 100644 --- a/functions/array/array_uintersect_assoc.js +++ b/functions/array/array_uintersect_assoc.js @@ -1,4 +1,4 @@ -function array_uintersect_assoc(arr1) { +function array_uintersect_assoc (arr1) { // discuss at: http://phpjs.org/functions/array_uintersect_assoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -13,27 +13,27 @@ function array_uintersect_assoc(arr1) { k1 = '', i = 1, arr = {}, - k = ''; + k = '' cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < arglm1; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (k === k1 && cb(arr[k], arr1[k1]) === 0) { if (i === arglm2) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_uintersect_uassoc.js b/functions/array/array_uintersect_uassoc.js index 104bd39992..411e599547 100644 --- a/functions/array/array_uintersect_uassoc.js +++ b/functions/array/array_uintersect_uassoc.js @@ -1,4 +1,4 @@ -function array_uintersect_uassoc(arr1) { +function array_uintersect_uassoc (arr1) { // discuss at: http://phpjs.org/functions/array_uintersect_uassoc/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'} @@ -14,29 +14,29 @@ function array_uintersect_uassoc(arr1) { k1 = '', i = 1, k = '', - arr = {}; + arr = {} cb = (typeof cb === 'string') ? this.window[cb] : (Object.prototype.toString.call(cb) === '[object Array]') ? this.window[ - cb[0]][cb[1]] : cb; + cb[0]][cb[1]] : cb cb0 = (typeof cb0 === 'string') ? this.window[cb0] : (Object.prototype.toString.call(cb0) === '[object Array]') ? - this.window[cb0[0]][cb0[1]] : cb0; + this.window[cb0[0]][cb0[1]] : cb0 arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < arglm2; i++) { - arr = arguments[i]; + arr = arguments[i] for (k in arr) { if (cb0(arr[k], arr1[k1]) === 0 && cb(k, k1) === 0) { if (i === arguments.length - 3) { - retArr[k1] = arr1[k1]; + retArr[k1] = arr1[k1] } // If the innermost loop always leads at least once to an equal value, continue the loop until done - continue arrs; + continue arrs } } // If it reaches here, it wasn't found in at least one array, so try next value - continue arr1keys; + continue arr1keys } } - return retArr; -} \ No newline at end of file + return retArr +} diff --git a/functions/array/array_unique.js b/functions/array/array_unique.js index ba81cbb9c6..645d468a30 100644 --- a/functions/array/array_unique.js +++ b/functions/array/array_unique.js @@ -1,4 +1,4 @@ -function array_unique(inputArr) { +function array_unique (inputArr) { // discuss at: http://phpjs.org/functions/array_unique/ // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // input by: duncan @@ -17,28 +17,28 @@ function array_unique(inputArr) { var key = '', tmp_arr2 = {}, - val = ''; + val = '' - var __array_search = function(needle, haystack) { - var fkey = ''; + var __array_search = function (needle, haystack) { + var fkey = '' for (fkey in haystack) { if (haystack.hasOwnProperty(fkey)) { if ((haystack[fkey] + '') === (needle + '')) { - return fkey; + return fkey } } } - return false; - }; + return false + } for (key in inputArr) { if (inputArr.hasOwnProperty(key)) { - val = inputArr[key]; + val = inputArr[key] if (false === __array_search(val, tmp_arr2)) { - tmp_arr2[key] = val; + tmp_arr2[key] = val } } } - return tmp_arr2; -} \ No newline at end of file + return tmp_arr2 +} diff --git a/functions/array/array_unshift.js b/functions/array/array_unshift.js index 38b0f37dd3..07e970e56e 100644 --- a/functions/array/array_unshift.js +++ b/functions/array/array_unshift.js @@ -1,4 +1,4 @@ -function array_unshift(array) { +function array_unshift (array) { // discuss at: http://phpjs.org/functions/array_unshift/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Martijn Wieringa @@ -7,11 +7,11 @@ function array_unshift(array) { // example 1: array_unshift(['van', 'Zonneveld'], 'Kevin'); // returns 1: 3 - var i = arguments.length; + var i = arguments.length while (--i !== 0) { - arguments[0].unshift(arguments[i]); + arguments[0].unshift(arguments[i]) } - return arguments[0].length; -} \ No newline at end of file + return arguments[0].length +} diff --git a/functions/array/array_values.js b/functions/array/array_values.js index bd1ee47c5d..c356ca002e 100644 --- a/functions/array/array_values.js +++ b/functions/array/array_values.js @@ -1,4 +1,4 @@ -function array_values(input) { +function array_values (input) { // discuss at: http://phpjs.org/functions/array_values/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Brett Zamir (http://brett-zamir.me) @@ -6,16 +6,16 @@ function array_values(input) { // returns 1: {0: 'Kevin', 1: 'van Zonneveld'} var tmp_arr = [], - key = ''; + key = '' if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array - return input.values(); + return input.values() } for (key in input) { - tmp_arr[tmp_arr.length] = input[key]; + tmp_arr[tmp_arr.length] = input[key] } - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/array/array_walk.js b/functions/array/array_walk.js index cdabd8c9ff..c9bd98b73f 100644 --- a/functions/array/array_walk.js +++ b/functions/array/array_walk.js @@ -1,4 +1,4 @@ -function array_walk(array, funcname, userdata) { +function array_walk (array, funcname, userdata) { // discuss at: http://phpjs.org/functions/array_walk/ // original by: Johnny Mast (http://www.phpvrouwen.nl) // bugfixed by: David @@ -20,17 +20,17 @@ function array_walk(array, funcname, userdata) { // example 5: array_walk(arr, [window, 'prompt']); // returns 5: '[object Object]' - var key, value, ini; + var key, value, ini if (!array || typeof array !== 'object') { - return false; + return false } if (typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array if (arguments.length > 2) { - return array.walk(funcname, userdata); + return array.walk(funcname, userdata) } else { - return array.walk(funcname); + return array.walk(funcname) } } @@ -38,57 +38,57 @@ function array_walk(array, funcname, userdata) { if (typeof funcname === 'function') { for (key in array) { if (arguments.length > 2) { - funcname(array[key], key, userdata); + funcname(array[key], key, userdata) } else { - funcname(array[key], key); + funcname(array[key], key) } } } else if (typeof funcname === 'string') { - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; - ini = this.php_js.ini['phpjs.no-eval']; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} + ini = this.php_js.ini['phpjs.no-eval'] if (ini && ( parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value.toLowerCase() !== 'off') )) { if (arguments.length > 2) { for (key in array) { - this.window[funcname](array[key], key, userdata); + this.window[funcname](array[key], key, userdata) } } else { for (key in array) { - this.window[funcname](array[key], key); + this.window[funcname](array[key], key) } } } else { if (arguments.length > 2) { for (key in array) { - eval(funcname + '(array[key], key, userdata)'); + eval(funcname + '(array[key], key, userdata)') } } else { for (key in array) { - eval(funcname + '(array[key], key)'); + eval(funcname + '(array[key], key)') } } } } else if (funcname && typeof funcname === 'object' && funcname.length === 2) { var obj = funcname[0], - func = funcname[1]; + func = funcname[1] if (arguments.length > 2) { for (key in array) { - obj[func](array[key], key, userdata); + obj[func](array[key], key, userdata) } } else { for (key in array) { - obj[func](array[key], key); + obj[func](array[key], key) } } } else { - return false; + return false } } catch (e) { - return false; + return false } - return true; -} \ No newline at end of file + return true +} diff --git a/functions/array/array_walk_recursive.js b/functions/array/array_walk_recursive.js index d55e0952a6..314d0d8efd 100644 --- a/functions/array/array_walk_recursive.js +++ b/functions/array/array_walk_recursive.js @@ -1,4 +1,4 @@ -function array_walk_recursive(array, funcname, userdata) { +function array_walk_recursive (array, funcname, userdata) { // discuss at: http://phpjs.org/functions/array_walk_recursive/ // original by: Johnny Mast (http://www.phpvrouwen.nl) // example 1: array_walk_recursive ({'a': 'b', 'c': {'d': 'e'}}, 'void', 'userdata'); @@ -6,23 +6,23 @@ function array_walk_recursive(array, funcname, userdata) { // example 2: array_walk_recursive ('a', 'void', 'userdata'); // returns 2: false - var key; + var key if (typeof array !== 'object') { - return false; + return false } for (key in array) { if (typeof array[key] === 'object') { - return this.array_walk_recursive(array[key], funcname, userdata); + return this.array_walk_recursive(array[key], funcname, userdata) } if (typeof userdata !== 'undefined') { - eval(funcname + '( array [key] , key , userdata )'); + eval(funcname + '( array [key] , key , userdata )') } else { - eval(funcname + '( userdata ) '); + eval(funcname + '( userdata ) ') } } - return true; -} \ No newline at end of file + return true +} diff --git a/functions/array/arsort.js b/functions/array/arsort.js index b007fbb58e..240400b22a 100644 --- a/functions/array/arsort.js +++ b/functions/array/arsort.js @@ -1,4 +1,4 @@ -function arsort(inputArr, sort_flags) { +function arsort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/arsort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -35,71 +35,71 @@ function arsort(inputArr, sort_flags) { valArrLen = 0, k, i, ret, sorter, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(b, a); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(b, a) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return (a - b); - }; - break; - case 'SORT_REGULAR': + sorter = function (a, b) { + return (a - b) + } + break + case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(b, a) { - var aFloat = parseFloat(a), + default: + sorter = function (b, a) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Get key and value arrays for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - valArr.push([k, inputArr[k]]); + valArr.push([k, inputArr[k]]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function(a, b) { - return sorter(a[1], b[1]); - }); + valArr.sort(function (a, b) { + return sorter(a[1], b[1]) + }) // Repopulate the old array for (i = 0, valArrLen = valArr.length; i < valArrLen; i++) { - populateArr[valArr[i][0]] = valArr[i][1]; + populateArr[valArr[i][0]] = valArr[i][1] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/asort.js b/functions/array/asort.js index 3bb6c6b7a4..46578eb141 100644 --- a/functions/array/asort.js +++ b/functions/array/asort.js @@ -1,4 +1,4 @@ -function asort(inputArr, sort_flags) { +function asort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/asort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -40,72 +40,72 @@ function asort(inputArr, sort_flags) { valArrLen = 0, k, i, ret, sorter, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(a, b); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(a, b) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return (a - b); - }; - break; - case 'SORT_REGULAR': + sorter = function (a, b) { + return (a - b) + } + break + case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(a, b) { - var aFloat = parseFloat(a), + default: + sorter = function (a, b) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Get key and value arrays for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - valArr.push([k, inputArr[k]]); + valArr.push([k, inputArr[k]]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function(a, b) { - return sorter(a[1], b[1]); - }); + valArr.sort(function (a, b) { + return sorter(a[1], b[1]) + }) // Repopulate the old array for (i = 0, valArrLen = valArr.length; i < valArrLen; i++) { - populateArr[valArr[i][0]] = valArr[i][1]; + populateArr[valArr[i][0]] = valArr[i][1] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/compact.js b/functions/array/compact.js index d7f2f9c486..e6ec9140fb 100644 --- a/functions/array/compact.js +++ b/functions/array/compact.js @@ -1,4 +1,4 @@ -function compact() { +function compact () { // discuss at: http://phpjs.org/functions/compact/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // improved by: Jack @@ -9,25 +9,25 @@ function compact() { // returns 1: {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'} var matrix = {}, - that = this; + that = this - var process = function(value) { + var process = function (value) { var i = 0, l = value.length, - key_value = ''; + key_value = '' for (i = 0; i < l; i++) { - key_value = value[i]; + key_value = value[i] if (Object.prototype.toString.call(key_value) === '[object Array]') { - process(key_value); + process(key_value) } else { if (typeof that.window[key_value] !== 'undefined') { - matrix[key_value] = that.window[key_value]; + matrix[key_value] = that.window[key_value] } } } - return true; - }; + return true + } - process(arguments); - return matrix; -} \ No newline at end of file + process(arguments) + return matrix +} diff --git a/functions/array/count.js b/functions/array/count.js index 1bb93a7202..bd5101454c 100644 --- a/functions/array/count.js +++ b/functions/array/count.js @@ -1,4 +1,4 @@ -function count(mixed_var, mode) { +function count (mixed_var, mode) { // discuss at: http://phpjs.org/functions/count/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Waldo Malqui Silva (http://waldo.malqui.info) @@ -11,30 +11,30 @@ function count(mixed_var, mode) { // example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); // returns 2: 6 - var key, cnt = 0; + var key, cnt = 0 if (mixed_var === null || typeof mixed_var === 'undefined') { - return 0; + return 0 } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object) { - return 1; + return 1 } if (mode === 'COUNT_RECURSIVE') { - mode = 1; + mode = 1 } if (mode != 1) { - mode = 0; + mode = 0 } for (key in mixed_var) { if (mixed_var.hasOwnProperty(key)) { - cnt++; + cnt++ if (mode == 1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object)) { - cnt += this.count(mixed_var[key], 1); + cnt += this.count(mixed_var[key], 1) } } } - return cnt; -} \ No newline at end of file + return cnt +} diff --git a/functions/array/current.js b/functions/array/current.js index f55a236a4b..23529ba56d 100644 --- a/functions/array/current.js +++ b/functions/array/current.js @@ -1,4 +1,4 @@ -function current(arr) { +function current (arr) { // discuss at: http://phpjs.org/functions/current/ // original by: Brett Zamir (http://brett-zamir.me) // note: Uses global: php_js to store the array pointer @@ -6,36 +6,36 @@ function current(arr) { // example 1: current(transport); // returns 1: 'foot' - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var arrpos = pointers.indexOf(arr); - var cursor = pointers[arrpos + 1]; + var arrpos = pointers.indexOf(arr) + var cursor = pointers[arrpos + 1] if (Object.prototype.toString.call(arr) === '[object Array]') { - return arr[cursor] || false; + return arr[cursor] || false } - var ct = 0; + var ct = 0 for (var k in arr) { if (ct === cursor) { - return arr[k]; + return arr[k] } - ct++; + ct++ } // Empty - return false; -} \ No newline at end of file + return false +} diff --git a/functions/array/each.js b/functions/array/each.js index c5b86a7fa5..def2e98dc5 100644 --- a/functions/array/each.js +++ b/functions/array/each.js @@ -1,4 +1,4 @@ -function each(arr) { +function each (arr) { // discuss at: http://phpjs.org/functions/each/ // original by: Ates Goral (http://magnetiq.com) // revised by: Brett Zamir (http://brett-zamir.me) @@ -6,62 +6,62 @@ function each(arr) { // example 1: each({a: "apple", b: "balloon"}); // returns 1: {0: "a", 1: "apple", key: "a", value: "apple"} - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var arrpos = pointers.indexOf(arr); - var cursor = pointers[arrpos + 1]; - var pos = 0; + var arrpos = pointers.indexOf(arr) + var cursor = pointers[arrpos + 1] + var pos = 0 if (Object.prototype.toString.call(arr) !== '[object Array]') { - var ct = 0; + var ct = 0 for (var k in arr) { if (ct === cursor) { - pointers[arrpos + 1] += 1; + pointers[arrpos + 1] += 1 if (each.returnArrayOnly) { - return [k, arr[k]]; + return [k, arr[k]] } else { return { - 1 : arr[k], - value : arr[k], - 0 : k, - key : k - }; + 1: arr[k], + value: arr[k], + 0: k, + key: k + } } } - ct++; + ct++ } // Empty - return false; + return false } if (arr.length === 0 || cursor === arr.length) { - return false; + return false } - pos = cursor; - pointers[arrpos + 1] += 1; + pos = cursor + pointers[arrpos + 1] += 1 if (each.returnArrayOnly) { - return [pos, arr[pos]]; + return [pos, arr[pos]] } else { return { - 1 : arr[pos], - value : arr[pos], - 0 : pos, - key : pos - }; + 1: arr[pos], + value: arr[pos], + 0: pos, + key: pos + } } -} \ No newline at end of file +} diff --git a/functions/array/end.js b/functions/array/end.js index 3fdfbff9d1..744e7880e6 100644 --- a/functions/array/end.js +++ b/functions/array/end.js @@ -1,4 +1,4 @@ -function end(arr) { +function end (arr) { // discuss at: http://phpjs.org/functions/end/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Legaev Andrey @@ -12,42 +12,42 @@ function end(arr) { // example 2: end(['Kevin', 'van', 'Zonneveld']); // returns 2: 'Zonneveld' - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var arrpos = pointers.indexOf(arr); + var arrpos = pointers.indexOf(arr) if (Object.prototype.toString.call(arr) !== '[object Array]') { - var ct = 0; - var val; + var ct = 0 + var val for (var k in arr) { - ct++; - val = arr[k]; + ct++ + val = arr[k] } if (ct === 0) { // Empty - return false; + return false } - pointers[arrpos + 1] = ct - 1; - return val; + pointers[arrpos + 1] = ct - 1 + return val } if (arr.length === 0) { - return false; + return false } - pointers[arrpos + 1] = arr.length - 1; - return arr[pointers[arrpos + 1]]; -} \ No newline at end of file + pointers[arrpos + 1] = arr.length - 1 + return arr[pointers[arrpos + 1]] +} diff --git a/functions/array/in_array.js b/functions/array/in_array.js index ce262c64e9..1db1d54b68 100644 --- a/functions/array/in_array.js +++ b/functions/array/in_array.js @@ -1,4 +1,4 @@ -function in_array(needle, haystack, argStrict) { +function in_array (needle, haystack, argStrict) { // discuss at: http://phpjs.org/functions/in_array/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: vlado houba @@ -17,24 +17,24 @@ function in_array(needle, haystack, argStrict) { // returns 4: false var key = '', - strict = !!argStrict; + strict = !!argStrict - //we prevent the double check (strict && arr[key] === ndl) || (!strict && arr[key] == ndl) - //in just one for, in order to improve the performance - //deciding wich type of comparation will do before walk array + // we prevent the double check (strict && arr[key] === ndl) || (!strict && arr[key] == ndl) + // in just one for, in order to improve the performance + // deciding wich type of comparation will do before walk array if (strict) { for (key in haystack) { if (haystack[key] === needle) { - return true; + return true } } } else { for (key in haystack) { if (haystack[key] == needle) { - return true; + return true } } } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/array/key.js b/functions/array/key.js index b75b5c4fc0..0f93d12624 100644 --- a/functions/array/key.js +++ b/functions/array/key.js @@ -1,4 +1,4 @@ -function key(arr) { +function key (arr) { // discuss at: http://phpjs.org/functions/key/ // original by: Brett Zamir (http://brett-zamir.me) // input by: Riddler (http://www.frontierwebdev.com/) @@ -8,39 +8,39 @@ function key(arr) { // example 1: key(array); // returns 1: 'fruit1' - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var cursor = pointers[pointers.indexOf(arr) + 1]; + var cursor = pointers[pointers.indexOf(arr) + 1] if (Object.prototype.toString.call(arr) !== '[object Array]') { - var ct = 0; + var ct = 0 for (var k in arr) { if (ct === cursor) { - return k; + return k } - ct++; + ct++ } // Empty - return false; + return false } if (arr.length === 0) { - return false; + return false } - return cursor; -} \ No newline at end of file + return cursor +} diff --git a/functions/array/krsort.js b/functions/array/krsort.js index d37861df94..fd4f80bf6d 100644 --- a/functions/array/krsort.js +++ b/functions/array/krsort.js @@ -1,4 +1,4 @@ -function krsort(inputArr, sort_flags) { +function krsort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/krsort/ // original by: GeekFG (http://geekfg.blogspot.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -32,75 +32,75 @@ function krsort(inputArr, sort_flags) { keys = [], sorter, i, k, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(b, a); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(b, a) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return (b - a); - }; - break; - case 'SORT_REGULAR': + sorter = function (a, b) { + return (b - a) + } + break + case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(b, a) { - var aFloat = parseFloat(a), + default: + sorter = function (b, a) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // Make a list of key names for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - keys.push(k); + keys.push(k) } } - keys.sort(sorter); + keys.sort(sorter) // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Rebuild array with sorted key names for (i = 0; i < keys.length; i++) { - k = keys[i]; - tmp_arr[k] = inputArr[k]; + k = keys[i] + tmp_arr[k] = inputArr[k] if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } for (i in tmp_arr) { if (tmp_arr.hasOwnProperty(i)) { - populateArr[i] = tmp_arr[i]; + populateArr[i] = tmp_arr[i] } } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/ksort.js b/functions/array/ksort.js index 8c3eae72fc..840574dfdd 100644 --- a/functions/array/ksort.js +++ b/functions/array/ksort.js @@ -1,4 +1,4 @@ -function ksort(inputArr, sort_flags) { +function ksort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/ksort/ // original by: GeekFG (http://geekfg.blogspot.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -33,74 +33,74 @@ function ksort(inputArr, sort_flags) { keys = [], sorter, i, k, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(a, b); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(a, b) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, original by the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return ((a + 0) - (b + 0)); - }; - break; + sorter = function (a, b) { + return ((a + 0) - (b + 0)) + } + break // case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(a, b) { - var aFloat = parseFloat(a), + default: + sorter = function (a, b) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // Make a list of key names for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - keys.push(k); + keys.push(k) } } - keys.sort(sorter); + keys.sort(sorter) // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Rebuild array with sorted key names for (i = 0; i < keys.length; i++) { - k = keys[i]; - tmp_arr[k] = inputArr[k]; + k = keys[i] + tmp_arr[k] = inputArr[k] if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } for (i in tmp_arr) { if (tmp_arr.hasOwnProperty(i)) { - populateArr[i] = tmp_arr[i]; + populateArr[i] = tmp_arr[i] } } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/natcasesort.js b/functions/array/natcasesort.js index 0665949ab3..0bbd34964b 100644 --- a/functions/array/natcasesort.js +++ b/functions/array/natcasesort.js @@ -1,4 +1,4 @@ -function natcasesort(inputArr) { +function natcasesort (inputArr) { // discuss at: http://phpjs.org/functions/natcasesort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -22,33 +22,33 @@ function natcasesort(inputArr) { var valArr = [], k, i, ret, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Get key and value arrays for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - valArr.push([k, inputArr[k]]); + valArr.push([k, inputArr[k]]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function(a, b) { - return that.strnatcasecmp(a[1], b[1]); - }); + valArr.sort(function (a, b) { + return that.strnatcasecmp(a[1], b[1]) + }) // Repopulate the old array for (i = 0; i < valArr.length; i++) { - populateArr[valArr[i][0]] = valArr[i][1]; + populateArr[valArr[i][0]] = valArr[i][1] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/natsort.js b/functions/array/natsort.js index 148ea9bb7b..6793a60198 100644 --- a/functions/array/natsort.js +++ b/functions/array/natsort.js @@ -1,4 +1,4 @@ -function natsort(inputArr) { +function natsort (inputArr) { // discuss at: http://phpjs.org/functions/natsort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -20,33 +20,33 @@ function natsort(inputArr) { var valArr = [], k, i, ret, that = this, strictForIn = false, - populateArr = {}; + populateArr = {} // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Get key and value arrays for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - valArr.push([k, inputArr[k]]); + valArr.push([k, inputArr[k]]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function(a, b) { - return that.strnatcmp(a[1], b[1]); - }); + valArr.sort(function (a, b) { + return that.strnatcmp(a[1], b[1]) + }) // Repopulate the old array for (i = 0; i < valArr.length; i++) { - populateArr[valArr[i][0]] = valArr[i][1]; + populateArr[valArr[i][0]] = valArr[i][1] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/next.js b/functions/array/next.js index 50dd481b91..65d3ea0972 100644 --- a/functions/array/next.js +++ b/functions/array/next.js @@ -1,4 +1,4 @@ -function next(arr) { +function next (arr) { // discuss at: http://phpjs.org/functions/next/ // original by: Brett Zamir (http://brett-zamir.me) // note: Uses global: php_js to store the array pointer @@ -7,41 +7,41 @@ function next(arr) { // example 1: next(transport); // returns 1: 'car' - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var arrpos = pointers.indexOf(arr); - var cursor = pointers[arrpos + 1]; + var arrpos = pointers.indexOf(arr) + var cursor = pointers[arrpos + 1] if (Object.prototype.toString.call(arr) !== '[object Array]') { - var ct = 0; + var ct = 0 for (var k in arr) { if (ct === cursor + 1) { - pointers[arrpos + 1] += 1; - return arr[k]; + pointers[arrpos + 1] += 1 + return arr[k] } - ct++; + ct++ } // End - return false; + return false } if (arr.length === 0 || cursor === (arr.length - 1)) { - return false; + return false } - pointers[arrpos + 1] += 1; - return arr[pointers[arrpos + 1]]; -} \ No newline at end of file + pointers[arrpos + 1] += 1 + return arr[pointers[arrpos + 1]] +} diff --git a/functions/array/pos.js b/functions/array/pos.js index 848ae2a598..2327cc0e66 100644 --- a/functions/array/pos.js +++ b/functions/array/pos.js @@ -1,4 +1,4 @@ -function pos(arr) { +function pos (arr) { // discuss at: http://phpjs.org/functions/pos/ // original by: Brett Zamir (http://brett-zamir.me) // note: Uses global: php_js to store the array pointer @@ -7,5 +7,5 @@ function pos(arr) { // example 1: pos(transport); // returns 1: 'foot' - return this.current(arr); -} \ No newline at end of file + return this.current(arr) +} diff --git a/functions/array/prev.js b/functions/array/prev.js index fee49129a1..4c41bda033 100644 --- a/functions/array/prev.js +++ b/functions/array/prev.js @@ -1,4 +1,4 @@ -function prev(arr) { +function prev (arr) { // discuss at: http://phpjs.org/functions/prev/ // original by: Brett Zamir (http://brett-zamir.me) // note: Uses global: php_js to store the array pointer @@ -6,40 +6,40 @@ function prev(arr) { // example 1: prev(transport); // returns 1: false - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } - var arrpos = pointers.indexOf(arr); - var cursor = pointers[arrpos + 1]; + var arrpos = pointers.indexOf(arr) + var cursor = pointers[arrpos + 1] if (pointers.indexOf(arr) === -1 || cursor === 0) { - return false; + return false } if (Object.prototype.toString.call(arr) !== '[object Array]') { - var ct = 0; + var ct = 0 for (var k in arr) { if (ct === cursor - 1) { - pointers[arrpos + 1] -= 1; - return arr[k]; + pointers[arrpos + 1] -= 1 + return arr[k] } - ct++; + ct++ } // Shouldn't reach here } if (arr.length === 0) { - return false; + return false } - pointers[arrpos + 1] -= 1; - return arr[pointers[arrpos + 1]]; -} \ No newline at end of file + pointers[arrpos + 1] -= 1 + return arr[pointers[arrpos + 1]] +} diff --git a/functions/array/range.js b/functions/array/range.js index ddec22fedb..8825a17600 100644 --- a/functions/array/range.js +++ b/functions/array/range.js @@ -1,4 +1,4 @@ -function range(low, high, step) { +function range (low, high, step) { // discuss at: http://phpjs.org/functions/range/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: range ( 0, 12 ); @@ -10,35 +10,35 @@ function range(low, high, step) { // example 4: range( 'c', 'a' ); // returns 4: ['c', 'b', 'a'] - var matrix = []; - var inival, endval, plus; - var walker = step || 1; - var chars = false; + var matrix = [] + var inival, endval, plus + var walker = step || 1 + var chars = false if (!isNaN(low) && !isNaN(high)) { - inival = low; - endval = high; + inival = low + endval = high } else if (isNaN(low) && isNaN(high)) { - chars = true; - inival = low.charCodeAt(0); - endval = high.charCodeAt(0); + chars = true + inival = low.charCodeAt(0) + endval = high.charCodeAt(0) } else { - inival = (isNaN(low) ? 0 : low); - endval = (isNaN(high) ? 0 : high); + inival = (isNaN(low) ? 0 : low) + endval = (isNaN(high) ? 0 : high) } - plus = ((inival > endval) ? false : true); + plus = ((inival > endval) ? false : true) if (plus) { while (inival <= endval) { - matrix.push(((chars) ? String.fromCharCode(inival) : inival)); - inival += walker; + matrix.push(((chars) ? String.fromCharCode(inival) : inival)) + inival += walker } } else { while (inival >= endval) { - matrix.push(((chars) ? String.fromCharCode(inival) : inival)); - inival -= walker; + matrix.push(((chars) ? String.fromCharCode(inival) : inival)) + inival -= walker } } - return matrix; -} \ No newline at end of file + return matrix +} diff --git a/functions/array/reset.js b/functions/array/reset.js index 806134655b..953c4ced61 100644 --- a/functions/array/reset.js +++ b/functions/array/reset.js @@ -1,4 +1,4 @@ -function reset(arr) { +function reset (arr) { // discuss at: http://phpjs.org/functions/reset/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Legaev Andrey @@ -7,40 +7,40 @@ function reset(arr) { // example 1: reset({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}); // returns 1: 'Kevin' - this.php_js = this.php_js || {}; - this.php_js.pointers = this.php_js.pointers || []; - var indexOf = function(value) { + this.php_js = this.php_js || {} + this.php_js.pointers = this.php_js.pointers || [] + var indexOf = function (value) { for (var i = 0, length = this.length; i < length; i++) { if (this[i] === value) { - return i; + return i } } - return -1; - }; + return -1 + } // END REDUNDANT - var pointers = this.php_js.pointers; + var pointers = this.php_js.pointers if (!pointers.indexOf) { - pointers.indexOf = indexOf; + pointers.indexOf = indexOf } if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } - var arrpos = pointers.indexOf(arr); + var arrpos = pointers.indexOf(arr) if (Object.prototype.toString.call(arr) !== '[object Array]') { for (var k in arr) { if (pointers.indexOf(arr) === -1) { - pointers.push(arr, 0); + pointers.push(arr, 0) } else { - pointers[arrpos + 1] = 0; + pointers[arrpos + 1] = 0 } - return arr[k]; + return arr[k] } // Empty - return false; + return false } if (arr.length === 0) { - return false; + return false } - pointers[arrpos + 1] = 0; - return arr[pointers[arrpos + 1]]; -} \ No newline at end of file + pointers[arrpos + 1] = 0 + return arr[pointers[arrpos + 1]] +} diff --git a/functions/array/rsort.js b/functions/array/rsort.js index 63a2db784f..4b473ec675 100644 --- a/functions/array/rsort.js +++ b/functions/array/rsort.js @@ -1,4 +1,4 @@ -function rsort(inputArr, sort_flags) { +function rsort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/rsort/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // revised by: Brett Zamir (http://brett-zamir.me) @@ -36,74 +36,74 @@ function rsort(inputArr, sort_flags) { sorter = false, that = this, strictForIn = false, - populateArr = []; + populateArr = [] switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(b, a); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(b, a) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return (b - a); - }; - break; - case 'SORT_REGULAR': + sorter = function (a, b) { + return (b - a) + } + break + case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(b, a) { - var aFloat = parseFloat(a), + default: + sorter = function (b, a) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // BEGIN REDUNDANT try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } - this.php_js.ini = this.php_js.ini || {}; + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { - valArr.push(inputArr[k]); + valArr.push(inputArr[k]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(sorter); + valArr.sort(sorter) for (i = 0; i < valArr.length; i++) { // Repopulate the old array - populateArr[i] = valArr[i]; + populateArr[i] = valArr[i] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/shuffle.js b/functions/array/shuffle.js index fcb8ecbd72..b3ab5e444c 100644 --- a/functions/array/shuffle.js +++ b/functions/array/shuffle.js @@ -1,4 +1,4 @@ -function shuffle(inputArr) { +function shuffle (inputArr) { // discuss at: http://phpjs.org/functions/shuffle/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -29,33 +29,33 @@ function shuffle(inputArr) { k = '', i = 0, strictForIn = false, - populateArr = []; + populateArr = [] for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { - valArr.push(inputArr[k]); + valArr.push(inputArr[k]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function() { - return 0.5 - Math.random(); - }); + valArr.sort(function () { + return 0.5 - Math.random() + }) // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr for (i = 0; i < valArr.length; i++) { // Repopulate the old array - populateArr[i] = valArr[i]; + populateArr[i] = valArr[i] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/sizeof.js b/functions/array/sizeof.js index d03e667a89..c0f6735574 100644 --- a/functions/array/sizeof.js +++ b/functions/array/sizeof.js @@ -1,4 +1,4 @@ -function sizeof(mixed_var, mode) { +function sizeof (mixed_var, mode) { // discuss at: http://phpjs.org/functions/sizeof/ // original by: Philip Peterson // depends on: count @@ -7,5 +7,5 @@ function sizeof(mixed_var, mode) { // example 2: sizeof({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE'); // returns 2: 6 - return this.count(mixed_var, mode); -} \ No newline at end of file + return this.count(mixed_var, mode) +} diff --git a/functions/array/sort.js b/functions/array/sort.js index 19a7c3f759..4356245063 100644 --- a/functions/array/sort.js +++ b/functions/array/sort.js @@ -1,4 +1,4 @@ -function sort(inputArr, sort_flags) { +function sort (inputArr, sort_flags) { // discuss at: http://phpjs.org/functions/sort/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // revised by: Brett Zamir (http://brett-zamir.me) @@ -37,74 +37,74 @@ function sort(inputArr, sort_flags) { sorter = false, that = this, strictForIn = false, - populateArr = []; + populateArr = [] switch (sort_flags) { - case 'SORT_STRING': + case 'SORT_STRING': // compare items as strings - sorter = function(a, b) { - return that.strnatcmp(a, b); - }; - break; - case 'SORT_LOCALE_STRING': + sorter = function (a, b) { + return that.strnatcmp(a, b) + } + break + case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) - var loc = this.i18n_loc_get_default(); - sorter = this.php_js.i18nLocales[loc].sorting; - break; - case 'SORT_NUMERIC': + var loc = this.i18n_loc_get_default() + sorter = this.php_js.i18nLocales[loc].sorting + break + case 'SORT_NUMERIC': // compare items numerically - sorter = function(a, b) { - return (a - b); - }; - break; - case 'SORT_REGULAR': + sorter = function (a, b) { + return (a - b) + } + break + case 'SORT_REGULAR': // compare items normally (don't change types) - default: - sorter = function(a, b) { - var aFloat = parseFloat(a), + default: + sorter = function (a, b) { + var aFloat = parseFloat(a), bFloat = parseFloat(b), aNumeric = aFloat + '' === a, - bNumeric = bFloat + '' === b; - if (aNumeric && bNumeric) { - return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0; + bNumeric = bFloat + '' === b + if (aNumeric && bNumeric) { + return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0 } else if (aNumeric && !bNumeric) { - return 1; + return 1 } else if (!aNumeric && bNumeric) { - return -1; + return -1 + } + return a > b ? 1 : a < b ? -1 : 0 } - return a > b ? 1 : a < b ? -1 : 0; - }; - break; + break } // BEGIN REDUNDANT try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } - this.php_js.ini = this.php_js.ini || {}; + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { - valArr.push(inputArr[k]); + valArr.push(inputArr[k]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(sorter); + valArr.sort(sorter) for (i = 0; i < valArr.length; i++) { // Repopulate the old array - populateArr[i] = valArr[i]; + populateArr[i] = valArr[i] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/uasort.js b/functions/array/uasort.js index 0074842177..90a40bed67 100644 --- a/functions/array/uasort.js +++ b/functions/array/uasort.js @@ -1,4 +1,4 @@ -function uasort(inputArr, sorter) { +function uasort (inputArr, sorter) { // discuss at: http://phpjs.org/functions/uasort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -21,39 +21,39 @@ function uasort(inputArr, sorter) { tempKeyVal, tempValue, ret, k = '', i = 0, strictForIn = false, - populateArr = {}; + populateArr = {} if (typeof sorter === 'string') { - sorter = this[sorter]; + sorter = this[sorter] } else if (Object.prototype.toString.call(sorter) === '[object Array]') { - sorter = this[sorter[0]][sorter[1]]; + sorter = this[sorter[0]][sorter[1]] } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { - valArr.push([k, inputArr[k]]); + valArr.push([k, inputArr[k]]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } - valArr.sort(function(a, b) { - return sorter(a[1], b[1]); - }); + valArr.sort(function (a, b) { + return sorter(a[1], b[1]) + }) for (i = 0; i < valArr.length; i++) { // Repopulate the old array - populateArr[valArr[i][0]] = valArr[i][1]; + populateArr[valArr[i][0]] = valArr[i][1] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/uksort.js b/functions/array/uksort.js index 525c62c2f7..ad24aa7d01 100644 --- a/functions/array/uksort.js +++ b/functions/array/uksort.js @@ -1,4 +1,4 @@ -function uksort(inputArr, sorter) { +function uksort (inputArr, sorter) { // discuss at: http://phpjs.org/functions/uksort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -22,50 +22,50 @@ function uksort(inputArr, sorter) { i = 0, k = '', strictForIn = false, - populateArr = {}; + populateArr = {} if (typeof sorter === 'string') { - sorter = this.window[sorter]; + sorter = this.window[sorter] } // Make a list of key names for (k in inputArr) { if (inputArr.hasOwnProperty(k)) { - keys.push(k); + keys.push(k) } } // Sort key names try { if (sorter) { - keys.sort(sorter); + keys.sort(sorter) } else { - keys.sort(); + keys.sort() } } catch (e) { - return false; + return false } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr // Rebuild array with sorted key names for (i = 0; i < keys.length; i++) { - k = keys[i]; - tmp_arr[k] = inputArr[k]; + k = keys[i] + tmp_arr[k] = inputArr[k] if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } for (i in tmp_arr) { if (tmp_arr.hasOwnProperty(i)) { - populateArr[i] = tmp_arr[i]; + populateArr[i] = tmp_arr[i] } } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/array/usort.js b/functions/array/usort.js index 6a6f9d433e..d1e24d3d58 100644 --- a/functions/array/usort.js +++ b/functions/array/usort.js @@ -1,4 +1,4 @@ -function usort(inputArr, sorter) { +function usort (inputArr, sorter) { // discuss at: http://phpjs.org/functions/usort/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -20,40 +20,40 @@ function usort(inputArr, sorter) { k = '', i = 0, strictForIn = false, - populateArr = {}; + populateArr = {} if (typeof sorter === 'string') { - sorter = this[sorter]; + sorter = this[sorter] } else if (Object.prototype.toString.call(sorter) === '[object Array]') { - sorter = this[sorter[0]][sorter[1]]; + sorter = this[sorter[0]][sorter[1]] } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value && this.php_js - .ini['phpjs.strictForIn'].local_value !== 'off'; - populateArr = strictForIn ? inputArr : populateArr; + .ini['phpjs.strictForIn'].local_value !== 'off' + populateArr = strictForIn ? inputArr : populateArr for (k in inputArr) { // Get key and value arrays if (inputArr.hasOwnProperty(k)) { - valArr.push(inputArr[k]); + valArr.push(inputArr[k]) if (strictForIn) { - delete inputArr[k]; + delete inputArr[k] } } } try { - valArr.sort(sorter); + valArr.sort(sorter) } catch (e) { - return false; + return false } for (i = 0; i < valArr.length; i++) { // Repopulate the old array - populateArr[i] = valArr[i]; + populateArr[i] = valArr[i] } - return strictForIn || populateArr; -} \ No newline at end of file + return strictForIn || populateArr +} diff --git a/functions/bc/bcadd.js b/functions/bc/bcadd.js index 5042403b40..ca51f3f453 100644 --- a/functions/bc/bcadd.js +++ b/functions/bc/bcadd.js @@ -1,4 +1,4 @@ -function bcadd(left_operand, right_operand, scale) { +function bcadd (left_operand, right_operand, scale) { // discuss at: http://phpjs.org/functions/bcadd/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,28 +6,28 @@ function bcadd(left_operand, right_operand, scale) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - var first, second, result; + var first, second, result if (typeof scale === 'undefined') { - scale = libbcmath.scale; + scale = libbcmath.scale } - scale = ((scale < 0) ? 0 : scale); + scale = ((scale < 0) ? 0 : scale) // create objects - first = libbcmath.bc_init_num(); - second = libbcmath.bc_init_num(); - result = libbcmath.bc_init_num(); + first = libbcmath.bc_init_num() + second = libbcmath.bc_init_num() + result = libbcmath.bc_init_num() - first = libbcmath.php_str2num(left_operand.toString()); - second = libbcmath.php_str2num(right_operand.toString()); + first = libbcmath.php_str2num(left_operand.toString()) + second = libbcmath.php_str2num(right_operand.toString()) - result = libbcmath.bc_add(first, second, scale); + result = libbcmath.bc_add(first, second, scale) if (result.n_scale > scale) { - result.n_scale = scale; + result.n_scale = scale } - return result.toString(); -} \ No newline at end of file + return result.toString() +} diff --git a/functions/bc/bccomp.js b/functions/bc/bccomp.js index e31a0646b1..c27df3a243 100644 --- a/functions/bc/bccomp.js +++ b/functions/bc/bccomp.js @@ -1,4 +1,4 @@ -function bccomp(left_operand, right_operand, scale) { +function bccomp (left_operand, right_operand, scale) { // discuss at: http://phpjs.org/functions/bccomp/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,21 +6,21 @@ function bccomp(left_operand, right_operand, scale) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - //bc_num - var first, second; + // bc_num + var first, second if (typeof scale === 'undefined') { - scale = libbcmath.scale; + scale = libbcmath.scale } - scale = ((scale < 0) ? 0 : scale); + scale = ((scale < 0) ? 0 : scale) - first = libbcmath.bc_init_num(); - second = libbcmath.bc_init_num(); + first = libbcmath.bc_init_num() + second = libbcmath.bc_init_num() // note bc_ not php_str2num - first = libbcmath.bc_str2num(left_operand.toString(), scale); + first = libbcmath.bc_str2num(left_operand.toString(), scale) // note bc_ not php_str2num - second = libbcmath.bc_str2num(right_operand.toString(), scale); - return libbcmath.bc_compare(first, second, scale); -} \ No newline at end of file + second = libbcmath.bc_str2num(right_operand.toString(), scale) + return libbcmath.bc_compare(first, second, scale) +} diff --git a/functions/bc/bcdiv.js b/functions/bc/bcdiv.js index de96ac4357..7d21e4695a 100644 --- a/functions/bc/bcdiv.js +++ b/functions/bc/bcdiv.js @@ -1,4 +1,4 @@ -function bcdiv(left_operand, right_operand, scale) { +function bcdiv (left_operand, right_operand, scale) { // discuss at: http://phpjs.org/functions/bcdiv/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,30 +6,30 @@ function bcdiv(left_operand, right_operand, scale) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - var first, second, result; + var first, second, result if (typeof scale === 'undefined') { - scale = libbcmath.scale; + scale = libbcmath.scale } - scale = ((scale < 0) ? 0 : scale); + scale = ((scale < 0) ? 0 : scale) // create objects - first = libbcmath.bc_init_num(); - second = libbcmath.bc_init_num(); - result = libbcmath.bc_init_num(); + first = libbcmath.bc_init_num() + second = libbcmath.bc_init_num() + result = libbcmath.bc_init_num() - first = libbcmath.php_str2num(left_operand.toString()); - second = libbcmath.php_str2num(right_operand.toString()); + first = libbcmath.php_str2num(left_operand.toString()) + second = libbcmath.php_str2num(right_operand.toString()) - result = libbcmath.bc_divide(first, second, scale); + result = libbcmath.bc_divide(first, second, scale) if (result === -1) { // error - throw new Error(11, '(BC) Division by zero'); + throw new Error(11, '(BC) Division by zero') } if (result.n_scale > scale) { - result.n_scale = scale; + result.n_scale = scale } - return result.toString(); -} \ No newline at end of file + return result.toString() +} diff --git a/functions/bc/bcmul.js b/functions/bc/bcmul.js index 341edca333..fc4f0e9e41 100644 --- a/functions/bc/bcmul.js +++ b/functions/bc/bcmul.js @@ -1,4 +1,4 @@ -function bcmul(left_operand, right_operand, scale) { +function bcmul (left_operand, right_operand, scale) { // discuss at: http://phpjs.org/functions/bcmul/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,27 +6,27 @@ function bcmul(left_operand, right_operand, scale) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - var first, second, result; + var first, second, result if (typeof scale === 'undefined') { - scale = libbcmath.scale; + scale = libbcmath.scale } - scale = ((scale < 0) ? 0 : scale); + scale = ((scale < 0) ? 0 : scale) // create objects - first = libbcmath.bc_init_num(); - second = libbcmath.bc_init_num(); - result = libbcmath.bc_init_num(); + first = libbcmath.bc_init_num() + second = libbcmath.bc_init_num() + result = libbcmath.bc_init_num() - first = libbcmath.php_str2num(left_operand.toString()); - second = libbcmath.php_str2num(right_operand.toString()); + first = libbcmath.php_str2num(left_operand.toString()) + second = libbcmath.php_str2num(right_operand.toString()) - result = libbcmath.bc_multiply(first, second, scale); + result = libbcmath.bc_multiply(first, second, scale) if (result.n_scale > scale) { - result.n_scale = scale; + result.n_scale = scale } - return result.toString(); -} \ No newline at end of file + return result.toString() +} diff --git a/functions/bc/bcround.js b/functions/bc/bcround.js index d8aae6a503..f9996b14c5 100644 --- a/functions/bc/bcround.js +++ b/functions/bc/bcround.js @@ -1,4 +1,4 @@ -function bcround(val, precision) { +function bcround (val, precision) { // discuss at: http://phpjs.org/functions/bcround/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,47 +6,47 @@ function bcround(val, precision) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - var temp, result, digit; - var right_operand; + var temp, result, digit + var right_operand // create number - temp = libbcmath.bc_init_num(); - temp = libbcmath.php_str2num(val.toString()); + temp = libbcmath.bc_init_num() + temp = libbcmath.php_str2num(val.toString()) // check if any rounding needs if (precision >= temp.n_scale) { // nothing to round, just add the zeros. while (temp.n_scale < precision) { - temp.n_value[temp.n_len + temp.n_scale] = 0; - temp.n_scale++; + temp.n_value[temp.n_len + temp.n_scale] = 0 + temp.n_scale++ } - return temp.toString(); + return temp.toString() } // get the digit we are checking (1 after the precision) // loop through digits after the precision marker - digit = temp.n_value[temp.n_len + precision]; + digit = temp.n_value[temp.n_len + precision] - right_operand = libbcmath.bc_init_num(); - right_operand = libbcmath.bc_new_num(1, precision); + right_operand = libbcmath.bc_init_num() + right_operand = libbcmath.bc_new_num(1, precision) if (digit >= 5) { - //round away from zero by adding 1 (or -1) at the "precision".. ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5) - right_operand.n_value[right_operand.n_len + right_operand.n_scale - 1] = 1; + // round away from zero by adding 1 (or -1) at the "precision".. ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5) + right_operand.n_value[right_operand.n_len + right_operand.n_scale - 1] = 1 if (temp.n_sign == libbcmath.MINUS) { // round down - right_operand.n_sign = libbcmath.MINUS; + right_operand.n_sign = libbcmath.MINUS } - result = libbcmath.bc_add(temp, right_operand, precision); + result = libbcmath.bc_add(temp, right_operand, precision) } else { // leave-as-is.. just truncate it. - result = temp; + result = temp } if (result.n_scale > precision) { - result.n_scale = precision; + result.n_scale = precision } - return result.toString(); -} \ No newline at end of file + return result.toString() +} diff --git a/functions/bc/bcscale.js b/functions/bc/bcscale.js index 11b95f87f7..ff09d46028 100644 --- a/functions/bc/bcscale.js +++ b/functions/bc/bcscale.js @@ -1,4 +1,4 @@ -function bcscale(scale) { +function bcscale (scale) { // discuss at: http://phpjs.org/functions/bcscale/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)this. // depends on: _phpjs_shared_bc @@ -6,15 +6,15 @@ function bcscale(scale) { // returns 1: 3 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - scale = parseInt(scale, 10); + scale = parseInt(scale, 10) if (isNaN(scale)) { - return false; + return false } if (scale < 0) { - return false; + return false } - libbcmath.scale = scale; - return true; -} \ No newline at end of file + libbcmath.scale = scale + return true +} diff --git a/functions/bc/bcsub.js b/functions/bc/bcsub.js index 31f9457f77..d9d394bca0 100644 --- a/functions/bc/bcsub.js +++ b/functions/bc/bcsub.js @@ -1,4 +1,4 @@ -function bcsub(left_operand, right_operand, scale) { +function bcsub (left_operand, right_operand, scale) { // discuss at: http://phpjs.org/functions/bcsub/ // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/) // depends on: _phpjs_shared_bc @@ -6,28 +6,28 @@ function bcsub(left_operand, right_operand, scale) { // returns 1: -1 // todo: implement these testcases - var libbcmath = this._phpjs_shared_bc(); + var libbcmath = this._phpjs_shared_bc() - var first, second, result; + var first, second, result if (typeof scale === 'undefined') { - scale = libbcmath.scale; + scale = libbcmath.scale } - scale = ((scale < 0) ? 0 : scale); + scale = ((scale < 0) ? 0 : scale) // create objects - first = libbcmath.bc_init_num(); - second = libbcmath.bc_init_num(); - result = libbcmath.bc_init_num(); + first = libbcmath.bc_init_num() + second = libbcmath.bc_init_num() + result = libbcmath.bc_init_num() - first = libbcmath.php_str2num(left_operand.toString()); - second = libbcmath.php_str2num(right_operand.toString()); + first = libbcmath.php_str2num(left_operand.toString()) + second = libbcmath.php_str2num(right_operand.toString()) - result = libbcmath.bc_sub(first, second, scale); + result = libbcmath.bc_sub(first, second, scale) if (result.n_scale > scale) { - result.n_scale = scale; + result.n_scale = scale } - return result.toString(); -} \ No newline at end of file + return result.toString() +} diff --git a/functions/ctype/ctype_alnum.js b/functions/ctype/ctype_alnum.js index 74fc884180..eba8cdd955 100644 --- a/functions/ctype/ctype_alnum.js +++ b/functions/ctype/ctype_alnum.js @@ -1,4 +1,4 @@ -function ctype_alnum(text) { +function ctype_alnum (text) { // discuss at: http://phpjs.org/functions/ctype_alnum/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_alnum(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.an) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.an) !== -1 +} diff --git a/functions/ctype/ctype_alpha.js b/functions/ctype/ctype_alpha.js index 71067cb96d..2c0ff6038b 100644 --- a/functions/ctype/ctype_alpha.js +++ b/functions/ctype/ctype_alpha.js @@ -1,4 +1,4 @@ -function ctype_alpha(text) { +function ctype_alpha (text) { // discuss at: http://phpjs.org/functions/ctype_alpha/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_alpha(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.al) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.al) !== -1 +} diff --git a/functions/ctype/ctype_cntrl.js b/functions/ctype/ctype_cntrl.js index a843241949..9efc8e68c7 100644 --- a/functions/ctype/ctype_cntrl.js +++ b/functions/ctype/ctype_cntrl.js @@ -1,4 +1,4 @@ -function ctype_cntrl(text) { +function ctype_cntrl (text) { // discuss at: http://phpjs.org/functions/ctype_cntrl/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -8,11 +8,11 @@ function ctype_cntrl(text) { // returns 2: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.ct) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.ct) !== -1 +} diff --git a/functions/ctype/ctype_digit.js b/functions/ctype/ctype_digit.js index b21a298990..bbc39fc8a3 100644 --- a/functions/ctype/ctype_digit.js +++ b/functions/ctype/ctype_digit.js @@ -1,4 +1,4 @@ -function ctype_digit(text) { +function ctype_digit (text) { // discuss at: http://phpjs.org/functions/ctype_digit/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_digit(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.dg) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.dg) !== -1 +} diff --git a/functions/ctype/ctype_graph.js b/functions/ctype/ctype_graph.js index bb45d46d23..866fff4fce 100644 --- a/functions/ctype/ctype_graph.js +++ b/functions/ctype/ctype_graph.js @@ -1,4 +1,4 @@ -function ctype_graph(text) { +function ctype_graph (text) { // discuss at: http://phpjs.org/functions/ctype_graph/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_graph(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.gr) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.gr) !== -1 +} diff --git a/functions/ctype/ctype_lower.js b/functions/ctype/ctype_lower.js index 8a01f0b1a7..80e66ba0a5 100644 --- a/functions/ctype/ctype_lower.js +++ b/functions/ctype/ctype_lower.js @@ -1,4 +1,4 @@ -function ctype_lower(text) { +function ctype_lower (text) { // discuss at: http://phpjs.org/functions/ctype_lower/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_lower(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lw) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lw) !== -1 +} diff --git a/functions/ctype/ctype_print.js b/functions/ctype/ctype_print.js index c2c03ba56d..9663433f38 100644 --- a/functions/ctype/ctype_print.js +++ b/functions/ctype/ctype_print.js @@ -1,4 +1,4 @@ -function ctype_print(text) { +function ctype_print (text) { // discuss at: http://phpjs.org/functions/ctype_print/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_print(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pr) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pr) !== -1 +} diff --git a/functions/ctype/ctype_punct.js b/functions/ctype/ctype_punct.js index 935e36a9c4..f6e3e36453 100644 --- a/functions/ctype/ctype_punct.js +++ b/functions/ctype/ctype_punct.js @@ -1,4 +1,4 @@ -function ctype_punct(text) { +function ctype_punct (text) { // discuss at: http://phpjs.org/functions/ctype_punct/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_punct(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pu) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.pu) !== -1 +} diff --git a/functions/ctype/ctype_space.js b/functions/ctype/ctype_space.js index 5373af9d7f..a4dd256056 100644 --- a/functions/ctype/ctype_space.js +++ b/functions/ctype/ctype_space.js @@ -1,4 +1,4 @@ -function ctype_space(text) { +function ctype_space (text) { // discuss at: http://phpjs.org/functions/ctype_space/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_space(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.sp) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.sp) !== -1 +} diff --git a/functions/ctype/ctype_upper.js b/functions/ctype/ctype_upper.js index 9d52f8b30a..1ad0b28979 100644 --- a/functions/ctype/ctype_upper.js +++ b/functions/ctype/ctype_upper.js @@ -1,4 +1,4 @@ -function ctype_upper(text) { +function ctype_upper (text) { // discuss at: http://phpjs.org/functions/ctype_upper/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_upper(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.up) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.up) !== -1 +} diff --git a/functions/ctype/ctype_xdigit.js b/functions/ctype/ctype_xdigit.js index a6afe26e9c..3e3ce6d779 100644 --- a/functions/ctype/ctype_xdigit.js +++ b/functions/ctype/ctype_xdigit.js @@ -1,4 +1,4 @@ -function ctype_xdigit(text) { +function ctype_xdigit (text) { // discuss at: http://phpjs.org/functions/ctype_xdigit/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -6,11 +6,11 @@ function ctype_xdigit(text) { // returns 1: true if (typeof text !== 'string') { - return false; + return false } // BEGIN REDUNDANT // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.xd) !== -1; -} \ No newline at end of file + return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.xd) !== -1 +} diff --git a/functions/datetime/checkdate.js b/functions/datetime/checkdate.js index 321fc5c220..d540c9e0e5 100644 --- a/functions/datetime/checkdate.js +++ b/functions/datetime/checkdate.js @@ -1,4 +1,4 @@ -function checkdate(m, d, y) { +function checkdate (m, d, y) { // discuss at: http://phpjs.org/functions/checkdate/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Pyerre @@ -13,5 +13,5 @@ function checkdate(m, d, y) { // returns 4: false return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)) - .getDate(); -} \ No newline at end of file + .getDate() +} diff --git a/functions/datetime/date.js b/functions/datetime/date.js index a71735a606..bb7247890d 100644 --- a/functions/datetime/date.js +++ b/functions/datetime/date.js @@ -1,4 +1,4 @@ -function date(format, timestamp) { +function date (format, timestamp) { // discuss at: http://phpjs.org/functions/date/ // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // original by: gettimeofday @@ -55,212 +55,212 @@ function date(format, timestamp) { // example 9: date('W Y-m-d', 1293974054); // 2011-01-02 // returns 9: '52 2011-01-02' - var that = this; - var jsdate, f; + var that = this + var jsdate, f // Keep this here (works, but for code commented-out below for file size reasons) // var tal= []; var txt_words = [ 'Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' - ]; + ] // trailing backslash -> (dropped) // a backslash followed by any character (including backslash) -> the character // empty string -> empty string - var formatChr = /\\?(.?)/gi; - var formatChrCb = function(t, s) { - return f[t] ? f[t]() : s; - }; - var _pad = function(n, c) { - n = String(n); + var formatChr = /\\?(.?)/gi + var formatChrCb = function (t, s) { + return f[t] ? f[t]() : s + } + var _pad = function (n, c) { + n = String(n) while (n.length < c) { - n = '0' + n; + n = '0' + n } - return n; - }; + return n + } f = { // Day - d : function() { + d: function () { // Day of month w/leading 0; 01..31 - return _pad(f.j(), 2); + return _pad(f.j(), 2) }, - D : function() { + D: function () { // Shorthand day name; Mon...Sun return f.l() - .slice(0, 3); + .slice(0, 3) }, - j : function() { + j: function () { // Day of month; 1..31 - return jsdate.getDate(); + return jsdate.getDate() }, - l : function() { + l: function () { // Full day name; Monday...Sunday - return txt_words[f.w()] + 'day'; + return txt_words[f.w()] + 'day' }, - N : function() { + N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun] - return f.w() || 7; + return f.w() || 7 }, - S : function() { + S: function () { // Ordinal suffix for day of month; st, nd, rd, th - var j = f.j(); - var i = j % 10; + var j = f.j() + var i = j % 10 if (i <= 3 && parseInt((j % 100) / 10, 10) == 1) { - i = 0; + i = 0 } - return ['st', 'nd', 'rd'][i - 1] || 'th'; + return ['st', 'nd', 'rd'][i - 1] || 'th' }, - w : function() { + w: function () { // Day of week; 0[Sun]..6[Sat] - return jsdate.getDay(); + return jsdate.getDay() }, - z : function() { + z: function () { // Day of year; 0..365 - var a = new Date(f.Y(), f.n() - 1, f.j()); - var b = new Date(f.Y(), 0, 1); - return Math.round((a - b) / 864e5); + var a = new Date(f.Y(), f.n() - 1, f.j()) + var b = new Date(f.Y(), 0, 1) + return Math.round((a - b) / 864e5) }, // Week - W : function() { + W: function () { // ISO-8601 week number - var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3); - var b = new Date(a.getFullYear(), 0, 4); - return _pad(1 + Math.round((a - b) / 864e5 / 7), 2); + var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3) + var b = new Date(a.getFullYear(), 0, 4) + return _pad(1 + Math.round((a - b) / 864e5 / 7), 2) }, // Month - F : function() { + F: function () { // Full month name; January...December - return txt_words[6 + f.n()]; + return txt_words[6 + f.n()] }, - m : function() { + m: function () { // Month w/leading 0; 01...12 - return _pad(f.n(), 2); + return _pad(f.n(), 2) }, - M : function() { + M: function () { // Shorthand month name; Jan...Dec return f.F() - .slice(0, 3); + .slice(0, 3) }, - n : function() { + n: function () { // Month; 1...12 - return jsdate.getMonth() + 1; + return jsdate.getMonth() + 1 }, - t : function() { + t: function () { // Days in month; 28...31 return (new Date(f.Y(), f.n(), 0)) - .getDate(); + .getDate() }, // Year - L : function() { + L: function () { // Is leap year?; 0 or 1 - var j = f.Y(); - return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0; + var j = f.Y() + return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0 }, - o : function() { + o: function () { // ISO-8601 year - var n = f.n(); - var W = f.W(); - var Y = f.Y(); - return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0); + var n = f.n() + var W = f.W() + var Y = f.Y() + return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0) }, - Y : function() { + Y: function () { // Full year; e.g. 1980...2010 - return jsdate.getFullYear(); + return jsdate.getFullYear() }, - y : function() { + y: function () { // Last two digits of year; 00...99 return f.Y() .toString() - .slice(-2); + .slice(-2) }, // Time - a : function() { + a: function () { // am or pm - return jsdate.getHours() > 11 ? 'pm' : 'am'; + return jsdate.getHours() > 11 ? 'pm' : 'am' }, - A : function() { + A: function () { // AM or PM return f.a() - .toUpperCase(); + .toUpperCase() }, - B : function() { + B: function () { // Swatch Internet time; 000..999 - var H = jsdate.getUTCHours() * 36e2; + var H = jsdate.getUTCHours() * 36e2 // Hours - var i = jsdate.getUTCMinutes() * 60; + var i = jsdate.getUTCMinutes() * 60 // Minutes // Seconds - var s = jsdate.getUTCSeconds(); - return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3); + var s = jsdate.getUTCSeconds() + return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3) }, - g : function() { + g: function () { // 12-Hours; 1..12 - return f.G() % 12 || 12; + return f.G() % 12 || 12 }, - G : function() { + G: function () { // 24-Hours; 0..23 - return jsdate.getHours(); + return jsdate.getHours() }, - h : function() { + h: function () { // 12-Hours w/leading 0; 01..12 - return _pad(f.g(), 2); + return _pad(f.g(), 2) }, - H : function() { + H: function () { // 24-Hours w/leading 0; 00..23 - return _pad(f.G(), 2); + return _pad(f.G(), 2) }, - i : function() { + i: function () { // Minutes w/leading 0; 00..59 - return _pad(jsdate.getMinutes(), 2); + return _pad(jsdate.getMinutes(), 2) }, - s : function() { + s: function () { // Seconds w/leading 0; 00..59 - return _pad(jsdate.getSeconds(), 2); + return _pad(jsdate.getSeconds(), 2) }, - u : function() { + u: function () { // Microseconds; 000000-999000 - return _pad(jsdate.getMilliseconds() * 1000, 6); + return _pad(jsdate.getMilliseconds() * 1000, 6) }, // Timezone - e : function() { + e: function () { // Timezone identifier; e.g. Atlantic/Azores, ... // The following works, but requires inclusion of the very large // timezone_abbreviations_list() function. /* return that.date_default_timezone_get(); */ - throw 'Not supported (see source code of date() for timezone on how to add support)'; + throw 'Not supported (see source code of date() for timezone on how to add support)' }, - I : function() { + I: function () { // DST observed?; 0 or 1 // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC. // If they are not equal, then DST is observed. - var a = new Date(f.Y(), 0); + var a = new Date(f.Y(), 0) // Jan 1 - var c = Date.UTC(f.Y(), 0); + var c = Date.UTC(f.Y(), 0) // Jan 1 UTC - var b = new Date(f.Y(), 6); + var b = new Date(f.Y(), 6) // Jul 1 // Jul 1 UTC - var d = Date.UTC(f.Y(), 6); - return ((a - c) !== (b - d)) ? 1 : 0; + var d = Date.UTC(f.Y(), 6) + return ((a - c) !== (b - d)) ? 1 : 0 }, - O : function() { + O: function () { // Difference to GMT in hour format; e.g. +0200 - var tzo = jsdate.getTimezoneOffset(); - var a = Math.abs(tzo); - return (tzo > 0 ? '-' : '+') + _pad(Math.floor(a / 60) * 100 + a % 60, 4); + var tzo = jsdate.getTimezoneOffset() + var a = Math.abs(tzo) + return (tzo > 0 ? '-' : '+') + _pad(Math.floor(a / 60) * 100 + a % 60, 4) }, - P : function() { + P: function () { // Difference to GMT w/colon; e.g. +02:00 - var O = f.O(); - return (O.substr(0, 3) + ':' + O.substr(3, 2)); + var O = f.O() + return (O.substr(0, 3) + ':' + O.substr(3, 2)) }, - T : function() { + T: function () { // Timezone abbreviation; e.g. EST, MDT, ... // The following works, but requires inclusion of the very // large timezone_abbreviations_list() function. @@ -287,34 +287,34 @@ function date(format, timestamp) { } } */ - return 'UTC'; + return 'UTC' }, - Z : function() { + Z: function () { // Timezone offset in seconds (-43200...50400) - return -jsdate.getTimezoneOffset() * 60; + return -jsdate.getTimezoneOffset() * 60 }, // Full Date/Time - c : function() { + c: function () { // ISO-8601 date. - return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb); + return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb) }, - r : function() { + r: function () { // RFC 2822 - return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb); + return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb) }, - U : function() { + U: function () { // Seconds since UNIX epoch - return jsdate / 1000 | 0; + return jsdate / 1000 | 0 } - }; - this.date = function(format, timestamp) { - that = this; + } + this.date = function (format, timestamp) { + that = this jsdate = (timestamp === undefined ? new Date() : // Not provided (timestamp instanceof Date) ? new Date(timestamp) : // JS Date() new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int) - ); - return format.replace(formatChr, formatChrCb); - }; - return this.date(format, timestamp); -} \ No newline at end of file + ) + return format.replace(formatChr, formatChrCb) + } + return this.date(format, timestamp) +} diff --git a/functions/datetime/date_parse.js b/functions/datetime/date_parse.js index 160b5175d7..4d1ac80ea1 100644 --- a/functions/datetime/date_parse.js +++ b/functions/datetime/date_parse.js @@ -1,4 +1,4 @@ -function date_parse(date) { +function date_parse (date) { // discuss at: http://phpjs.org/functions/date_parse/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: strtotime @@ -6,43 +6,43 @@ function date_parse(date) { // returns 1: {year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0.5, warning_count: 0, warnings: [], error_count: 0, errors: [], is_localtime: false} // BEGIN REDUNDANT - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // END REDUNDANT var ts, warningsOffset = this.php_js.warnings ? this.php_js.warnings.length : null, - errorsOffset = this.php_js.errors ? this.php_js.errors.length : null; + errorsOffset = this.php_js.errors ? this.php_js.errors.length : null try { // Allow strtotime to return a decimal (which it normally does not) - this.php_js.date_parse_state = true; - ts = this.strtotime(date); - this.php_js.date_parse_state = false; + this.php_js.date_parse_state = true + ts = this.strtotime(date) + this.php_js.date_parse_state = false } finally { if (!ts) { - return false; + return false } } - var dt = new Date(ts * 1000); + var dt = new Date(ts * 1000) var retObj = { // Grab any new warnings or errors added (not implemented yet in strtotime()); throwing warnings, notices, or errors could also be easily monitored by using 'watch' on this.php_js.latestWarning, etc. and/or calling any defined error handlers - warning_count : warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset) + warning_count: warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset) .length : 0, - warnings : warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset) : [], - error_count : errorsOffset !== null ? this.php_js.errors.slice(errorsOffset) + warnings: warningsOffset !== null ? this.php_js.warnings.slice(warningsOffset) : [], + error_count: errorsOffset !== null ? this.php_js.errors.slice(errorsOffset) .length : 0, - errors : errorsOffset !== null ? this.php_js.errors.slice(errorsOffset) : [] - }; - retObj.year = dt.getFullYear(); - retObj.month = dt.getMonth() + 1; - retObj.day = dt.getDate(); - retObj.hour = dt.getHours(); - retObj.minute = dt.getMinutes(); - retObj.second = dt.getSeconds(); - retObj.fraction = parseFloat('0.' + dt.getMilliseconds()); - retObj.is_localtime = dt.getTimezoneOffset() !== 0; + errors: errorsOffset !== null ? this.php_js.errors.slice(errorsOffset) : [] + } + retObj.year = dt.getFullYear() + retObj.month = dt.getMonth() + 1 + retObj.day = dt.getDate() + retObj.hour = dt.getHours() + retObj.minute = dt.getMinutes() + retObj.second = dt.getSeconds() + retObj.fraction = parseFloat('0.' + dt.getMilliseconds()) + retObj.is_localtime = dt.getTimezoneOffset() !== 0 - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/datetime/getdate.js b/functions/datetime/getdate.js index fd25e6daf2..5ce30b336e 100644 --- a/functions/datetime/getdate.js +++ b/functions/datetime/getdate.js @@ -1,4 +1,4 @@ -function getdate(timestamp) { +function getdate (timestamp) { // discuss at: http://phpjs.org/functions/getdate/ // original by: Paulo Freitas // input by: Alex @@ -6,30 +6,30 @@ function getdate(timestamp) { // example 1: getdate(1055901520); // returns 1: {'seconds': 40, 'minutes': 58, 'hours': 21, 'mday': 17, 'wday': 2, 'mon': 6, 'year': 2003, 'yday': 167, 'weekday': 'Tuesday', 'month': 'June', '0': 1055901520} - var _w = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur']; + var _w = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'] var _m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' - ]; + ] var d = ((typeof timestamp === 'undefined') ? new Date() : // Not provided (typeof timestamp === 'object') ? new Date(timestamp) : // Javascript Date() new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int) - ); - var w = d.getDay(); - var m = d.getMonth(); - var y = d.getFullYear(); - var r = {}; + ) + var w = d.getDay() + var m = d.getMonth() + var y = d.getFullYear() + var r = {} - r.seconds = d.getSeconds(); - r.minutes = d.getMinutes(); - r.hours = d.getHours(); - r.mday = d.getDate(); - r.wday = w; - r.mon = m + 1; - r.year = y; - r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000); - r.weekday = _w[w] + 'day'; - r.month = _m[m]; - r['0'] = parseInt(d.getTime() / 1000, 10); + r.seconds = d.getSeconds() + r.minutes = d.getMinutes() + r.hours = d.getHours() + r.mday = d.getDate() + r.wday = w + r.mon = m + 1 + r.year = y + r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000) + r.weekday = _w[w] + 'day' + r.month = _m[m] + r['0'] = parseInt(d.getTime() / 1000, 10) - return r; -} \ No newline at end of file + return r +} diff --git a/functions/datetime/gettimeofday.js b/functions/datetime/gettimeofday.js index f77161453f..18f06d7453 100644 --- a/functions/datetime/gettimeofday.js +++ b/functions/datetime/gettimeofday.js @@ -1,4 +1,4 @@ -function gettimeofday(return_float) { +function gettimeofday (return_float) { // discuss at: http://phpjs.org/functions/gettimeofday/ // original by: Brett Zamir (http://brett-zamir.me) // original by: Josh Fraser (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/) @@ -10,19 +10,19 @@ function gettimeofday(return_float) { // returns 2: 1238748978.49 var t = new Date(), - y = 0; + y = 0 if (return_float) { - return t.getTime() / 1000; + return t.getTime() / 1000 } // Store current year. - y = t.getFullYear(); + y = t.getFullYear() return { - sec : t.getUTCSeconds(), - usec : t.getUTCMilliseconds() * 1000, - minuteswest : t.getTimezoneOffset(), + sec: t.getUTCSeconds(), + usec: t.getUTCMilliseconds() * 1000, + minuteswest: t.getTimezoneOffset(), // Compare Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC to see if DST is observed. - dsttime : 0 + (((new Date(y, 0)) - Date.UTC(y, 0)) !== ((new Date(y, 6)) - Date.UTC(y, 6))) - }; -} \ No newline at end of file + dsttime: 0 + (((new Date(y, 0)) - Date.UTC(y, 0)) !== ((new Date(y, 6)) - Date.UTC(y, 6))) + } +} diff --git a/functions/datetime/gmdate.js b/functions/datetime/gmdate.js index c5671b32dd..6bd38907c0 100644 --- a/functions/datetime/gmdate.js +++ b/functions/datetime/gmdate.js @@ -1,4 +1,4 @@ -function gmdate(format, timestamp) { +function gmdate (format, timestamp) { // discuss at: http://phpjs.org/functions/gmdate/ // original by: Brett Zamir (http://brett-zamir.me) // input by: Alex @@ -10,8 +10,8 @@ function gmdate(format, timestamp) { var dt = typeof timestamp === 'undefined' ? new Date() : // Not provided typeof timestamp === 'object' ? new Date(timestamp) : // Javascript Date() // UNIX timestamp (auto-convert to int) - new Date(timestamp * 1000); + new Date(timestamp * 1000) timestamp = Date.parse(dt.toUTCString() - .slice(0, -4)) / 1000; - return this.date(format, timestamp); -} \ No newline at end of file + .slice(0, -4)) / 1000 + return this.date(format, timestamp) +} diff --git a/functions/datetime/gmmktime.js b/functions/datetime/gmmktime.js index fe9d68be4c..28da9f00a2 100644 --- a/functions/datetime/gmmktime.js +++ b/functions/datetime/gmmktime.js @@ -1,4 +1,4 @@ -function gmmktime() { +function gmmktime () { // discuss at: http://phpjs.org/functions/gmmktime/ // original by: Brett Zamir (http://brett-zamir.me) // original by: mktime @@ -10,32 +10,32 @@ function gmmktime() { var d = new Date(), r = arguments, i = 0, - e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear']; + e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'] for (i = 0; i < e.length; i++) { if (typeof r[i] === 'undefined') { - r[i] = d['getUTC' + e[i]](); + r[i] = d['getUTC' + e[i]]() // +1 to fix JS months. - r[i] += (i === 3); + r[i] += (i === 3) } else { - r[i] = parseInt(r[i], 10); + r[i] = parseInt(r[i], 10) if (isNaN(r[i])) { - return false; + return false } } } // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000. - r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0); + r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0) // Set year, month (-1 to fix JS months), and date. // !This must come before the call to setHours! - d.setUTCFullYear(r[5], r[3] - 1, r[4]); + d.setUTCFullYear(r[5], r[3] - 1, r[4]) // Set hours, minutes, and seconds. - d.setUTCHours(r[0], r[1], r[2]); + d.setUTCHours(r[0], r[1], r[2]) // Divide milliseconds by 1000 to return seconds and drop decimal. // Add 1 second if negative or it'll be off from PHP by 1 second. - return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0); -} \ No newline at end of file + return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0) +} diff --git a/functions/datetime/gmstrftime.js b/functions/datetime/gmstrftime.js index e5fca4efd6..aad3c5ad98 100644 --- a/functions/datetime/gmstrftime.js +++ b/functions/datetime/gmstrftime.js @@ -1,4 +1,4 @@ -function gmstrftime(format, timestamp) { +function gmstrftime (format, timestamp) { // discuss at: http://phpjs.org/functions/gmstrftime/ // original by: Brett Zamir (http://brett-zamir.me) // input by: Alex @@ -10,8 +10,8 @@ function gmstrftime(format, timestamp) { var dt = ((typeof timestamp === 'undefined') ? new Date() : // Not provided (typeof timestamp === 'object') ? new Date(timestamp) : // Javascript Date() new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int) - ); + ) timestamp = Date.parse(dt.toUTCString() - .slice(0, -4)) / 1000; - return this.strftime(format, timestamp); -} \ No newline at end of file + .slice(0, -4)) / 1000 + return this.strftime(format, timestamp) +} diff --git a/functions/datetime/idate.js b/functions/datetime/idate.js index 66061abe79..640dd9a7e3 100644 --- a/functions/datetime/idate.js +++ b/functions/datetime/idate.js @@ -1,4 +1,4 @@ -function idate(format, timestamp) { +function idate (format, timestamp) { // discuss at: http://phpjs.org/functions/idate/ // original by: Brett Zamir (http://brett-zamir.me) // original by: date @@ -10,10 +10,10 @@ function idate(format, timestamp) { // returns 1: 9 if (format === undefined) { - throw 'idate() expects at least 1 parameter, 0 given'; + throw 'idate() expects at least 1 parameter, 0 given' } if (!format.length || format.length > 1) { - throw 'idate format is one char'; + throw 'idate format is one char' } // Fix: Need to allow date_default_timezone_set() (check for this.php_js.default_timezone and use) @@ -21,54 +21,54 @@ function idate(format, timestamp) { (timestamp instanceof Date) ? new Date(timestamp) : // Javascript Date() new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int) ), - a; + a switch (format) { - case 'B': - return Math.floor(((date.getUTCHours() * 36e2) + (date.getUTCMinutes() * 60) + date.getUTCSeconds() + 36e2) / - 86.4) % 1e3; - case 'd': - return date.getDate(); - case 'h': - return date.getHours() % 12 || 12; - case 'H': - return date.getHours(); - case 'i': - return date.getMinutes(); - case 'I': + case 'B': + return Math.floor(((date.getUTCHours() * 36e2) + (date.getUTCMinutes() * 60) + date.getUTCSeconds() + 36e2) / + 86.4) % 1e3 + case 'd': + return date.getDate() + case 'h': + return date.getHours() % 12 || 12 + case 'H': + return date.getHours() + case 'i': + return date.getMinutes() + case 'I': // capital 'i' // Logic original by getimeofday(). // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC. // If they are not equal, then DST is observed. - a = date.getFullYear(); - return 0 + (((new Date(a, 0)) - Date.UTC(a, 0)) !== ((new Date(a, 6)) - Date.UTC(a, 6))); - case 'L': - a = date.getFullYear(); - return (!(a & 3) && (a % 1e2 || !(a % 4e2))) ? 1 : 0; - case 'm': - return date.getMonth() + 1; - case 's': - return date.getSeconds(); - case 't': - return (new Date(date.getFullYear(), date.getMonth() + 1, 0)) - .getDate(); - case 'U': - return Math.round(date.getTime() / 1000); - case 'w': - return date.getDay(); - case 'W': - a = new Date(date.getFullYear(), date.getMonth(), date.getDate() - (date.getDay() || 7) + 3); - return 1 + Math.round((a - (new Date(a.getFullYear(), 0, 4))) / 864e5 / 7); - case 'y': - return parseInt((date.getFullYear() + '') - .slice(2), 10); // This function returns an integer, unlike date() - case 'Y': - return date.getFullYear(); - case 'z': - return Math.floor((date - new Date(date.getFullYear(), 0, 1)) / 864e5); - case 'Z': - return -date.getTimezoneOffset() * 60; - default: - throw 'Unrecognized date format token'; + a = date.getFullYear() + return 0 + (((new Date(a, 0)) - Date.UTC(a, 0)) !== ((new Date(a, 6)) - Date.UTC(a, 6))) + case 'L': + a = date.getFullYear() + return (!(a & 3) && (a % 1e2 || !(a % 4e2))) ? 1 : 0 + case 'm': + return date.getMonth() + 1 + case 's': + return date.getSeconds() + case 't': + return (new Date(date.getFullYear(), date.getMonth() + 1, 0)) + .getDate() + case 'U': + return Math.round(date.getTime() / 1000) + case 'w': + return date.getDay() + case 'W': + a = new Date(date.getFullYear(), date.getMonth(), date.getDate() - (date.getDay() || 7) + 3) + return 1 + Math.round((a - (new Date(a.getFullYear(), 0, 4))) / 864e5 / 7) + case 'y': + return parseInt((date.getFullYear() + '') + .slice(2), 10) // This function returns an integer, unlike date() + case 'Y': + return date.getFullYear() + case 'z': + return Math.floor((date - new Date(date.getFullYear(), 0, 1)) / 864e5) + case 'Z': + return -date.getTimezoneOffset() * 60 + default: + throw 'Unrecognized date format token' } -} \ No newline at end of file +} diff --git a/functions/datetime/microtime.js b/functions/datetime/microtime.js index 371b470908..1ba1781abb 100644 --- a/functions/datetime/microtime.js +++ b/functions/datetime/microtime.js @@ -1,4 +1,4 @@ -function microtime(get_as_float) { +function microtime (get_as_float) { // discuss at: http://phpjs.org/functions/microtime/ // original by: Paulo Freitas // improved by: Dumitru Uzun (http://duzun.me) @@ -9,19 +9,19 @@ function microtime(get_as_float) { // returns 2: true if (typeof performance !== 'undefined' && performance.now) { - var now = (performance.now() + performance.timing.navigationStart) / 1e3; - if (get_as_float) return now; + var now = (performance.now() + performance.timing.navigationStart) / 1e3 + if (get_as_float) return now // Math.round(now) - var s = now | 0; - return (Math.round((now - s) * 1e6) / 1e6) + ' ' + s; + var s = now | 0 + return (Math.round((now - s) * 1e6) / 1e6) + ' ' + s } else { var now = (Date.now ? Date.now() : new Date() - .getTime()) / 1e3; - if (get_as_float) return now; + .getTime()) / 1e3 + if (get_as_float) return now // Math.round(now) - var s = now | 0; - return (Math.round((now - s) * 1e3) / 1e3) + ' ' + s; + var s = now | 0 + return (Math.round((now - s) * 1e3) / 1e3) + ' ' + s } -} \ No newline at end of file +} diff --git a/functions/datetime/mktime.js b/functions/datetime/mktime.js index e09efb699d..29f95bb15a 100644 --- a/functions/datetime/mktime.js +++ b/functions/datetime/mktime.js @@ -1,4 +1,4 @@ -function mktime() { +function mktime () { // discuss at: http://phpjs.org/functions/mktime/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: baris ozdil @@ -41,32 +41,32 @@ function mktime() { var d = new Date(), r = arguments, i = 0, - e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear']; + e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'] for (i = 0; i < e.length; i++) { if (typeof r[i] === 'undefined') { - r[i] = d['get' + e[i]](); + r[i] = d['get' + e[i]]() // +1 to fix JS months. - r[i] += (i === 3); + r[i] += (i === 3) } else { - r[i] = parseInt(r[i], 10); + r[i] = parseInt(r[i], 10) if (isNaN(r[i])) { - return false; + return false } } } // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000. - r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0); + r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0) // Set year, month (-1 to fix JS months), and date. // !This must come before the call to setHours! - d.setFullYear(r[5], r[3] - 1, r[4]); + d.setFullYear(r[5], r[3] - 1, r[4]) // Set hours, minutes, and seconds. - d.setHours(r[0], r[1], r[2]); + d.setHours(r[0], r[1], r[2]) // Divide milliseconds by 1000 to return seconds and drop decimal. // Add 1 second if negative or it'll be off from PHP by 1 second. - return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0); -} \ No newline at end of file + return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0) +} diff --git a/functions/datetime/strftime.js b/functions/datetime/strftime.js index 3224c174c6..647a567b87 100644 --- a/functions/datetime/strftime.js +++ b/functions/datetime/strftime.js @@ -1,4 +1,4 @@ -function strftime(fmt, timestamp) { +function strftime (fmt, timestamp) { // discuss at: http://phpjs.org/functions/strftime/ // original by: Blues (http://tech.bluesmoon.info/) // reimplemented by: Brett Zamir (http://brett-zamir.me) @@ -10,143 +10,143 @@ function strftime(fmt, timestamp) { // example 1: strftime("%A", 1062462400); // Return value will depend on date and locale // returns 1: 'Tuesday' - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - var phpjs = this.php_js; + var phpjs = this.php_js // BEGIN STATIC - var _xPad = function(x, pad, r) { + var _xPad = function (x, pad, r) { if (typeof r === 'undefined') { - r = 10; + r = 10 } for (; parseInt(x, 10) < r && r > 1; r /= 10) { - x = pad.toString() + x; + x = pad.toString() + x } - return x.toString(); - }; + return x.toString() + } - var locale = phpjs.localeCategories.LC_TIME; - var locales = phpjs.locales; - var lc_time = locales[locale].LC_TIME; + var locale = phpjs.localeCategories.LC_TIME + var locales = phpjs.locales + var lc_time = locales[locale].LC_TIME var _formats = { - a : function(d) { - return lc_time.a[d.getDay()]; + a: function (d) { + return lc_time.a[d.getDay()] }, - A : function(d) { - return lc_time.A[d.getDay()]; + A: function (d) { + return lc_time.A[d.getDay()] }, - b : function(d) { - return lc_time.b[d.getMonth()]; + b: function (d) { + return lc_time.b[d.getMonth()] }, - B : function(d) { - return lc_time.B[d.getMonth()]; + B: function (d) { + return lc_time.B[d.getMonth()] }, - C : function(d) { - return _xPad(parseInt(d.getFullYear() / 100, 10), 0); + C: function (d) { + return _xPad(parseInt(d.getFullYear() / 100, 10), 0) }, - d : ['getDate', '0'], - e : ['getDate', ' '], - g : function(d) { - return _xPad(parseInt(this.G(d) / 100, 10), 0); + d: ['getDate', '0'], + e: ['getDate', ' '], + g: function (d) { + return _xPad(parseInt(this.G(d) / 100, 10), 0) }, - G : function(d) { - var y = d.getFullYear(); - var V = parseInt(_formats.V(d), 10); - var W = parseInt(_formats.W(d), 10); + G: function (d) { + var y = d.getFullYear() + var V = parseInt(_formats.V(d), 10) + var W = parseInt(_formats.W(d), 10) if (W > V) { - y++; + y++ } else if (W === 0 && V >= 52) { - y--; + y-- } - return y; + return y }, - H : ['getHours', '0'], - I : function(d) { - var I = d.getHours() % 12; - return _xPad(I === 0 ? 12 : I, 0); + H: ['getHours', '0'], + I: function (d) { + var I = d.getHours() % 12 + return _xPad(I === 0 ? 12 : I, 0) }, - j : function(d) { - var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT'); + j: function (d) { + var ms = d - new Date('' + d.getFullYear() + '/1/1 GMT') // Line differs from Yahoo implementation which would be equivalent to replacing it here with: - ms += d.getTimezoneOffset() * 60000; + ms += d.getTimezoneOffset() * 60000 // ms = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT') - ms; - var doy = parseInt(ms / 60000 / 60 / 24, 10) + 1; - return _xPad(doy, 0, 100); + var doy = parseInt(ms / 60000 / 60 / 24, 10) + 1 + return _xPad(doy, 0, 100) }, - k : ['getHours', '0'], + k: ['getHours', '0'], // not in PHP, but implemented here (as in Yahoo) - l : function(d) { - var l = d.getHours() % 12; - return _xPad(l === 0 ? 12 : l, ' '); + l: function (d) { + var l = d.getHours() % 12 + return _xPad(l === 0 ? 12 : l, ' ') }, - m : function(d) { - return _xPad(d.getMonth() + 1, 0); + m: function (d) { + return _xPad(d.getMonth() + 1, 0) }, - M : ['getMinutes', '0'], - p : function(d) { - return lc_time.p[d.getHours() >= 12 ? 1 : 0]; + M: ['getMinutes', '0'], + p: function (d) { + return lc_time.p[d.getHours() >= 12 ? 1 : 0] }, - P : function(d) { - return lc_time.P[d.getHours() >= 12 ? 1 : 0]; + P: function (d) { + return lc_time.P[d.getHours() >= 12 ? 1 : 0] }, - s : function(d) { + s: function (d) { // Yahoo uses return parseInt(d.getTime()/1000, 10); - return Date.parse(d) / 1000; + return Date.parse(d) / 1000 }, - S : ['getSeconds', '0'], - u : function(d) { - var dow = d.getDay(); - return ((dow === 0) ? 7 : dow); + S: ['getSeconds', '0'], + u: function (d) { + var dow = d.getDay() + return ((dow === 0) ? 7 : dow) }, - U : function(d) { - var doy = parseInt(_formats.j(d), 10); - var rdow = 6 - d.getDay(); - var woy = parseInt((doy + rdow) / 7, 10); - return _xPad(woy, 0); + U: function (d) { + var doy = parseInt(_formats.j(d), 10) + var rdow = 6 - d.getDay() + var woy = parseInt((doy + rdow) / 7, 10) + return _xPad(woy, 0) }, - V : function(d) { - var woy = parseInt(_formats.W(d), 10); + V: function (d) { + var woy = parseInt(_formats.W(d), 10) var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')) - .getDay(); + .getDay() // First week is 01 and not 00 as in the case of %U and %W, // so we add 1 to the final result except if day 1 of the year // is a Monday (then %W returns 01). // We also need to subtract 1 if the day 1 of the year is // Friday-Sunday, so the resulting equation becomes: - var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1); + var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1) if (idow === 53 && (new Date('' + d.getFullYear() + '/12/31')) .getDay() < 4) { - idow = 1; + idow = 1 } else if (idow === 0) { - idow = _formats.V(new Date('' + (d.getFullYear() - 1) + '/12/31')); + idow = _formats.V(new Date('' + (d.getFullYear() - 1) + '/12/31')) } - return _xPad(idow, 0); - }, - w : 'getDay', - W : function(d) { - var doy = parseInt(_formats.j(d), 10); - var rdow = 7 - _formats.u(d); - var woy = parseInt((doy + rdow) / 7, 10); - return _xPad(woy, 0, 10); - }, - y : function(d) { - return _xPad(d.getFullYear() % 100, 0); - }, - Y : 'getFullYear', - z : function(d) { - var o = d.getTimezoneOffset(); - var H = _xPad(parseInt(Math.abs(o / 60), 10), 0); - var M = _xPad(o % 60, 0); - return (o > 0 ? '-' : '+') + H + M; - }, - Z : function(d) { + return _xPad(idow, 0) + }, + w: 'getDay', + W: function (d) { + var doy = parseInt(_formats.j(d), 10) + var rdow = 7 - _formats.u(d) + var woy = parseInt((doy + rdow) / 7, 10) + return _xPad(woy, 0, 10) + }, + y: function (d) { + return _xPad(d.getFullYear() % 100, 0) + }, + Y: 'getFullYear', + z: function (d) { + var o = d.getTimezoneOffset() + var H = _xPad(parseInt(Math.abs(o / 60), 10), 0) + var M = _xPad(o % 60, 0) + return (o > 0 ? '-' : '+') + H + M + }, + Z: function (d) { return d.toString() - .replace(/^.*\(([^)]+)\)$/, '$1'); + .replace(/^.*\(([^)]+)\)$/, '$1') /* // Yahoo's: Better? var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, ''); @@ -156,10 +156,10 @@ function strftime(fmt, timestamp) { return tz; */ }, - '%' : function(d) { - return '%'; + '%': function (d) { + return '%' } - }; + } // END STATIC /* Fix: Locale alternatives are supported though not documented in PHP; see http://linux.die.net/man/3/strptime Ec @@ -183,43 +183,43 @@ Oy var _date = ((typeof timestamp === 'undefined') ? new Date() : // Not provided (typeof timestamp === 'object') ? new Date(timestamp) : // Javascript Date() new Date(timestamp * 1000) // PHP API expects UNIX timestamp (auto-convert to int) - ); + ) var _aggregates = { - c : 'locale', - D : '%m/%d/%y', - F : '%y-%m-%d', - h : '%b', - n : '\n', - r : 'locale', - R : '%H:%M', - t : '\t', - T : '%H:%M:%S', - x : 'locale', - X : 'locale' - }; + c: 'locale', + D: '%m/%d/%y', + F: '%y-%m-%d', + h: '%b', + n: '\n', + r: 'locale', + R: '%H:%M', + t: '\t', + T: '%H:%M:%S', + x: 'locale', + X: 'locale' + } // First replace aggregates (run in a loop because an agg may be made up of other aggs) while (fmt.match(/%[cDFhnrRtTxX]/)) { - fmt = fmt.replace(/%([cDFhnrRtTxX])/g, function(m0, m1) { - var f = _aggregates[m1]; - return (f === 'locale' ? lc_time[m1] : f); - }); + fmt = fmt.replace(/%([cDFhnrRtTxX])/g, function (m0, m1) { + var f = _aggregates[m1] + return (f === 'locale' ? lc_time[m1] : f) + }) } // Now replace formats - we need a closure so that the date object gets passed through - var str = fmt.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, function(m0, m1) { - var f = _formats[m1]; + var str = fmt.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, function (m0, m1) { + var f = _formats[m1] if (typeof f === 'string') { - return _date[f](); + return _date[f]() } else if (typeof f === 'function') { - return f(_date); + return f(_date) } else if (typeof f === 'object' && typeof f[0] === 'string') { - return _xPad(_date[f[0]](), f[1]); + return _xPad(_date[f[0]](), f[1]) } else { // Shouldn't reach here - return m1; + return m1 } - }); - return str; -} \ No newline at end of file + }) + return str +} diff --git a/functions/datetime/strptime.js b/functions/datetime/strptime.js index cad766dc0f..3527805e63 100644 --- a/functions/datetime/strptime.js +++ b/functions/datetime/strptime.js @@ -1,4 +1,4 @@ -function strptime(dateStr, format) { +function strptime (dateStr, format) { // discuss at: http://phpjs.org/functions/strptime/ // original by: Brett Zamir (http://brett-zamir.me) // original by: strftime @@ -15,57 +15,57 @@ function strptime(dateStr, format) { // Needs more thorough testing and examples var retObj = { - tm_sec : 0, - tm_min : 0, - tm_hour : 0, - tm_mday : 0, - tm_mon : 0, - tm_year : 0, - tm_wday : 0, - tm_yday : 0, - unparsed : '' + tm_sec: 0, + tm_min: 0, + tm_hour: 0, + tm_mday: 0, + tm_mon: 0, + tm_year: 0, + tm_wday: 0, + tm_yday: 0, + unparsed: '' }, i = 0, that = this, amPmOffset = 0, prevHour = false, - _reset = function(dateObj, realMday) { + _reset = function (dateObj, realMday) { // realMday is to allow for a value of 0 in return results (but without // messing up the Date() object) var jan1, o = retObj, - d = dateObj; - o.tm_sec = d.getUTCSeconds(); - o.tm_min = d.getUTCMinutes(); - o.tm_hour = d.getUTCHours(); - o.tm_mday = realMday === 0 ? realMday : d.getUTCDate(); - o.tm_mon = d.getUTCMonth(); - o.tm_year = d.getUTCFullYear() - 1900; - o.tm_wday = realMday === 0 ? (d.getUTCDay() > 0 ? d.getUTCDay() - 1 : 6) : d.getUTCDay(); - jan1 = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); - o.tm_yday = Math.ceil((d - jan1) / (1000 * 60 * 60 * 24)); + d = dateObj + o.tm_sec = d.getUTCSeconds() + o.tm_min = d.getUTCMinutes() + o.tm_hour = d.getUTCHours() + o.tm_mday = realMday === 0 ? realMday : d.getUTCDate() + o.tm_mon = d.getUTCMonth() + o.tm_year = d.getUTCFullYear() - 1900 + o.tm_wday = realMday === 0 ? (d.getUTCDay() > 0 ? d.getUTCDay() - 1 : 6) : d.getUTCDay() + jan1 = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)) + o.tm_yday = Math.ceil((d - jan1) / (1000 * 60 * 60 * 24)) }, - _date = function() { - var o = retObj; + _date = function () { + var o = retObj // We set date to at least 1 to ensure year or month doesn't go backwards return _reset(new Date(Date.UTC(o.tm_year + 1900, o.tm_mon, o.tm_mday || 1, o.tm_hour, o.tm_min, o.tm_sec)), - o.tm_mday); - }; + o.tm_mday) + } // BEGIN STATIC var _NWS = /\S/, - _WS = /\s/; + _WS = /\s/ var _aggregates = { - c : 'locale', - D : '%m/%d/%y', - F : '%y-%m-%d', - r : 'locale', - R : '%H:%M', - T : '%H:%M:%S', - x : 'locale', - X : 'locale' - }; + c: 'locale', + D: '%m/%d/%y', + F: '%y-%m-%d', + r: 'locale', + R: '%H:%M', + T: '%H:%M:%S', + x: 'locale', + X: 'locale' + } /* Fix: Locale alternatives are supported though not documented in PHP; see http://linux.die.net/man/3/strptime Ec @@ -85,271 +85,271 @@ Ow OW Oy */ - var _preg_quote = function(str) { + var _preg_quote = function (str) { return (str + '') - .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1'); - }; + .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1') + } // END STATIC // BEGIN REDUNDANT - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // ensure setup of localization variables takes place - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT - var phpjs = this.php_js; - var locale = phpjs.localeCategories.LC_TIME; - var locales = phpjs.locales; - var lc_time = locales[locale].LC_TIME; + var phpjs = this.php_js + var locale = phpjs.localeCategories.LC_TIME + var locales = phpjs.locales + var lc_time = locales[locale].LC_TIME // First replace aggregates (run in a loop because an agg may be made up of other aggs) while (format.match(/%[cDFhnrRtTxX]/)) { - format = format.replace(/%([cDFhnrRtTxX])/g, function(m0, m1) { - var f = _aggregates[m1]; - return (f === 'locale' ? lc_time[m1] : f); - }); + format = format.replace(/%([cDFhnrRtTxX])/g, function (m0, m1) { + var f = _aggregates[m1] + return (f === 'locale' ? lc_time[m1] : f) + }) } - var _addNext = function(j, regex, cb) { + var _addNext = function (j, regex, cb) { if (typeof regex === 'string') { - regex = new RegExp('^' + regex, 'i'); + regex = new RegExp('^' + regex, 'i') } - var check = dateStr.slice(j); - var match = regex.exec(check); + var check = dateStr.slice(j) + var match = regex.exec(check) // Even if the callback returns null after assigning to the return object, the object won't be saved anyways - var testNull = match ? cb.apply(null, match) : null; + var testNull = match ? cb.apply(null, match) : null if (testNull === null) { - throw 'No match in string'; + throw 'No match in string' } - return j + match[0].length; - }; + return j + match[0].length + } - var _addLocalized = function(j, formatChar, category) { + var _addLocalized = function (j, formatChar, category) { return _addNext(j, that.array_map( _preg_quote, lc_time[formatChar]) .join('|'), // Could make each parenthesized instead and pass index to callback - function(m) { - var match = lc_time[formatChar].search(new RegExp('^' + _preg_quote(m) + '$', 'i')); + function (m) { + var match = lc_time[formatChar].search(new RegExp('^' + _preg_quote(m) + '$', 'i')) if (match) { - retObj[category] = match[0]; + retObj[category] = match[0] } - }); - }; + }) + } // BEGIN PROCESSING CHARACTERS for (i = 0, j = 0; i < format.length; i++) { if (format.charAt(i) === '%') { - var literalPos = ['%', 'n', 't'].indexOf(format.charAt(i + 1)); + var literalPos = ['%', 'n', 't'].indexOf(format.charAt(i + 1)) if (literalPos !== -1) { if (['%', '\n', '\t'].indexOf(dateStr.charAt(j)) === literalPos) { // a matched literal ++i; // skip beyond - ++j; - continue; + ++j + continue } // Format indicated a percent literal, but not actually present - return false; + return false } - var formatChar = format.charAt(i + 1); + var formatChar = format.charAt(i + 1) try { switch (formatChar) { - case 'a': + case 'a': // Fall-through // Sun-Sat - case 'A': + case 'A': // Sunday-Saturday // Changes nothing else - j = _addLocalized(j, formatChar, 'tm_wday'); - break; - case 'h': + j = _addLocalized(j, formatChar, 'tm_wday') + break + case 'h': // Fall-through (alias of 'b'); - case 'b': + case 'b': // Jan-Dec - j = _addLocalized(j, 'b', 'tm_mon'); + j = _addLocalized(j, 'b', 'tm_mon') // Also changes wday, yday - _date(); - break; - case 'B': + _date() + break + case 'B': // January-December - j = _addLocalized(j, formatChar, 'tm_mon'); + j = _addLocalized(j, formatChar, 'tm_mon') // Also changes wday, yday - _date(); - break; - case 'C': + _date() + break + case 'C': // 0+; century (19 for 20th) - j = _addNext(j, /^\d?\d/, // PHP docs say two-digit, but accepts one-digit (two-digit max) + j = _addNext(j, /^\d?\d/, // PHP docs say two-digit, but accepts one-digit (two-digit max) - function(d) { - var year = (parseInt(d, 10) - 19) * 100; - retObj.tm_year = year; - _date(); + function (d) { + var year = (parseInt(d, 10) - 19) * 100 + retObj.tm_year = year + _date() if (!retObj.tm_yday) { - retObj.tm_yday = -1; + retObj.tm_yday = -1 } // Also changes wday; and sets yday to -1 (always?) - }); - break; - case 'd': + }) + break + case 'd': // Fall-through 01-31 day - case 'e': + case 'e': // 1-31 day - j = _addNext(j, formatChar === 'd' ? /^(0[1-9]|[1-2]\d|3[0-1])/ : /^([1-2]\d|3[0-1]|[1-9])/, - function(d) { - var dayMonth = parseInt(d, 10); - retObj.tm_mday = dayMonth; + j = _addNext(j, formatChar === 'd' ? /^(0[1-9]|[1-2]\d|3[0-1])/ : /^([1-2]\d|3[0-1]|[1-9])/, + function (d) { + var dayMonth = parseInt(d, 10) + retObj.tm_mday = dayMonth // Also changes w_day, y_day - _date(); - }); - break; - case 'g': + _date() + }) + break + case 'g': // No apparent effect; 2-digit year (see 'V') - break; - case 'G': + break + case 'G': // No apparent effect; 4-digit year (see 'V')' - break; - case 'H': + break + case 'H': // 00-23 hours - j = _addNext(j, /^([0-1]\d|2[0-3])/, function(d) { - var hour = parseInt(d, 10); - retObj.tm_hour = hour; + j = _addNext(j, /^([0-1]\d|2[0-3])/, function (d) { + var hour = parseInt(d, 10) + retObj.tm_hour = hour // Changes nothing else - }); - break; - case 'l': + }) + break + case 'l': // Fall-through of lower-case 'L'; 1-12 hours - case 'I': + case 'I': // 01-12 hours - j = _addNext(j, formatChar === 'l' ? /^([1-9]|1[0-2])/ : /^(0[1-9]|1[0-2])/, function(d) { - var hour = parseInt(d, 10) - 1 + amPmOffset; - retObj.tm_hour = hour; + j = _addNext(j, formatChar === 'l' ? /^([1-9]|1[0-2])/ : /^(0[1-9]|1[0-2])/, function (d) { + var hour = parseInt(d, 10) - 1 + amPmOffset + retObj.tm_hour = hour // Used for coordinating with am-pm - prevHour = true; + prevHour = true // Changes nothing else, but affected by prior 'p/P' - }); - break; - case 'j': + }) + break + case 'j': // 001-366 day of year - j = _addNext(j, /^(00[1-9]|0[1-9]\d|[1-2]\d\d|3[0-6][0-6])/, function(d) { - var dayYear = parseInt(d, 10) - 1; - retObj.tm_yday = dayYear; + j = _addNext(j, /^(00[1-9]|0[1-9]\d|[1-2]\d\d|3[0-6][0-6])/, function (d) { + var dayYear = parseInt(d, 10) - 1 + retObj.tm_yday = dayYear // Changes nothing else (oddly, since if original by a given year, could calculate other fields) - }); - break; - case 'm': + }) + break + case 'm': // 01-12 month - j = _addNext(j, /^(0[1-9]|1[0-2])/, function(d) { - var month = parseInt(d, 10) - 1; - retObj.tm_mon = month; + j = _addNext(j, /^(0[1-9]|1[0-2])/, function (d) { + var month = parseInt(d, 10) - 1 + retObj.tm_mon = month // Also sets wday and yday - _date(); - }); - break; - case 'M': + _date() + }) + break + case 'M': // 00-59 minutes - j = _addNext(j, /^[0-5]\d/, function(d) { - var minute = parseInt(d, 10); - retObj.tm_min = minute; + j = _addNext(j, /^[0-5]\d/, function (d) { + var minute = parseInt(d, 10) + retObj.tm_min = minute // Changes nothing else - }); - break; - case 'P': + }) + break + case 'P': // Seems not to work; AM-PM // Could make fall-through instead since supposed to be a synonym despite PHP docs - return false; - case 'p': + return false + case 'p': // am-pm - j = _addNext(j, /^(am|pm)/i, function(d) { + j = _addNext(j, /^(am|pm)/i, function (d) { // No effect on 'H' since already 24 hours but // works before or after setting of l/I hour - amPmOffset = (/a/) - .test(d) ? 0 : 12; - if (prevHour) { - retObj.tm_hour += amPmOffset; + amPmOffset = (/a/) + .test(d) ? 0 : 12 + if (prevHour) { + retObj.tm_hour += amPmOffset } - }); - break; - case 's': + }) + break + case 's': // Unix timestamp (in seconds) - j = _addNext(j, /^\d+/, function(d) { - var timestamp = parseInt(d, 10); - var date = new Date(Date.UTC(timestamp * 1000)); - _reset(date); + j = _addNext(j, /^\d+/, function (d) { + var timestamp = parseInt(d, 10) + var date = new Date(Date.UTC(timestamp * 1000)) + _reset(date) // Affects all fields, but can't be negative (and initial + not allowed) - }); - break; - case 'S': + }) + break + case 'S': // 00-59 seconds - j = _addNext(j, /^[0-5]\d/, // strptime also accepts 60-61 for some reason + j = _addNext(j, /^[0-5]\d/, // strptime also accepts 60-61 for some reason - function(d) { - var second = parseInt(d, 10); - retObj.tm_sec = second; + function (d) { + var second = parseInt(d, 10) + retObj.tm_sec = second // Changes nothing else - }); - break; - case 'u': + }) + break + case 'u': // Fall-through; 1 (Monday)-7(Sunday) - case 'w': + case 'w': // 0 (Sunday)-6(Saturday) - j = _addNext(j, /^\d/, function(d) { - retObj.tm_wday = d - (formatChar === 'u'); + j = _addNext(j, /^\d/, function (d) { + retObj.tm_wday = d - (formatChar === 'u') // Changes nothing else apparently - }); - break; - case 'U': + }) + break + case 'U': // Fall-through (week of year, from 1st Sunday) - case 'V': + case 'V': // Fall-through (ISO-8601:1988 week number; from first 4-weekday week, starting with Monday) - case 'W': + case 'W': // Apparently ignored (week of year, from 1st Monday) - break; - case 'y': + break + case 'y': // 69 (or higher) for 1969+, 68 (or lower) for 2068- - j = _addNext(j, /^\d?\d/, // PHP docs say two-digit, but accepts one-digit (two-digit max) + j = _addNext(j, /^\d?\d/, // PHP docs say two-digit, but accepts one-digit (two-digit max) - function(d) { - d = parseInt(d, 10); - var year = d >= 69 ? d : d + 100; - retObj.tm_year = year; - _date(); + function (d) { + d = parseInt(d, 10) + var year = d >= 69 ? d : d + 100 + retObj.tm_year = year + _date() if (!retObj.tm_yday) { - retObj.tm_yday = -1; + retObj.tm_yday = -1 } // Also changes wday; and sets yday to -1 (always?) - }); - break; - case 'Y': + }) + break + case 'Y': // 2010 (4-digit year) - j = _addNext(j, /^\d{1,4}/, // PHP docs say four-digit, but accepts one-digit (four-digit max) + j = _addNext(j, /^\d{1,4}/, // PHP docs say four-digit, but accepts one-digit (four-digit max) - function(d) { - var year = (parseInt(d, 10)) - 1900; - retObj.tm_year = year; - _date(); + function (d) { + var year = (parseInt(d, 10)) - 1900 + retObj.tm_year = year + _date() if (!retObj.tm_yday) { - retObj.tm_yday = -1; + retObj.tm_yday = -1 } // Also changes wday; and sets yday to -1 (always?) - }); - break; - case 'z': + }) + break + case 'z': // Timezone; on my system, strftime gives -0800, but strptime seems not to alter hour setting - break; - case 'Z': + break + case 'Z': // Timezone; on my system, strftime gives PST, but strptime treats text as unparsed - break; - default: - throw 'Unrecognized formatting character in strptime()'; + break + default: + throw 'Unrecognized formatting character in strptime()' } } catch (e) { if (e === 'No match in string') { // Allow us to exit // There was supposed to be a matching format but there wasn't - return false; + return false } // Calculate skipping beyond initial percent too - }++i; + }++i } else if (format.charAt(i) !== dateStr.charAt(j)) { // If extra whitespace at beginning or end of either, or between formats, no problem // (just a problem when between % and format specifier) @@ -357,25 +357,25 @@ Oy // If the string has white-space, it is ok to ignore if (dateStr.charAt(j) .search(_WS) !== -1) { - j++; + j++ // Let the next iteration try again with the same format character - i--; + i-- } else if (format.charAt(i) .search(_NWS) !== -1) { // Any extra formatting characters besides white-space causes // problems (do check after WS though, as may just be WS in string before next character) - return false; + return false } // Extra WS in format // Adjust strings when encounter non-matching whitespace, so they align in future checks above // Will check on next iteration (against same (non-WS) string character) } else { - j++; + j++ } } // POST-PROCESSING // Will also get extra whitespace; empty string if none - retObj.unparsed = dateStr.slice(j); - return retObj; -} \ No newline at end of file + retObj.unparsed = dateStr.slice(j) + return retObj +} diff --git a/functions/datetime/strtotime.js b/functions/datetime/strtotime.js index efb5cc2094..6162338ed3 100644 --- a/functions/datetime/strtotime.js +++ b/functions/datetime/strtotime.js @@ -1,4 +1,4 @@ -function strtotime(text, now) { +function strtotime (text, now) { // discuss at: http://phpjs.org/functions/strtotime/ // version: 1109.2016 // original by: Caio Ariede (http://caioariede.com) @@ -28,17 +28,17 @@ function strtotime(text, now) { // example 7: strtotime('2009-05-04T08:30:00Z'); // returns 7: 1241425800 - var parsed, match, today, year, date, days, ranges, len, times, regex, i, fail = false; + var parsed, match, today, year, date, days, ranges, len, times, regex, i, fail = false if (!text) { - return fail; + return fail } // Unecessary spaces text = text.replace(/^\s+|\s+$/g, '') .replace(/\s{2,}/g, ' ') .replace(/[\t\r\n]/g, '') - .toLowerCase(); + .toLowerCase() // in contrast to php, js Date.parse function interprets: // dates given as yyyy-mm-dd as in timezone: UTC, @@ -47,121 +47,131 @@ function strtotime(text, now) { // etc...etc... // ...therefore we manually parse lots of common date formats match = text.match( - /^(\d{1,4})([\-\.\/\:])(\d{1,2})([\-\.\/\:])(\d{1,4})(?:\s(\d{1,2}):(\d{2})?:?(\d{2})?)?(?:\s([A-Z]+)?)?$/); + /^(\d{1,4})([\-\.\/\:])(\d{1,2})([\-\.\/\:])(\d{1,4})(?:\s(\d{1,2}):(\d{2})?:?(\d{2})?)?(?:\s([A-Z]+)?)?$/) if (match && match[2] === match[4]) { if (match[1] > 1901) { switch (match[2]) { - case '-': { - // YYYY-M-D - if (match[3] > 12 || match[5] > 31) { - return fail; - } - - return new Date(match[1], parseInt(match[3], 10) - 1, match[5], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - case '.': { - // YYYY.M.D is not parsed by strtotime() - return fail; - } - case '/': { - // YYYY/M/D - if (match[3] > 12 || match[5] > 31) { - return fail; - } - - return new Date(match[1], parseInt(match[3], 10) - 1, match[5], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } + case '-': + { + // YYYY-M-D + if (match[3] > 12 || match[5] > 31) { + return fail + } + + return new Date(match[1], parseInt(match[3], 10) - 1, match[5], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + case '.': + { + // YYYY.M.D is not parsed by strtotime() + return fail + } + case '/': + { + // YYYY/M/D + if (match[3] > 12 || match[5] > 31) { + return fail + } + + return new Date(match[1], parseInt(match[3], 10) - 1, match[5], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } } } else if (match[5] > 1901) { switch (match[2]) { - case '-': { - // D-M-YYYY - if (match[3] > 12 || match[1] > 31) { - return fail; - } - - return new Date(match[5], parseInt(match[3], 10) - 1, match[1], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - case '.': { - // D.M.YYYY - if (match[3] > 12 || match[1] > 31) { - return fail; - } - - return new Date(match[5], parseInt(match[3], 10) - 1, match[1], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - case '/': { - // M/D/YYYY - if (match[1] > 12 || match[3] > 31) { - return fail; - } - - return new Date(match[5], parseInt(match[1], 10) - 1, match[3], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } + case '-': + { + // D-M-YYYY + if (match[3] > 12 || match[1] > 31) { + return fail + } + + return new Date(match[5], parseInt(match[3], 10) - 1, match[1], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + case '.': + { + // D.M.YYYY + if (match[3] > 12 || match[1] > 31) { + return fail + } + + return new Date(match[5], parseInt(match[3], 10) - 1, match[1], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + case '/': + { + // M/D/YYYY + if (match[1] > 12 || match[3] > 31) { + return fail + } + + return new Date(match[5], parseInt(match[1], 10) - 1, match[3], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } } } else { switch (match[2]) { - case '-': { - // YY-M-D - if (match[3] > 12 || match[5] > 31 || (match[1] < 70 && match[1] > 38)) { - return fail; - } - - year = match[1] >= 0 && match[1] <= 38 ? +match[1] + 2000 : match[1]; - return new Date(year, parseInt(match[3], 10) - 1, match[5], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - case '.': { - // D.M.YY or H.MM.SS - if (match[5] >= 70) { - // D.M.YY - if (match[3] > 12 || match[1] > 31) { - return fail; + case '-': + { + // YY-M-D + if (match[3] > 12 || match[5] > 31 || (match[1] < 70 && match[1] > 38)) { + return fail + } + + year = match[1] >= 0 && match[1] <= 38 ? +match[1] + 2000 : match[1] + return new Date(year, parseInt(match[3], 10) - 1, match[5], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + case '.': + { + // D.M.YY or H.MM.SS + if (match[5] >= 70) { + // D.M.YY + if (match[3] > 12 || match[1] > 31) { + return fail + } + + return new Date(match[5], parseInt(match[3], 10) - 1, match[1], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + if (match[5] < 60 && !match[6]) { + // H.MM.SS + if (match[1] > 23 || match[3] > 59) { + return fail + } + + today = new Date() + return new Date(today.getFullYear(), today.getMonth(), today.getDate(), + match[1] || 0, match[3] || 0, match[5] || 0, match[9] || 0) / 1000 } - return new Date(match[5], parseInt(match[3], 10) - 1, match[1], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - if (match[5] < 60 && !match[6]) { - // H.MM.SS - if (match[1] > 23 || match[3] > 59) { - return fail; + // invalid format, cannot be parsed + return fail + } + case '/': + { + // M/D/YY + if (match[1] > 12 || match[3] > 31 || (match[5] < 70 && match[5] > 38)) { + return fail } - today = new Date(); - return new Date(today.getFullYear(), today.getMonth(), today.getDate(), - match[1] || 0, match[3] || 0, match[5] || 0, match[9] || 0) / 1000; - } + year = match[5] >= 0 && match[5] <= 38 ? +match[5] + 2000 : match[5] + return new Date(year, parseInt(match[1], 10) - 1, match[3], + match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000 + } + case ':': + { + // HH:MM:SS + if (match[1] > 23 || match[3] > 59 || match[5] > 59) { + return fail + } - // invalid format, cannot be parsed - return fail; - } - case '/': { - // M/D/YY - if (match[1] > 12 || match[3] > 31 || (match[5] < 70 && match[5] > 38)) { - return fail; - } - - year = match[5] >= 0 && match[5] <= 38 ? +match[5] + 2000 : match[5]; - return new Date(year, parseInt(match[1], 10) - 1, match[3], - match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000; - } - case ':': { - // HH:MM:SS - if (match[1] > 23 || match[3] > 59 || match[5] > 59) { - return fail; - } - - today = new Date(); - return new Date(today.getFullYear(), today.getMonth(), today.getDate(), - match[1] || 0, match[3] || 0, match[5] || 0) / 1000; - } + today = new Date() + return new Date(today.getFullYear(), today.getMonth(), today.getDate(), + match[1] || 0, match[3] || 0, match[5] || 0) / 1000 + } } } } @@ -169,10 +179,10 @@ function strtotime(text, now) { // other formats and "now" should be parsed by Date.parse() if (text === 'now') { return now === null || isNaN(now) ? new Date() - .getTime() / 1000 | 0 : now | 0; + .getTime() / 1000 | 0 : now | 0 } if (!isNaN(parsed = Date.parse(text))) { - return parsed / 1000 | 0; + return parsed / 1000 | 0 } // Browsers != Chrome have problems parsing ISO 8601 date strings, as they do // not accept lower case characters, space, or shortened time zones. @@ -185,95 +195,95 @@ function strtotime(text, now) { /^([0-9]{4}-[0-9]{2}-[0-9]{2})[ t]([0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?)([\+-][0-9]{2}(:[0-9]{2})?|z)/)) { // fix time zone information if (match[4] == 'z') { - match[4] = 'Z'; + match[4] = 'Z' } else if (match[4].match(/^([\+-][0-9]{2})$/)) { - match[4] = match[4] + ':00'; + match[4] = match[4] + ':00' } if (!isNaN(parsed = Date.parse(match[1] + 'T' + match[2] + match[4]))) { - return parsed / 1000 | 0; + return parsed / 1000 | 0 } } - date = now ? new Date(now * 1000) : new Date(); + date = now ? new Date(now * 1000) : new Date() days = { - 'sun' : 0, - 'mon' : 1, - 'tue' : 2, - 'wed' : 3, - 'thu' : 4, - 'fri' : 5, - 'sat' : 6 - }; + 'sun': 0, + 'mon': 1, + 'tue': 2, + 'wed': 3, + 'thu': 4, + 'fri': 5, + 'sat': 6 + } ranges = { - 'yea' : 'FullYear', - 'mon' : 'Month', - 'day' : 'Date', - 'hou' : 'Hours', - 'min' : 'Minutes', - 'sec' : 'Seconds' - }; + 'yea': 'FullYear', + 'mon': 'Month', + 'day': 'Date', + 'hou': 'Hours', + 'min': 'Minutes', + 'sec': 'Seconds' + } - function lastNext(type, range, modifier) { - var diff, day = days[range]; + function lastNext (type, range, modifier) { + var diff, day = days[range] if (typeof day !== 'undefined') { - diff = day - date.getDay(); + diff = day - date.getDay() if (diff === 0) { - diff = 7 * modifier; + diff = 7 * modifier } else if (diff > 0 && type === 'last') { - diff -= 7; + diff -= 7 } else if (diff < 0 && type === 'next') { - diff += 7; + diff += 7 } - date.setDate(date.getDate() + diff); + date.setDate(date.getDate() + diff) } } - function process(val) { + function process (val) { var splt = val.split(' '), // Todo: Reconcile this with regex using \s, taking into account browser issues with split and regexes type = splt[0], range = splt[1].substring(0, 3), typeIsNumber = /\d+/.test(type), ago = splt[2] === 'ago', - num = (type === 'last' ? -1 : 1) * (ago ? -1 : 1); + num = (type === 'last' ? -1 : 1) * (ago ? -1 : 1) if (typeIsNumber) { - num *= parseInt(type, 10); + num *= parseInt(type, 10) } if (ranges.hasOwnProperty(range) && !splt[1].match(/^mon(day|\.)?$/i)) { - return date['set' + ranges[range]](date['get' + ranges[range]]() + num); + return date['set' + ranges[range]](date['get' + ranges[range]]() + num) } if (range === 'wee') { - return date.setDate(date.getDate() + (num * 7)); + return date.setDate(date.getDate() + (num * 7)) } if (type === 'next' || type === 'last') { - lastNext(type, range, num); + lastNext(type, range, num) } else if (!typeIsNumber) { - return false; + return false } - return true; + return true } times = '(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec' + '|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?' + - '|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)'; - regex = '([+-]?\\d+\\s' + times + '|' + '(last|next)\\s' + times + ')(\\sago)?'; + '|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)' + regex = '([+-]?\\d+\\s' + times + '|' + '(last|next)\\s' + times + ')(\\sago)?' - match = text.match(new RegExp(regex, 'gi')); + match = text.match(new RegExp(regex, 'gi')) if (!match) { - return fail; + return fail } for (i = 0, len = match.length; i < len; i++) { if (!process(match[i])) { - return fail; + return fail } } @@ -281,5 +291,5 @@ function strtotime(text, now) { // if (!match.every(process)) // return false; - return (date.getTime() / 1000); -} \ No newline at end of file + return (date.getTime() / 1000) +} diff --git a/functions/datetime/time.js b/functions/datetime/time.js index 1179e7d1c0..037ce6238b 100644 --- a/functions/datetime/time.js +++ b/functions/datetime/time.js @@ -1,4 +1,4 @@ -function time() { +function time () { // discuss at: http://phpjs.org/functions/time/ // original by: GeekFG (http://geekfg.blogspot.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -9,5 +9,5 @@ function time() { // returns 1: true return Math.floor(new Date() - .getTime() / 1000); -} \ No newline at end of file + .getTime() / 1000) +} diff --git a/functions/exec/escapeshellarg.js b/functions/exec/escapeshellarg.js index 95c9587adc..66fd30fc70 100644 --- a/functions/exec/escapeshellarg.js +++ b/functions/exec/escapeshellarg.js @@ -1,15 +1,15 @@ -function escapeshellarg(arg) { +function escapeshellarg (arg) { // discuss at: http://phpjs.org/functions/escapeshellarg/ // original by: Felix Geisendoerfer (http://www.debuggable.com/felix) // improved by: Brett Zamir (http://brett-zamir.me) // example 1: escapeshellarg("kevin's birthday"); // returns 1: "'kevin\\'s birthday'" - var ret = ''; + var ret = '' - ret = arg.replace(/[^\\]'/g, function(m, i, s) { - return m.slice(0, 1) + '\\\''; - }); + ret = arg.replace(/[^\\]'/g, function (m, i, s) { + return m.slice(0, 1) + '\\\'' + }) - return "'" + ret + "'"; -} \ No newline at end of file + return "'" + ret + "'" +} diff --git a/functions/filesystem/basename.js b/functions/filesystem/basename.js index f74fa6f083..066bc7f24f 100644 --- a/functions/filesystem/basename.js +++ b/functions/filesystem/basename.js @@ -1,4 +1,4 @@ -function basename(path, suffix) { +function basename (path, suffix) { // discuss at: http://phpjs.org/functions/basename/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Ash Searle (http://hexmen.com/blog/) @@ -14,18 +14,18 @@ function basename(path, suffix) { // example 4: basename('/some/path_ext.ext/','.ext'); // returns 4: 'path_ext' - var b = path; - var lastChar = b.charAt(b.length - 1); + var b = path + var lastChar = b.charAt(b.length - 1) if (lastChar === '/' || lastChar === '\\') { - b = b.slice(0, -1); + b = b.slice(0, -1) } - b = b.replace(/^.*[\/\\]/g, ''); + b = b.replace(/^.*[\/\\]/g, '') if (typeof suffix === 'string' && b.substr(b.length - suffix.length) == suffix) { - b = b.substr(0, b.length - suffix.length); + b = b.substr(0, b.length - suffix.length) } - return b; -} \ No newline at end of file + return b +} diff --git a/functions/filesystem/dirname.js b/functions/filesystem/dirname.js index f026e78199..57b55a925c 100644 --- a/functions/filesystem/dirname.js +++ b/functions/filesystem/dirname.js @@ -1,4 +1,4 @@ -function dirname(path) { +function dirname (path) { // discuss at: http://phpjs.org/functions/dirname/ // original by: Ozh // improved by: XoraX (http://www.xorax.info) @@ -10,5 +10,5 @@ function dirname(path) { // returns 3: '/dir' return path.replace(/\\/g, '/') - .replace(/\/[^\/]*\/?$/, ''); -} \ No newline at end of file + .replace(/\/[^\/]*\/?$/, '') +} diff --git a/functions/filesystem/file_get_contents.js b/functions/filesystem/file_get_contents.js index 37d4f882a7..aef2500fae 100644 --- a/functions/filesystem/file_get_contents.js +++ b/functions/filesystem/file_get_contents.js @@ -1,4 +1,4 @@ -function file_get_contents(url, flags, context, offset, maxLen) { +function file_get_contents (url, flags, context, offset, maxLen) { // discuss at: http://phpjs.org/functions/file_get_contents/ // original by: Legaev Andrey // input by: Jani Hartikainen @@ -29,76 +29,76 @@ function file_get_contents(url, flags, context, offset, maxLen) { pathPos = -1, flagNames = 0, content = null, - http_stream = false; - var func = function(value) { - return value.substring(1) !== ''; - }; + http_stream = false + var func = function (value) { + return value.substring(1) !== '' + } // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT - var ini = this.php_js.ini; - context = context || this.php_js.default_streams_context || null; + var ini = this.php_js.ini + context = context || this.php_js.default_streams_context || null if (!flags) { - flags = 0; + flags = 0 } var OPTS = { - FILE_USE_INCLUDE_PATH : 1, - FILE_TEXT : 32, - FILE_BINARY : 64 - }; + FILE_USE_INCLUDE_PATH: 1, + FILE_TEXT: 32, + FILE_BINARY: 64 + } if (typeof flags === 'number') { // Allow for a single string or an array of string flags - flagNames = flags; + flagNames = flags } else { - flags = [].concat(flags); + flags = [].concat(flags) for (i = 0; i < flags.length; i++) { if (OPTS[flags[i]]) { - flagNames = flagNames | OPTS[flags[i]]; + flagNames = flagNames | OPTS[flags[i]] } } } if (flagNames & OPTS.FILE_BINARY && (flagNames & OPTS.FILE_TEXT)) { // These flags shouldn't be together - throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()'; + throw 'You cannot pass both FILE_BINARY and FILE_TEXT to file_get_contents()' } if ((flagNames & OPTS.FILE_USE_INCLUDE_PATH) && ini.include_path && ini.include_path.local_value) { - var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\'; - url = ini.include_path.local_value + slash + url; + var slash = ini.include_path.local_value.indexOf('/') !== -1 ? '/' : '\\' + url = ini.include_path.local_value + slash + url } else if (!/^(https?|file):/.test(url)) { // Allow references within or below the same directory (should fix to allow other relative references or root reference; could make dependent on parse_url()) - href = this.window.location.href; - pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8) - 1 : href.lastIndexOf('/'); - url = href.slice(0, pathPos + 1) + url; + href = this.window.location.href + pathPos = url.indexOf('/') === 0 ? href.indexOf('/', 8) - 1 : href.lastIndexOf('/') + url = href.slice(0, pathPos + 1) + url } - var http_options; + var http_options if (context) { - http_options = context.stream_options && context.stream_options.http; - http_stream = !!http_options; + http_options = context.stream_options && context.stream_options.http + http_stream = !!http_options } if (!context || !context.stream_options || http_stream) { - var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); + var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest() if (!req) { - throw new Error('XMLHttpRequest not supported'); + throw new Error('XMLHttpRequest not supported') } - var method = http_stream ? http_options.method : 'GET'; - var async = !!(context && context.stream_params && context.stream_params['phpjs.async']); + var method = http_stream ? http_options.method : 'GET' + var async = !!(context && context.stream_params && context.stream_params['phpjs.async']) if (ini['phpjs.ajaxBypassCache'] && ini['phpjs.ajaxBypassCache'].local_value) { url += (url.match(/\?/) == null ? '?' : '&') + (new Date()) - .getTime(); // Give optional means of forcing bypass of cache + .getTime() // Give optional means of forcing bypass of cache } - req.open(method, url, async); + req.open(method, url, async) if (async) { - var notification = context.stream_params.notification; + var notification = context.stream_params.notification if (typeof notification === 'function') { // Fix: make work with req.addEventListener if available: https://developer.mozilla.org/En/Using_XMLHttpRequest if (0 && req.addEventListener) { @@ -110,7 +110,7 @@ function file_get_contents(url, flags, context, offset, maxLen) { req.addEventListener('abort', transferCanceled, false); */ } else { - req.onreadystatechange = function(aEvt) { + req.onreadystatechange = function (aEvt) { // aEvt has stopPropagation(), preventDefault(); see https://developer.mozilla.org/en/NsIDOMEvent // Other XMLHttpRequest properties: multipart, responseXML, status, statusText, upload, withCredentials /* @@ -131,76 +131,76 @@ function file_get_contents(url, flags, context, offset, maxLen) { STREAM_NOTIFY_SEVERITY_ERR 2 A critical error occurred. Processing cannot continue. */ var objContext = { - responseText : req.responseText, - responseXML : req.responseXML, - status : req.status, - statusText : req.statusText, - readyState : req.readyState, - evt : aEvt - }; // properties are not available in PHP, but offered on notification via 'this' for convenience + responseText: req.responseText, + responseXML: req.responseXML, + status: req.status, + statusText: req.statusText, + readyState: req.readyState, + evt: aEvt + } // properties are not available in PHP, but offered on notification via 'this' for convenience // notification args: notification_code, severity, message, message_code, bytes_transferred, bytes_max (all int's except string 'message') // Need to add message, etc. - var bytes_transferred; + var bytes_transferred switch (req.readyState) { - case 0: + case 0: // UNINITIALIZED open() has not been called yet. - notification.call(objContext, 0, 0, '', 0, 0, 0); - break; - case 1: + notification.call(objContext, 0, 0, '', 0, 0, 0) + break + case 1: // LOADING send() has not been called yet. - notification.call(objContext, 0, 0, '', 0, 0, 0); - break; - case 2: + notification.call(objContext, 0, 0, '', 0, 0, 0) + break + case 2: // LOADED send() has been called, and headers and status are available. - notification.call(objContext, 0, 0, '', 0, 0, 0); - break; - case 3: + notification.call(objContext, 0, 0, '', 0, 0, 0) + break + case 3: // INTERACTIVE Downloading; responseText holds partial data. // One character is two bytes - bytes_transferred = req.responseText.length * 2; - notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0); - break; - case 4: + bytes_transferred = req.responseText.length * 2 + notification.call(objContext, 7, 0, '', 0, bytes_transferred, 0) + break + case 4: // COMPLETED The operation is complete. - if (req.status >= 200 && req.status < 400) { + if (req.status >= 200 && req.status < 400) { // One character is two bytes - bytes_transferred = req.responseText.length * 2; - notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0); - } else if (req.status === 403) { + bytes_transferred = req.responseText.length * 2 + notification.call(objContext, 8, 0, '', req.status, bytes_transferred, 0) + } else if (req.status === 403) { // Fix: These two are finished except for message - notification.call(objContext, 10, 2, '', req.status, 0, 0); + notification.call(objContext, 10, 2, '', req.status, 0, 0) } else { // Errors - notification.call(objContext, 9, 2, '', req.status, 0, 0); + notification.call(objContext, 9, 2, '', req.status, 0, 0) } - break; - default: - throw 'Unrecognized ready state for file_get_contents()'; + break + default: + throw 'Unrecognized ready state for file_get_contents()' } - }; + } } } } if (http_stream) { - var sendHeaders = (http_options.header && http_options.header.split(/\r?\n/)) || []; - var userAgentSent = false; + var sendHeaders = (http_options.header && http_options.header.split(/\r?\n/)) || [] + var userAgentSent = false for (i = 0; i < sendHeaders.length; i++) { - var sendHeader = sendHeaders[i]; - var breakPos = sendHeader.search(/:\s*/); - var sendHeaderName = sendHeader.substring(0, breakPos); - req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos + 1)); + var sendHeader = sendHeaders[i] + var breakPos = sendHeader.search(/:\s*/) + var sendHeaderName = sendHeader.substring(0, breakPos) + req.setRequestHeader(sendHeaderName, sendHeader.substring(breakPos + 1)) if (sendHeaderName === 'User-Agent') { - userAgentSent = true; + userAgentSent = true } } if (!userAgentSent) { - var user_agent = http_options.user_agent || (ini.user_agent && ini.user_agent.local_value); + var user_agent = http_options.user_agent || (ini.user_agent && ini.user_agent.local_value) if (user_agent) { - req.setRequestHeader('User-Agent', user_agent); + req.setRequestHeader('User-Agent', user_agent) } } - content = http_options.content || null; + content = http_options.content || null /* // Presently unimplemented HTTP context options // When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it. @@ -218,34 +218,34 @@ function file_get_contents(url, flags, context, offset, maxLen) { if (flagNames & OPTS.FILE_TEXT) { // Overrides how encoding is treated (regardless of what is returned from the server) - var content_type = 'text/html'; + var content_type = 'text/html' if (http_options && http_options['phpjs.override']) { // Fix: Could allow for non-HTTP as well // We use this, e.g., in gettext-related functions if character set - content_type = http_options['phpjs.override']; + content_type = http_options['phpjs.override'] // overridden earlier by bind_textdomain_codeset() } else { var encoding = (ini['unicode.stream_encoding'] && ini['unicode.stream_encoding'].local_value) || - 'UTF-8'; + 'UTF-8' if (http_options && http_options.header && (/^content-type:/im) .test(http_options.header)) { // We'll assume a content-type expects its own specified encoding if present // We let any header encoding stand - content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1]; + content_type = http_options.header.match(/^content-type:\s*(.*)$/im)[1] } if (!(/;\s*charset=/) .test(content_type)) { // If no encoding - content_type += '; charset=' + encoding; + content_type += '; charset=' + encoding } } - req.overrideMimeType(content_type); + req.overrideMimeType(content_type) } // Default is FILE_BINARY, but for binary, we apparently deviate from PHP in requiring the flag, since many if not // most people will also want a way to have it be auto-converted into native JavaScript text instead else if (flagNames & OPTS.FILE_BINARY) { // Trick at https://developer.mozilla.org/En/Using_XMLHttpRequest to get binary - req.overrideMimeType('text/plain; charset=x-user-defined'); + req.overrideMimeType('text/plain; charset=x-user-defined') // Getting an individual byte then requires: // throw away high-order byte (f7) where x is 0 to responseText.length-1 (see notes in our substr()) // responseText.charCodeAt(x) & 0xFF; @@ -255,38 +255,38 @@ function file_get_contents(url, flags, context, offset, maxLen) { if (http_options && http_options['phpjs.sendAsBinary']) { // For content sent in a POST or PUT request (use with file_put_contents()?) // In Firefox, only available FF3+ - req.sendAsBinary(content); + req.sendAsBinary(content) } else { - req.send(content); + req.send(content) } } catch (e) { // catches exception reported in issue #66 - return false; + return false } - tmp = req.getAllResponseHeaders(); + tmp = req.getAllResponseHeaders() if (tmp) { - tmp = tmp.split('\n'); + tmp = tmp.split('\n') for (k = 0; k < tmp.length; k++) { if (func(tmp[k])) { - newTmp.push(tmp[k]); + newTmp.push(tmp[k]) } } - tmp = newTmp; + tmp = newTmp for (i = 0; i < tmp.length; i++) { - headers[i] = tmp[i]; + headers[i] = tmp[i] } // see http://php.net/manual/en/reserved.variables.httpresponseheader.php - this.$http_response_header = headers; + this.$http_response_header = headers } if (offset || maxLen) { if (maxLen) { - return req.responseText.substr(offset || 0, maxLen); + return req.responseText.substr(offset || 0, maxLen) } - return req.responseText.substr(offset); + return req.responseText.substr(offset) } - return req.responseText; + return req.responseText } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/filesystem/pathinfo.js b/functions/filesystem/pathinfo.js index 3abc82d079..dfcee8244c 100644 --- a/functions/filesystem/pathinfo.js +++ b/functions/filesystem/pathinfo.js @@ -1,4 +1,4 @@ -function pathinfo(path, options) { +function pathinfo (path, options) { // discuss at: http://phpjs.org/functions/pathinfo/ // original by: Nate // revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -36,106 +36,106 @@ function pathinfo(path, options) { optTemp = 0, tmp_arr = {}, cnt = 0, - i = 0; + i = 0 var have_basename = false, have_extension = false, - have_filename = false; + have_filename = false // Input defaulting & sanitation if (!path) { - return false; + return false } if (!options) { - options = 'PATHINFO_ALL'; + options = 'PATHINFO_ALL' } // Initialize binary arguments. Both the string & integer (constant) input is // allowed var OPTS = { - 'PATHINFO_DIRNAME' : 1, - 'PATHINFO_BASENAME' : 2, - 'PATHINFO_EXTENSION' : 4, - 'PATHINFO_FILENAME' : 8, - 'PATHINFO_ALL' : 0 - }; + 'PATHINFO_DIRNAME': 1, + 'PATHINFO_BASENAME': 2, + 'PATHINFO_EXTENSION': 4, + 'PATHINFO_FILENAME': 8, + 'PATHINFO_ALL': 0 + } // PATHINFO_ALL sums up all previously defined PATHINFOs (could just pre-calculate) for (optName in OPTS) { if (OPTS.hasOwnProperty(optName)) { - OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName]; + OPTS.PATHINFO_ALL = OPTS.PATHINFO_ALL | OPTS[optName] } } if (typeof options !== 'number') { // Allow for a single string or an array of string flags - options = [].concat(options); + options = [].concat(options) for (i = 0; i < options.length; i++) { // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4 if (OPTS[options[i]]) { - optTemp = optTemp | OPTS[options[i]]; + optTemp = optTemp | OPTS[options[i]] } } - options = optTemp; + options = optTemp } // Internal Functions - var __getExt = function(path) { - var str = path + ''; - var dotP = str.lastIndexOf('.') + 1; - return !dotP ? false : dotP !== str.length ? str.substr(dotP) : ''; - }; + var __getExt = function (path) { + var str = path + '' + var dotP = str.lastIndexOf('.') + 1 + return !dotP ? false : dotP !== str.length ? str.substr(dotP) : '' + } // Gather path infos if (options & OPTS.PATHINFO_DIRNAME) { var dirName = path.replace(/\\/g, '/') - .replace(/\/[^\/]*\/?$/, ''); // dirname - tmp_arr.dirname = dirName === path ? '.' : dirName; + .replace(/\/[^\/]*\/?$/, '') // dirname + tmp_arr.dirname = dirName === path ? '.' : dirName } if (options & OPTS.PATHINFO_BASENAME) { if (false === have_basename) { - have_basename = this.basename(path); + have_basename = this.basename(path) } - tmp_arr.basename = have_basename; + tmp_arr.basename = have_basename } if (options & OPTS.PATHINFO_EXTENSION) { if (false === have_basename) { - have_basename = this.basename(path); + have_basename = this.basename(path) } if (false === have_extension) { - have_extension = __getExt(have_basename); + have_extension = __getExt(have_basename) } if (false !== have_extension) { - tmp_arr.extension = have_extension; + tmp_arr.extension = have_extension } } if (options & OPTS.PATHINFO_FILENAME) { if (false === have_basename) { - have_basename = this.basename(path); + have_basename = this.basename(path) } if (false === have_extension) { - have_extension = __getExt(have_basename); + have_extension = __getExt(have_basename) } if (false === have_filename) { have_filename = have_basename.slice(0, have_basename.length - (have_extension ? have_extension.length + 1 : - have_extension === false ? 0 : 1)); + have_extension === false ? 0 : 1)) } - tmp_arr.filename = have_filename; + tmp_arr.filename = have_filename } // If array contains only 1 element: return string - cnt = 0; + cnt = 0 for (opt in tmp_arr) { if (tmp_arr.hasOwnProperty(opt)) { - cnt++; - real_opt = opt; + cnt++ + real_opt = opt } } if (cnt === 1) { - return tmp_arr[real_opt]; + return tmp_arr[real_opt] } // Return full-blown array - return tmp_arr; -} \ No newline at end of file + return tmp_arr +} diff --git a/functions/filesystem/realpath.js b/functions/filesystem/realpath.js index 1f649c6c27..e8307a1d28 100644 --- a/functions/filesystem/realpath.js +++ b/functions/filesystem/realpath.js @@ -1,4 +1,4 @@ -function realpath(path) { +function realpath (path) { // discuss at: http://phpjs.org/functions/realpath/ // original by: mk.keck // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -7,27 +7,27 @@ function realpath(path) { // returns 1: 'file:/home/kevin/code/_supporters/pj_test_supportfile_1.htm' var p = 0, - arr = []; /* Save the root, if not given */ - var r = this.window.location.href; /* Avoid input failures */ + arr = [] /* Save the root, if not given */ + var r = this.window.location.href /* Avoid input failures */ path = (path + '') - .replace('\\', '/'); /* Check if there's a port in path (like 'http://') */ + .replace('\\', '/') /* Check if there's a port in path (like 'http://') */ if (path.indexOf('://') !== -1) { - p = 1; + p = 1 } /* Ok, there's not a port in path, so let's take the root */ if (!p) { - path = r.substring(0, r.lastIndexOf('/') + 1) + path; + path = r.substring(0, r.lastIndexOf('/') + 1) + path } /* Explode the given path into it's parts */ - arr = path.split('/'); /* The path is an array now */ - path = []; /* Foreach part make a check */ + arr = path.split('/') /* The path is an array now */ + path = [] /* Foreach part make a check */ for (var k in arr) { /* This is'nt really interesting */ if (arr[k] == '.') { - continue; + continue } /* This reduces the realpath */ if (arr[k] == '..') { /* But only if there more than 3 parts in the path-array. * The first three parts are for the uri */ if (path.length > 3) { - path.pop(); + path.pop() } } /* This adds parts to the realpath */ else { @@ -35,9 +35,9 @@ function realpath(path) { * (the first three parts ar needed) was not * saved */ if ((path.length < 2) || (arr[k] !== '')) { - path.push(arr[k]); + path.push(arr[k]) } } } /* Returns the absloute path as a string */ - return path.join('/'); -} \ No newline at end of file + return path.join('/') +} diff --git a/functions/funchand/call_user_func.js b/functions/funchand/call_user_func.js index 95cf034ec2..92eb77048d 100644 --- a/functions/funchand/call_user_func.js +++ b/functions/funchand/call_user_func.js @@ -1,4 +1,4 @@ -function call_user_func(cb) { +function call_user_func (cb) { // discuss at: http://phpjs.org/functions/call_user_func/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Diplom@t (http://difane.com/) @@ -6,21 +6,21 @@ function call_user_func(cb) { // example 1: call_user_func('isNaN', 'a'); // returns 1: true - var func; + var func if (typeof cb === 'string') { - func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))(); + func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))() } else if (Object.prototype.toString.call(cb) === '[object Array]') { - func = (typeof cb[0] === 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]]; + func = (typeof cb[0] === 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]] } else if (typeof cb === 'function') { - func = cb; + func = cb } if (typeof func !== 'function') { - throw new Error(func + ' is not a valid function'); + throw new Error(func + ' is not a valid function') } - var parameters = Array.prototype.slice.call(arguments, 1); + var parameters = Array.prototype.slice.call(arguments, 1) return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply( - null, parameters) : func.apply(cb[0], parameters); -} \ No newline at end of file + null, parameters) : func.apply(cb[0], parameters) +} diff --git a/functions/funchand/call_user_func_array.js b/functions/funchand/call_user_func_array.js index d06c121440..83001753d7 100644 --- a/functions/funchand/call_user_func_array.js +++ b/functions/funchand/call_user_func_array.js @@ -1,4 +1,4 @@ -function call_user_func_array(cb, parameters) { +function call_user_func_array (cb, parameters) { // discuss at: http://phpjs.org/functions/call_user_func_array/ // original by: Thiago Mata (http://thiagomata.blog.com) // revised by: Jon Hohle @@ -10,20 +10,20 @@ function call_user_func_array(cb, parameters) { // example 2: call_user_func_array('isNaN', [1]); // returns 2: false - var func; + var func if (typeof cb === 'string') { - func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))(); + func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))() } else if (Object.prototype.toString.call(cb) === '[object Array]') { - func = (typeof cb[0] === 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]]; + func = (typeof cb[0] === 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]] } else if (typeof cb === 'function') { - func = cb; + func = cb } if (typeof func !== 'function') { - throw new Error(func + ' is not a valid function'); + throw new Error(func + ' is not a valid function') } return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply( - null, parameters) : func.apply(cb[0], parameters); -} \ No newline at end of file + null, parameters) : func.apply(cb[0], parameters) +} diff --git a/functions/funchand/create_function.js b/functions/funchand/create_function.js index 920324ce79..79b2c75fac 100644 --- a/functions/funchand/create_function.js +++ b/functions/funchand/create_function.js @@ -1,4 +1,4 @@ -function create_function(args, code) { +function create_function (args, code) { // discuss at: http://phpjs.org/functions/create_function/ // original by: Johnny Mast (http://www.phpvrouwen.nl) // reimplemented by: Brett Zamir (http://brett-zamir.me) @@ -8,8 +8,8 @@ function create_function(args, code) { try { return Function.apply(null, args.split(',') - .concat(code)); + .concat(code)) } catch (e) { - return false; + return false } -} \ No newline at end of file +} diff --git a/functions/funchand/function_exists.js b/functions/funchand/function_exists.js index 984f6c30a5..f75c10c57b 100644 --- a/functions/funchand/function_exists.js +++ b/functions/funchand/function_exists.js @@ -1,4 +1,4 @@ -function function_exists(func_name) { +function function_exists (func_name) { // discuss at: http://phpjs.org/functions/function_exists/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Steve Clay @@ -8,7 +8,7 @@ function function_exists(func_name) { // returns 1: true if (typeof func_name === 'string') { - func_name = this.window[func_name]; + func_name = this.window[func_name] } - return typeof func_name === 'function'; -} \ No newline at end of file + return typeof func_name === 'function' +} diff --git a/functions/funchand/get_defined_functions.js b/functions/funchand/get_defined_functions.js index 7b9779cc21..f2c07ca5b4 100644 --- a/functions/funchand/get_defined_functions.js +++ b/functions/funchand/get_defined_functions.js @@ -1,4 +1,4 @@ -function get_defined_functions() { +function get_defined_functions () { // discuss at: http://phpjs.org/functions/get_defined_functions/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -11,20 +11,20 @@ function get_defined_functions() { var i = '', arr = [], - already = {}; + already = {} for (i in this.window) { try { if (typeof this.window[i] === 'function') { if (!already[i]) { - already[i] = 1; - arr.push(i); + already[i] = 1 + arr.push(i) } } else if (typeof this.window[i] === 'object') { for (var j in this.window[i]) { if (typeof this.window[j] === 'function' && this.window[j] && !already[j]) { - already[j] = 1; - arr.push(j); + already[j] = 1 + arr.push(j) } } } @@ -33,5 +33,5 @@ function get_defined_functions() { } } - return arr; -} \ No newline at end of file + return arr +} diff --git a/functions/i18n/i18n_loc_get_default.js b/functions/i18n/i18n_loc_get_default.js index f49023cbdf..1573aef30e 100644 --- a/functions/i18n/i18n_loc_get_default.js +++ b/functions/i18n/i18n_loc_get_default.js @@ -1,4 +1,4 @@ -function i18n_loc_get_default() { +function i18n_loc_get_default () { // discuss at: http://phpjs.org/functions/i18n_loc_get_default/ // original by: Brett Zamir (http://brett-zamir.me) // note: Renamed in PHP6 from locale_get_default(). Not listed yet at php.net @@ -10,11 +10,11 @@ function i18n_loc_get_default() { // returns 1: 'pt_PT' try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } // Ensure defaults are set up - return this.php_js.i18nLocale || (i18n_loc_set_default('en_US_POSIX'), 'en_US_POSIX'); -} \ No newline at end of file + return this.php_js.i18nLocale || (i18n_loc_set_default('en_US_POSIX'), 'en_US_POSIX') +} diff --git a/functions/i18n/i18n_loc_set_default.js b/functions/i18n/i18n_loc_set_default.js index e8bdd1fb32..0fb3336bb0 100644 --- a/functions/i18n/i18n_loc_set_default.js +++ b/functions/i18n/i18n_loc_set_default.js @@ -1,4 +1,4 @@ -function i18n_loc_set_default(name) { +function i18n_loc_set_default (name) { // discuss at: http://phpjs.org/functions/i18n_loc_set_default/ // original by: Brett Zamir (http://brett-zamir.me) // note: Renamed in PHP6 from locale_set_default(). Not listed yet at php.net @@ -8,18 +8,18 @@ function i18n_loc_set_default(name) { // returns 1: true // BEGIN REDUNDANT - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // END REDUNDANT this.php_js.i18nLocales = { - en_US_POSIX : { - sorting : function(str1, str2) { + en_US_POSIX: { + sorting: function (str1, str2) { // Fix: This one taken from strcmp, but need for other locales; we don't use localeCompare since its locale is not settable - return (str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1); + return (str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1) } } - }; + } - this.php_js.i18nLocale = name; - return true; -} \ No newline at end of file + this.php_js.i18nLocale = name + return true +} diff --git a/functions/info/assert_options.js b/functions/info/assert_options.js index 7f76140bd9..9671253e8c 100644 --- a/functions/info/assert_options.js +++ b/functions/info/assert_options.js @@ -1,47 +1,47 @@ -function assert_options(what, value) { +function assert_options (what, value) { // discuss at: http://phpjs.org/functions/assert_options/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: assert_options('ASSERT_CALLBACK'); // returns 1: null // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; - this.php_js.assert_values = this.php_js.assert_values || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} + this.php_js.assert_values = this.php_js.assert_values || {} // END REDUNDANT - var ini, dflt; + var ini, dflt switch (what) { - case 'ASSERT_ACTIVE': - ini = 'assert.active'; - dflt = 1; - break; - case 'ASSERT_WARNING': - ini = 'assert.warning'; - dflt = 1; - throw 'We have not yet implemented warnings for us to throw in JavaScript (assert_options())'; - case 'ASSERT_BAIL': - ini = 'assert.bail'; - dflt = 0; - break; - case 'ASSERT_QUIET_EVAL': - ini = 'assert.quiet_eval'; - dflt = 0; - break; - case 'ASSERT_CALLBACK': - ini = 'assert.callback'; - dflt = null; - break; - default: - throw 'Improper type for assert_options()'; + case 'ASSERT_ACTIVE': + ini = 'assert.active' + dflt = 1 + break + case 'ASSERT_WARNING': + ini = 'assert.warning' + dflt = 1 + throw 'We have not yet implemented warnings for us to throw in JavaScript (assert_options())' + case 'ASSERT_BAIL': + ini = 'assert.bail' + dflt = 0 + break + case 'ASSERT_QUIET_EVAL': + ini = 'assert.quiet_eval' + dflt = 0 + break + case 'ASSERT_CALLBACK': + ini = 'assert.callback' + dflt = null + break + default: + throw 'Improper type for assert_options()' } // I presume this is to be the most recent value, instead of the default value var originalValue = this.php_js.assert_values[ini] || (this.php_js.ini[ini] && this.php_js.ini[ini].local_value) || - dflt; + dflt if (value) { // We use 'ini' instead of 'what' as key to be more convenient for assert() to test for current value - this.php_js.assert_values[ini] = value; + this.php_js.assert_values[ini] = value } - return originalValue; -} \ No newline at end of file + return originalValue +} diff --git a/functions/info/getenv.js b/functions/info/getenv.js index adfd1eb9df..b4674b76ef 100644 --- a/functions/info/getenv.js +++ b/functions/info/getenv.js @@ -1,4 +1,4 @@ -function getenv(varname) { +function getenv (varname) { // discuss at: http://phpjs.org/functions/getenv/ // original by: Brett Zamir (http://brett-zamir.me) // note: We are not using $_ENV as in PHP, you could define @@ -9,8 +9,8 @@ function getenv(varname) { // returns 1: false if (!this.php_js || !this.php_js.ENV || !this.php_js.ENV[varname]) { - return false; + return false } - return this.php_js.ENV[varname]; -} \ No newline at end of file + return this.php_js.ENV[varname] +} diff --git a/functions/info/getlastmod.js b/functions/info/getlastmod.js index 82b0d7db45..45a62bd197 100644 --- a/functions/info/getlastmod.js +++ b/functions/info/getlastmod.js @@ -1,4 +1,4 @@ -function getlastmod() { +function getlastmod () { // discuss at: http://phpjs.org/functions/getlastmod/ // original by: Brett Zamir (http://brett-zamir.me) // note: Will not work on browsers which don't support document.lastModified @@ -7,5 +7,5 @@ function getlastmod() { // returns 1: 1237610043 return new Date(this.window.document.lastModified) - .getTime() / 1000; -} \ No newline at end of file + .getTime() / 1000 +} diff --git a/functions/info/ini_get.js b/functions/info/ini_get.js index 7a937031dd..168069a202 100644 --- a/functions/info/ini_get.js +++ b/functions/info/ini_get.js @@ -1,4 +1,4 @@ -function ini_get(varname) { +function ini_get (varname) { // discuss at: http://phpjs.org/functions/ini_get/ // original by: Brett Zamir (http://brett-zamir.me) // note: The ini values must be set by ini_set or manually within an ini file @@ -9,10 +9,10 @@ function ini_get(varname) { if (this.php_js && this.php_js.ini && this.php_js.ini[varname] && this.php_js.ini[varname].local_value !== undefined) { if (this.php_js.ini[varname].local_value === null) { - return ''; + return '' } - return this.php_js.ini[varname].local_value; + return this.php_js.ini[varname].local_value } - return ''; -} \ No newline at end of file + return '' +} diff --git a/functions/info/ini_set.js b/functions/info/ini_set.js index 73245384c1..bda3be5722 100644 --- a/functions/info/ini_set.js +++ b/functions/info/ini_set.js @@ -1,4 +1,4 @@ -function ini_set(varname, newvalue) { +function ini_set (varname, newvalue) { // discuss at: http://phpjs.org/functions/ini_set/ // original by: Brett Zamir (http://brett-zamir.me) // note: This will not set a global_value or access level for the ini item @@ -6,40 +6,40 @@ function ini_set(varname, newvalue) { // example 1: ini_set('date.timezone', 'America/Chicago'); // returns 1: 'Asia/Hong_Kong' - var oldval = ''; - var self = this; + var oldval = '' + var self = this try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } - this.php_js.ini = this.php_js.ini || {}; - this.php_js.ini[varname] = this.php_js.ini[varname] || {}; + this.php_js.ini = this.php_js.ini || {} + this.php_js.ini[varname] = this.php_js.ini[varname] || {} - oldval = this.php_js.ini[varname].local_value; + oldval = this.php_js.ini[varname].local_value - var _setArr = function(oldval) { + var _setArr = function (oldval) { // Although these are set individually, they are all accumulated if (typeof oldval === 'undefined') { - self.php_js.ini[varname].local_value = []; + self.php_js.ini[varname].local_value = [] } - self.php_js.ini[varname].local_value.push(newvalue); - }; + self.php_js.ini[varname].local_value.push(newvalue) + } switch (varname) { - case 'extension': - if (typeof this.dl === 'function') { + case 'extension': + if (typeof this.dl === 'function') { // This function is only experimental in php.js - this.dl(newvalue); - } - _setArr(oldval, newvalue); - break; - default: - this.php_js.ini[varname].local_value = newvalue; - break; + this.dl(newvalue) + } + _setArr(oldval, newvalue) + break + default: + this.php_js.ini[varname].local_value = newvalue + break } - return oldval; -} \ No newline at end of file + return oldval +} diff --git a/functions/info/set_time_limit.js b/functions/info/set_time_limit.js index ff36e33d17..3d4cac196e 100644 --- a/functions/info/set_time_limit.js +++ b/functions/info/set_time_limit.js @@ -1,4 +1,4 @@ -function set_time_limit(seconds) { +function set_time_limit (seconds) { // discuss at: http://phpjs.org/functions/set_time_limit/ // original by: Brett Zamir (http://brett-zamir.me) // test: skip @@ -6,13 +6,13 @@ function set_time_limit(seconds) { // returns 1: undefined // BEGIN REDUNDANT - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // END REDUNDANT - this.window.setTimeout(function() { + this.window.setTimeout(function () { if (!this.php_js.timeoutStatus) { - this.php_js.timeoutStatus = true; + this.php_js.timeoutStatus = true } - throw 'Maximum execution time exceeded'; - }, seconds * 1000); -} \ No newline at end of file + throw 'Maximum execution time exceeded' + }, seconds * 1000) +} diff --git a/functions/info/version_compare.js b/functions/info/version_compare.js index 0581df3a39..bbaaae1c5a 100644 --- a/functions/info/version_compare.js +++ b/functions/info/version_compare.js @@ -1,4 +1,4 @@ -function version_compare(v1, v2, operator) { +function version_compare (v1, v2, operator) { // discuss at: http://phpjs.org/functions/version_compare/ // original by: Philippe Jausions (http://pear.php.net/user/jausions) // original by: Aidan Lister (http://aidanlister.com/) @@ -15,8 +15,8 @@ function version_compare(v1, v2, operator) { // example 4: version_compare('4.1.0.52','4.01.0.51'); // returns 4: 1 - this.php_js = this.php_js || {}; - this.php_js.ENV = this.php_js.ENV || {}; + this.php_js = this.php_js || {} + this.php_js.ENV = this.php_js.ENV || {} // END REDUNDANT // Important: compare must be initialized at 0. var i, @@ -30,16 +30,16 @@ function version_compare(v1, v2, operator) { // If a non-numerical value can't be mapped to this table, it receives // -7 as its value. vm = { - 'dev' : -6, - 'alpha' : -5, - 'a' : -5, - 'beta' : -4, - 'b' : -4, - 'RC' : -3, - 'rc' : -3, - '#' : -2, - 'p' : 1, - 'pl' : 1 + 'dev': -6, + 'alpha': -5, + 'a': -5, + 'beta': -4, + 'b': -4, + 'RC': -3, + 'rc': -3, + '#': -2, + 'p': 1, + 'pl': 1 }, // This function will be called to prepare each version argument. // It replaces every _, -, and + with a dot. @@ -50,67 +50,67 @@ function version_compare(v1, v2, operator) { // even less than an unexisting value in vm (-7), hence [-8]. // It's also important to not strip spaces because of this. // version_compare('', ' ') == 1 - prepVersion = function(v) { + prepVersion = function (v) { v = ('' + v) - .replace(/[_\-+]/g, '.'); + .replace(/[_\-+]/g, '.') v = v.replace(/([^.\d]+)/g, '.$1.') - .replace(/\.{2,}/g, '.'); - return (!v.length ? [-8] : v.split('.')); + .replace(/\.{2,}/g, '.') + return (!v.length ? [-8] : v.split('.')) }, - // This converts a version component to a number. - // Empty component becomes 0. - // Non-numerical component becomes a negative number. - // Numerical component becomes itself as an integer. - numVersion = function(v) { - return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)); - }; - v1 = prepVersion(v1); - v2 = prepVersion(v2); - x = Math.max(v1.length, v2.length); + // This converts a version component to a number. + // Empty component becomes 0. + // Non-numerical component becomes a negative number. + // Numerical component becomes itself as an integer. + numVersion = function (v) { + return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)) + } + v1 = prepVersion(v1) + v2 = prepVersion(v2) + x = Math.max(v1.length, v2.length) for (i = 0; i < x; i++) { if (v1[i] == v2[i]) { - continue; + continue } - v1[i] = numVersion(v1[i]); - v2[i] = numVersion(v2[i]); + v1[i] = numVersion(v1[i]) + v2[i] = numVersion(v2[i]) if (v1[i] < v2[i]) { - compare = -1; - break; + compare = -1 + break } else if (v1[i] > v2[i]) { - compare = 1; - break; + compare = 1 + break } } if (!operator) { - return compare; + return compare } // Important: operator is CASE-SENSITIVE. // "No operator" seems to be treated as "<." // Any other values seem to make the function return null. switch (operator) { - case '>': - case 'gt': - return (compare > 0); - case '>=': - case 'ge': - return (compare >= 0); - case '<=': - case 'le': - return (compare <= 0); - case '==': - case '=': - case 'eq': - return (compare === 0); - case '<>': - case '!=': - case 'ne': - return (compare !== 0); - case '': - case '<': - case 'lt': - return (compare < 0); - default: - return null; + case '>': + case 'gt': + return (compare > 0) + case '>=': + case 'ge': + return (compare >= 0) + case '<=': + case 'le': + return (compare <= 0) + case '==': + case '=': + case 'eq': + return (compare === 0) + case '<>': + case '!=': + case 'ne': + return (compare !== 0) + case '': + case '<': + case 'lt': + return (compare < 0) + default: + return null } } diff --git a/functions/json/json_decode.js b/functions/json/json_decode.js index 02c8d48ff0..ff6217eb37 100644 --- a/functions/json/json_decode.js +++ b/functions/json/json_decode.js @@ -1,4 +1,4 @@ -function json_decode(str_json) { +function json_decode (str_json) { // discuss at: http://phpjs.org/functions/json_decode/ // original by: Public Domain (http://www.json.org/json2.js) // reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -8,42 +8,42 @@ function json_decode(str_json) { // returns 1: [1] /* - http://www.JSON.org/json2.js - 2008-11-19 - Public Domain. - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - See http://www.JSON.org/js.html - */ + http://www.JSON.org/json2.js + 2008-11-19 + Public Domain. + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + See http://www.JSON.org/js.html + */ - var json = this.window.JSON; + var json = this.window.JSON if (typeof json === 'object' && typeof json.parse === 'function') { try { - return json.parse(str_json); + return json.parse(str_json) } catch (err) { if (!(err instanceof SyntaxError)) { - throw new Error('Unexpected error type in json_decode()'); + throw new Error('Unexpected error type in json_decode()') } - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // usable by json_last_error() - this.php_js.last_error_json = 4; - return null; + this.php_js.last_error_json = 4 + return null } } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - var j; - var text = str_json; + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + var j + var text = str_json // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. - cx.lastIndex = 0; + cx.lastIndex = 0 if (cx.test(text)) { - text = text.replace(cx, function(a) { + text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0) .toString(16)) - .slice(-4); - }); + .slice(-4) + }) } // In the second stage, we run the text against regular expressions that look @@ -66,13 +66,13 @@ function json_decode(str_json) { // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. - j = eval('(' + text + ')'); + j = eval('(' + text + ')') - return j; + return j } - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // usable by json_last_error() - this.php_js.last_error_json = 4; - return null; -} \ No newline at end of file + this.php_js.last_error_json = 4 + return null +} diff --git a/functions/json/json_encode.js b/functions/json/json_encode.js index 2999184cf7..8ff5b25a79 100644 --- a/functions/json/json_encode.js +++ b/functions/json/json_encode.js @@ -1,4 +1,4 @@ -function json_encode(mixed_val) { +function json_encode (mixed_val) { // discuss at: http://phpjs.org/functions/json_encode/ // original by: Public Domain (http://www.json.org/json2.js) // reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -9,158 +9,158 @@ function json_encode(mixed_val) { // returns 1: '"Kevin"' /* - http://www.JSON.org/json2.js - 2008-11-19 - Public Domain. - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - See http://www.JSON.org/js.html - */ - var retVal, json = this.window.JSON; + http://www.JSON.org/json2.js + 2008-11-19 + Public Domain. + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + See http://www.JSON.org/js.html + */ + var retVal, json = this.window.JSON try { if (typeof json === 'object' && typeof json.stringify === 'function') { // Errors will not be caught here if our own equivalent to resource - retVal = json.stringify(mixed_val); + retVal = json.stringify(mixed_val) // (an instance of PHPJS_Resource) is used if (retVal === undefined) { - throw new SyntaxError('json_encode'); + throw new SyntaxError('json_encode') } - return retVal; + return retVal } - var value = mixed_val; + var value = mixed_val - var quote = function(string) { + var quote = function (string) { var escapable = - /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; + /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g var meta = { // table of character substitutions - '\b' : '\\b', - '\t' : '\\t', - '\n' : '\\n', - '\f' : '\\f', - '\r' : '\\r', - '"' : '\\"', - '\\' : '\\\\' - }; - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function(a) { - var c = meta[a]; + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"': '\\"', + '\\': '\\\\' + } + + escapable.lastIndex = 0 + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a] return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0) .toString(16)) - .slice(-4); - }) + '"' : '"' + string + '"'; - }; + .slice(-4) + }) + '"' : '"' + string + '"' + } - var str = function(key, holder) { - var gap = ''; - var indent = ' '; + var str = function (key, holder) { + var gap = '' + var indent = ' ' // The loop counter. - var i = 0; + var i = 0 // The member key. - var k = ''; + var k = '' // The member value. - var v = ''; - var length = 0; - var mind = gap; - var partial = []; - var value = holder[key]; + var v = '' + var length = 0 + var mind = gap + var partial = [] + var value = holder[key] // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { - value = value.toJSON(key); + value = value.toJSON(key) } // What happens next depends on the value's type. switch (typeof value) { - case 'string': - return quote(value); + case 'string': + return quote(value) - case 'number': + case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. - return isFinite(value) ? String(value) : 'null'; + return isFinite(value) ? String(value) : 'null' - case 'boolean': - case 'null': + case 'boolean': + case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. - return String(value); + return String(value) - case 'object': + case 'object': // If the type is 'object', we might be dealing with an object or an array or // null. // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. - if (!value) { - return 'null'; - } - if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) || (window.PHPJS_Resource && + if (!value) { + return 'null' + } + if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) || (window.PHPJS_Resource && value instanceof window.PHPJS_Resource)) { - throw new SyntaxError('json_encode'); - } + throw new SyntaxError('json_encode') + } // Make an array to hold the partial results of stringifying this object value. - gap += indent; - partial = []; + gap += indent + partial = [] // Is the value an array? - if (Object.prototype.toString.apply(value) === '[object Array]') { + if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; + length = value.length + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null' } // Join all of the elements together, separated with commas, and wrap them in // brackets. - v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + - ']' : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + + ']' : '[' + partial.join(',') + ']' + gap = mind + return v + } // Iterate through all of the keys in the object. - for (k in value) { - if (Object.hasOwnProperty.call(value, k)) { - v = str(k, value); + for (k in value) { + if (Object.hasOwnProperty.call(value, k)) { + v = str(k, value) if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); + partial.push(quote(k) + (gap ? ': ' : ':') + v) } } - } + } // Join all of the member texts together, separated with commas, // and wrap them in braces. - v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - case 'undefined': + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : + '{' + partial.join(',') + '}' + gap = mind + return v + case 'undefined': // Fall-through - case 'function': + case 'function': // Fall-through - default: - throw new SyntaxError('json_encode'); + default: + throw new SyntaxError('json_encode') } - }; + } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', { - '' : value - }); + '': value + }) } catch (err) { // Todo: ensure error handling above throws a SyntaxError in all cases where it could // (i.e., when the JSON global is not available and there is an error) if (!(err instanceof SyntaxError)) { - throw new Error('Unexpected error type in json_encode()'); + throw new Error('Unexpected error type in json_encode()') } - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // usable by json_last_error() - this.php_js.last_error_json = 4; - return null; + this.php_js.last_error_json = 4 + return null } -} \ No newline at end of file +} diff --git a/functions/json/json_last_error.js b/functions/json/json_last_error.js index 6b39b4c765..56768f1f65 100644 --- a/functions/json/json_last_error.js +++ b/functions/json/json_last_error.js @@ -1,16 +1,16 @@ -function json_last_error() { +function json_last_error () { // discuss at: http://phpjs.org/functions/json_last_error/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: json_last_error(); // returns 1: 0 /* - JSON_ERROR_NONE = 0 - JSON_ERROR_DEPTH = 1 // max depth limit to be removed per PHP comments in json.c (not possible in JS?) - JSON_ERROR_STATE_MISMATCH = 2 // internal use? also not documented - JSON_ERROR_CTRL_CHAR = 3 // [\u0000-\u0008\u000B-\u000C\u000E-\u001F] if used directly within json_decode(), - // but JSON functions auto-escape these, so error not possible in JavaScript - JSON_ERROR_SYNTAX = 4 - */ - return this.php_js && this.php_js.last_error_json ? this.php_js.last_error_json : 0; -} \ No newline at end of file + JSON_ERROR_NONE = 0 + JSON_ERROR_DEPTH = 1 // max depth limit to be removed per PHP comments in json.c (not possible in JS?) + JSON_ERROR_STATE_MISMATCH = 2 // internal use? also not documented + JSON_ERROR_CTRL_CHAR = 3 // [\u0000-\u0008\u000B-\u000C\u000E-\u001F] if used directly within json_decode(), + // but JSON functions auto-escape these, so error not possible in JavaScript + JSON_ERROR_SYNTAX = 4 + */ + return this.php_js && this.php_js.last_error_json ? this.php_js.last_error_json : 0 +} diff --git a/functions/math/abs.js b/functions/math/abs.js index 2b36dfab2c..5f977c8005 100644 --- a/functions/math/abs.js +++ b/functions/math/abs.js @@ -1,4 +1,4 @@ -function abs(mixed_number) { +function abs (mixed_number) { // discuss at: http://phpjs.org/functions/abs/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // improved by: Karol Kowalski @@ -13,5 +13,5 @@ function abs(mixed_number) { // example 4: abs('_argos'); // returns 4: 0 - return Math.abs(mixed_number) || 0; -} \ No newline at end of file + return Math.abs(mixed_number) || 0 +} diff --git a/functions/math/acos.js b/functions/math/acos.js index dbfb1db762..4bf3e296c1 100644 --- a/functions/math/acos.js +++ b/functions/math/acos.js @@ -1,9 +1,9 @@ -function acos(arg) { +function acos (arg) { // discuss at: http://phpjs.org/functions/acos/ // original by: Onno Marsman // note: Sorry about the crippled test. Needed because precision differs accross platforms. // example 1: (acos(0.3) + '').substr(0, 17); // returns 1: "1.266103672779499" - return Math.acos(arg); -} \ No newline at end of file + return Math.acos(arg) +} diff --git a/functions/math/acosh.js b/functions/math/acosh.js index 30d7923301..e262d087d6 100644 --- a/functions/math/acosh.js +++ b/functions/math/acosh.js @@ -1,8 +1,8 @@ -function acosh(arg) { +function acosh (arg) { // discuss at: http://phpjs.org/functions/acosh/ // original by: Onno Marsman // example 1: acosh(8723321.4); // returns 1: 16.674657798418625 - return Math.log(arg + Math.sqrt(arg * arg - 1)); -} \ No newline at end of file + return Math.log(arg + Math.sqrt(arg * arg - 1)) +} diff --git a/functions/math/asin.js b/functions/math/asin.js index 27c670b0d2..757fbc4102 100644 --- a/functions/math/asin.js +++ b/functions/math/asin.js @@ -1,9 +1,9 @@ -function asin(arg) { +function asin (arg) { // discuss at: http://phpjs.org/functions/asin/ // original by: Onno Marsman // note: Sorry about the crippled test. Needed because precision differs accross platforms. // example 1: (asin(0.3) + '').substr(0, 17); // returns 1: "0.304692654015397" - return Math.asin(arg); -} \ No newline at end of file + return Math.asin(arg) +} diff --git a/functions/math/asinh.js b/functions/math/asinh.js index d588cf5cbd..ec60d717f2 100644 --- a/functions/math/asinh.js +++ b/functions/math/asinh.js @@ -1,8 +1,8 @@ -function asinh(arg) { +function asinh (arg) { // discuss at: http://phpjs.org/functions/asinh/ // original by: Onno Marsman // example 1: asinh(8723321.4); // returns 1: 16.67465779841863 - return Math.log(arg + Math.sqrt(arg * arg + 1)); -} \ No newline at end of file + return Math.log(arg + Math.sqrt(arg * arg + 1)) +} diff --git a/functions/math/atan.js b/functions/math/atan.js index bb18bd374c..8ec618758f 100644 --- a/functions/math/atan.js +++ b/functions/math/atan.js @@ -1,8 +1,8 @@ -function atan(arg) { +function atan (arg) { // discuss at: http://phpjs.org/functions/atan/ // original by: Onno Marsman // example 1: atan(8723321.4); // returns 1: 1.5707962121596615 - return Math.atan(arg); -} \ No newline at end of file + return Math.atan(arg) +} diff --git a/functions/math/atan2.js b/functions/math/atan2.js index b2e1b8411f..70882f40f8 100644 --- a/functions/math/atan2.js +++ b/functions/math/atan2.js @@ -1,8 +1,8 @@ -function atan2(y, x) { +function atan2 (y, x) { // discuss at: http://phpjs.org/functions/atan2/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: atan2(1, 1); // returns 1: 0.7853981633974483 - return Math.atan2(y, x); -} \ No newline at end of file + return Math.atan2(y, x) +} diff --git a/functions/math/atanh.js b/functions/math/atanh.js index 1ee14b2872..d4f76b4a60 100644 --- a/functions/math/atanh.js +++ b/functions/math/atanh.js @@ -1,8 +1,8 @@ -function atanh(arg) { +function atanh (arg) { // discuss at: http://phpjs.org/functions/atanh/ // original by: Onno Marsman // example 1: atanh(0.3); // returns 1: 0.3095196042031118 - return 0.5 * Math.log((1 + arg) / (1 - arg)); -} \ No newline at end of file + return 0.5 * Math.log((1 + arg) / (1 - arg)) +} diff --git a/functions/math/base_convert.js b/functions/math/base_convert.js index d2218d49d7..0dbc93f5f0 100644 --- a/functions/math/base_convert.js +++ b/functions/math/base_convert.js @@ -1,4 +1,4 @@ -function base_convert(number, frombase, tobase) { +function base_convert (number, frombase, tobase) { // discuss at: http://phpjs.org/functions/base_convert/ // original by: Philippe Baumann // improved by: Rafał Kukawski (http://blog.kukawski.pl) @@ -6,5 +6,5 @@ function base_convert(number, frombase, tobase) { // returns 1: '101000110111001100110100' return parseInt(number + '', frombase | 0) - .toString(tobase | 0); -} \ No newline at end of file + .toString(tobase | 0) +} diff --git a/functions/math/bindec.js b/functions/math/bindec.js index 72200840e4..53a14aa50e 100644 --- a/functions/math/bindec.js +++ b/functions/math/bindec.js @@ -1,4 +1,4 @@ -function bindec(binary_string) { +function bindec (binary_string) { // discuss at: http://phpjs.org/functions/bindec/ // original by: Philippe Baumann // example 1: bindec('110011'); @@ -9,6 +9,6 @@ function bindec(binary_string) { // returns 3: 7 binary_string = (binary_string + '') - .replace(/[^01]/gi, ''); - return parseInt(binary_string, 2); -} \ No newline at end of file + .replace(/[^01]/gi, '') + return parseInt(binary_string, 2) +} diff --git a/functions/math/ceil.js b/functions/math/ceil.js index a0c5a392a9..fe8ebb94ad 100644 --- a/functions/math/ceil.js +++ b/functions/math/ceil.js @@ -1,8 +1,8 @@ -function ceil(value) { +function ceil (value) { // discuss at: http://phpjs.org/functions/ceil/ // original by: Onno Marsman // example 1: ceil(8723321.4); // returns 1: 8723322 - return Math.ceil(value); -} \ No newline at end of file + return Math.ceil(value) +} diff --git a/functions/math/cos.js b/functions/math/cos.js index 68efa79e56..627dae1772 100644 --- a/functions/math/cos.js +++ b/functions/math/cos.js @@ -1,8 +1,8 @@ -function cos(arg) { +function cos (arg) { // discuss at: http://phpjs.org/functions/cos/ // original by: Onno Marsman // example 1: Math.ceil(cos(8723321.4) * 10000000); // returns 1: -1812718 - return Math.cos(arg); -} \ No newline at end of file + return Math.cos(arg) +} diff --git a/functions/math/cosh.js b/functions/math/cosh.js index b7229de184..ad10dc060b 100644 --- a/functions/math/cosh.js +++ b/functions/math/cosh.js @@ -1,8 +1,8 @@ -function cosh(arg) { +function cosh (arg) { // discuss at: http://phpjs.org/functions/cosh/ // original by: Onno Marsman // example 1: cosh(-0.18127180117607017); // returns 1: 1.0164747716114113 - return (Math.exp(arg) + Math.exp(-arg)) / 2; -} \ No newline at end of file + return (Math.exp(arg) + Math.exp(-arg)) / 2 +} diff --git a/functions/math/decbin.js b/functions/math/decbin.js index 007d72d580..c889b68f75 100644 --- a/functions/math/decbin.js +++ b/functions/math/decbin.js @@ -1,4 +1,4 @@ -function decbin(number) { +function decbin (number) { // discuss at: http://phpjs.org/functions/decbin/ // original by: Enrique Gonzalez // bugfixed by: Onno Marsman @@ -13,8 +13,8 @@ function decbin(number) { // returns 3: '11010' if (number < 0) { - number = 0xFFFFFFFF + number + 1; + number = 0xFFFFFFFF + number + 1 } return parseInt(number, 10) - .toString(2); -} \ No newline at end of file + .toString(2) +} diff --git a/functions/math/dechex.js b/functions/math/dechex.js index 856784c87c..df7e2187a1 100644 --- a/functions/math/dechex.js +++ b/functions/math/dechex.js @@ -1,4 +1,4 @@ -function dechex(number) { +function dechex (number) { // discuss at: http://phpjs.org/functions/dechex/ // original by: Philippe Baumann // bugfixed by: Onno Marsman @@ -12,8 +12,8 @@ function dechex(number) { // returns 3: 'ab9dc427' if (number < 0) { - number = 0xFFFFFFFF + number + 1; + number = 0xFFFFFFFF + number + 1 } return parseInt(number, 10) - .toString(16); -} \ No newline at end of file + .toString(16) +} diff --git a/functions/math/decoct.js b/functions/math/decoct.js index 80fdf8b050..423e3aca3a 100644 --- a/functions/math/decoct.js +++ b/functions/math/decoct.js @@ -1,4 +1,4 @@ -function decoct(number) { +function decoct (number) { // discuss at: http://phpjs.org/functions/decoct/ // original by: Enrique Gonzalez // bugfixed by: Onno Marsman @@ -10,8 +10,8 @@ function decoct(number) { // returns 2: '410' if (number < 0) { - number = 0xFFFFFFFF + number + 1; + number = 0xFFFFFFFF + number + 1 } return parseInt(number, 10) - .toString(8); -} \ No newline at end of file + .toString(8) +} diff --git a/functions/math/deg2rad.js b/functions/math/deg2rad.js index 98a0dc2cad..ce42d3671d 100644 --- a/functions/math/deg2rad.js +++ b/functions/math/deg2rad.js @@ -1,9 +1,9 @@ -function deg2rad(angle) { +function deg2rad (angle) { // discuss at: http://phpjs.org/functions/deg2rad/ // original by: Enrique Gonzalez // improved by: Thomas Grainger (http://graingert.co.uk) // example 1: deg2rad(45); // returns 1: 0.7853981633974483 - return angle * .017453292519943295; // (angle / 180) * Math.PI; -} \ No newline at end of file + return angle * .017453292519943295 // (angle / 180) * Math.PI; +} diff --git a/functions/math/exp.js b/functions/math/exp.js index 9acab57536..03f6807674 100644 --- a/functions/math/exp.js +++ b/functions/math/exp.js @@ -1,8 +1,8 @@ -function exp(arg) { +function exp (arg) { // discuss at: http://phpjs.org/functions/exp/ // original by: Onno Marsman // example 1: exp(0.3); // returns 1: 1.3498588075760032 - return Math.exp(arg); -} \ No newline at end of file + return Math.exp(arg) +} diff --git a/functions/math/expm1.js b/functions/math/expm1.js index 09208496d6..04dc84b12b 100644 --- a/functions/math/expm1.js +++ b/functions/math/expm1.js @@ -1,4 +1,4 @@ -function expm1(x) { +function expm1 (x) { // discuss at: http://phpjs.org/functions/expm1/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Robert Eisele (http://www.xarg.org/) @@ -6,5 +6,5 @@ function expm1(x) { // example 1: expm1(1e-15); // returns 1: 1.0000000000000007e-15 - return (x < 1e-5 && -1e-5 < x) ? x + 0.5 * x * x : Math.exp(x) - 1; -} \ No newline at end of file + return (x < 1e-5 && -1e-5 < x) ? x + 0.5 * x * x : Math.exp(x) - 1 +} diff --git a/functions/math/floor.js b/functions/math/floor.js index 42219c11b6..eeb70a971c 100644 --- a/functions/math/floor.js +++ b/functions/math/floor.js @@ -1,8 +1,8 @@ -function floor(value) { +function floor (value) { // discuss at: http://phpjs.org/functions/floor/ // original by: Onno Marsman // example 1: floor(8723321.4); // returns 1: 8723321 - return Math.floor(value); -} \ No newline at end of file + return Math.floor(value) +} diff --git a/functions/math/fmod.js b/functions/math/fmod.js index 3c327cca28..f3c95312da 100644 --- a/functions/math/fmod.js +++ b/functions/math/fmod.js @@ -1,4 +1,4 @@ -function fmod(x, y) { +function fmod (x, y) { // discuss at: http://phpjs.org/functions/fmod/ // original by: Onno Marsman // input by: Brett Zamir (http://brett-zamir.me) @@ -9,31 +9,31 @@ function fmod(x, y) { var tmp, tmp2, p = 0, pY = 0, l = 0.0, - l2 = 0.0; + l2 = 0.0 tmp = x.toExponential() - .match(/^.\.?(.*)e(.+)$/); + .match(/^.\.?(.*)e(.+)$/) p = parseInt(tmp[2], 10) - (tmp[1] + '') - .length; + .length tmp = y.toExponential() - .match(/^.\.?(.*)e(.+)$/); + .match(/^.\.?(.*)e(.+)$/) pY = parseInt(tmp[2], 10) - (tmp[1] + '') - .length; + .length if (pY > p) { - p = pY; + p = pY } - tmp2 = (x % y); + tmp2 = (x % y) if (p < -100 || p > 20) { // toFixed will give an out of bound error so we fix it like this: - l = Math.round(Math.log(tmp2) / Math.log(10)); - l2 = Math.pow(10, l); + l = Math.round(Math.log(tmp2) / Math.log(10)) + l2 = Math.pow(10, l) return (tmp2 / l2) - .toFixed(l - p) * l2; + .toFixed(l - p) * l2 } else { - return parseFloat(tmp2.toFixed(-p)); + return parseFloat(tmp2.toFixed(-p)) } -} \ No newline at end of file +} diff --git a/functions/math/getrandmax.js b/functions/math/getrandmax.js index ecc5ff8db1..4d30faf3f9 100644 --- a/functions/math/getrandmax.js +++ b/functions/math/getrandmax.js @@ -1,8 +1,8 @@ -function getrandmax() { +function getrandmax () { // discuss at: http://phpjs.org/functions/getrandmax/ // original by: Onno Marsman // example 1: getrandmax(); // returns 1: 2147483647 - return 2147483647; -} \ No newline at end of file + return 2147483647 +} diff --git a/functions/math/hexdec.js b/functions/math/hexdec.js index 911ecd12f9..fc15890fa8 100644 --- a/functions/math/hexdec.js +++ b/functions/math/hexdec.js @@ -1,4 +1,4 @@ -function hexdec(hex_string) { +function hexdec (hex_string) { // discuss at: http://phpjs.org/functions/hexdec/ // original by: Philippe Baumann // example 1: hexdec('that'); @@ -7,6 +7,6 @@ function hexdec(hex_string) { // returns 2: 160 hex_string = (hex_string + '') - .replace(/[^a-f0-9]/gi, ''); - return parseInt(hex_string, 16); -} \ No newline at end of file + .replace(/[^a-f0-9]/gi, '') + return parseInt(hex_string, 16) +} diff --git a/functions/math/hypot.js b/functions/math/hypot.js index a641a0cd5a..86c4ad78f5 100644 --- a/functions/math/hypot.js +++ b/functions/math/hypot.js @@ -1,4 +1,4 @@ -function hypot(x, y) { +function hypot (x, y) { // discuss at: http://phpjs.org/functions/hypot/ // original by: Onno Marsman // imprived by: Robert Eisele (http://www.xarg.org/) @@ -7,12 +7,12 @@ function hypot(x, y) { // example 2: hypot([], 'a'); // returns 2: null - x = Math.abs(x); - y = Math.abs(y); + x = Math.abs(x) + y = Math.abs(y) - var t = Math.min(x, y); - x = Math.max(x, y); - t = t / x; + var t = Math.min(x, y) + x = Math.max(x, y) + t = t / x - return x * Math.sqrt(1 + t * t) || null; -} \ No newline at end of file + return x * Math.sqrt(1 + t * t) || null +} diff --git a/functions/math/is_finite.js b/functions/math/is_finite.js index cfa0e21bdb..2a98ffb973 100644 --- a/functions/math/is_finite.js +++ b/functions/math/is_finite.js @@ -1,4 +1,4 @@ -function is_finite(val) { +function is_finite (val) { // discuss at: http://phpjs.org/functions/is_finite/ // original by: Onno Marsman // example 1: is_finite(Infinity); @@ -8,22 +8,22 @@ function is_finite(val) { // example 3: is_finite(0); // returns 3: true - var warningType = ''; + var warningType = '' if (val === Infinity || val === -Infinity) { - return false; + return false } - //Some warnings for maximum PHP compatibility + // Some warnings for maximum PHP compatibility if (typeof val === 'object') { - warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object'); + warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object') } else if (typeof val === 'string' && !val.match(/^[\+\-]?\d/)) { - //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. - warningType = 'string'; + // simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. + warningType = 'string' } if (warningType) { - throw new Error('Warning: is_finite() expects parameter 1 to be double, ' + warningType + ' given'); + throw new Error('Warning: is_finite() expects parameter 1 to be double, ' + warningType + ' given') } - return true; -} \ No newline at end of file + return true +} diff --git a/functions/math/is_infinite.js b/functions/math/is_infinite.js index ba25271765..ab0dae3959 100644 --- a/functions/math/is_infinite.js +++ b/functions/math/is_infinite.js @@ -1,4 +1,4 @@ -function is_infinite(val) { +function is_infinite (val) { // discuss at: http://phpjs.org/functions/is_infinite/ // original by: Onno Marsman // example 1: is_infinite(Infinity); @@ -8,22 +8,22 @@ function is_infinite(val) { // example 3: is_infinite(0); // returns 3: false - var warningType = ''; + var warningType = '' if (val === Infinity || val === -Infinity) { - return true; + return true } - //Some warnings for maximum PHP compatibility + // Some warnings for maximum PHP compatibility if (typeof val === 'object') { - warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object'); + warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object') } else if (typeof val === 'string' && !val.match(/^[\+\-]?\d/)) { - //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. - warningType = 'string'; + // simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. + warningType = 'string' } if (warningType) { - throw new Error('Warning: is_infinite() expects parameter 1 to be double, ' + warningType + ' given'); + throw new Error('Warning: is_infinite() expects parameter 1 to be double, ' + warningType + ' given') } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/math/is_nan.js b/functions/math/is_nan.js index 097b54b374..5958691ae0 100644 --- a/functions/math/is_nan.js +++ b/functions/math/is_nan.js @@ -1,4 +1,4 @@ -function is_nan(val) { +function is_nan (val) { // discuss at: http://phpjs.org/functions/is_nan/ // original by: Onno Marsman // input by: Robin @@ -7,22 +7,22 @@ function is_nan(val) { // example 2: is_nan(0); // returns 2: false - var warningType = ''; + var warningType = '' if (typeof val === 'number' && isNaN(val)) { - return true; + return true } - //Some errors for maximum PHP compatibility + // Some errors for maximum PHP compatibility if (typeof val === 'object') { - warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object'); + warningType = (Object.prototype.toString.call(val) === '[object Array]' ? 'array' : 'object') } else if (typeof val === 'string' && !val.match(/^[\+\-]?\d/)) { - //simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. - warningType = 'string'; + // simulate PHP's behaviour: '-9a' doesn't give a warning, but 'a9' does. + warningType = 'string' } if (warningType) { - throw new Error('Warning: is_nan() expects parameter 1 to be double, ' + warningType + ' given'); + throw new Error('Warning: is_nan() expects parameter 1 to be double, ' + warningType + ' given') } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/math/lcg_value.js b/functions/math/lcg_value.js index 2c384d5128..b9f11cf004 100644 --- a/functions/math/lcg_value.js +++ b/functions/math/lcg_value.js @@ -1,9 +1,9 @@ -function lcg_value() { +function lcg_value () { // discuss at: http://phpjs.org/functions/lcg_value/ // original by: Onno Marsman // test: skip // example 1: lcg_value() // returns 1: 1 - return Math.random(); -} \ No newline at end of file + return Math.random() +} diff --git a/functions/math/log.js b/functions/math/log.js index 2d9f4994bb..f48d819ad2 100644 --- a/functions/math/log.js +++ b/functions/math/log.js @@ -1,4 +1,4 @@ -function log(arg, base) { +function log (arg, base) { // discuss at: http://phpjs.org/functions/log/ // original by: Onno Marsman // improved by: Brett Zamir (http://brett-zamir.me) @@ -7,5 +7,5 @@ function log(arg, base) { return (typeof base === 'undefined') ? Math.log(arg) : - Math.log(arg) / Math.log(base); -} \ No newline at end of file + Math.log(arg) / Math.log(base) +} diff --git a/functions/math/log10.js b/functions/math/log10.js index c61aa9f0c9..835c0f41f4 100644 --- a/functions/math/log10.js +++ b/functions/math/log10.js @@ -1,4 +1,4 @@ -function log10(arg) { +function log10 (arg) { // discuss at: http://phpjs.org/functions/log10/ // original by: Philip Peterson // improved by: Onno Marsman @@ -9,5 +9,5 @@ function log10(arg) { // example 2: log10(1); // returns 2: 0 - return Math.log(arg) / 2.302585092994046; // Math.LN10 -} \ No newline at end of file + return Math.log(arg) / 2.302585092994046 // Math.LN10 +} diff --git a/functions/math/log1p.js b/functions/math/log1p.js index f2ba8133ad..c000679870 100644 --- a/functions/math/log1p.js +++ b/functions/math/log1p.js @@ -1,4 +1,4 @@ -function log1p(x) { +function log1p (x) { // discuss at: http://phpjs.org/functions/log1p/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Robert Eisele (http://www.xarg.org/) @@ -8,16 +8,16 @@ function log1p(x) { var ret = 0, // degree of precision - n = 50; + n = 50 if (x <= -1) { // JavaScript style would be to return Number.NEGATIVE_INFINITY - return '-INF'; + return '-INF' } if (x < 0 || x > 1) { - return Math.log(1 + x); + return Math.log(1 + x) } for (var i = 1; i < n; i++) { - ret += Math.pow(-x, i) / i; + ret += Math.pow(-x, i) / i } - return -ret; -} \ No newline at end of file + return -ret +} diff --git a/functions/math/max.js b/functions/math/max.js index 4d2e5d3205..5b910cf230 100644 --- a/functions/math/max.js +++ b/functions/math/max.js @@ -1,4 +1,4 @@ -function max() { +function max () { // discuss at: http://phpjs.org/functions/max/ // original by: Onno Marsman // revised by: Onno Marsman @@ -21,90 +21,90 @@ function max() { n = 0, argv = arguments, argc = argv.length, - _obj2Array = function(obj) { + _obj2Array = function (obj) { if (Object.prototype.toString.call(obj) === '[object Array]') { - return obj; + return obj } else { - var ar = []; + var ar = [] for (var i in obj) { if (obj.hasOwnProperty(i)) { - ar.push(obj[i]); + ar.push(obj[i]) } } - return ar; + return ar } - }, //function _obj2Array - _compare = function(current, next) { + }, // function _obj2Array + _compare = function (current, next) { var i = 0, n = 0, tmp = 0, nl = 0, - cl = 0; + cl = 0 if (current === next) { - return 0; + return 0 } else if (typeof current === 'object') { if (typeof next === 'object') { - current = _obj2Array(current); - next = _obj2Array(next); - cl = current.length; - nl = next.length; + current = _obj2Array(current) + next = _obj2Array(next) + cl = current.length + nl = next.length if (nl > cl) { - return 1; + return 1 } else if (nl < cl) { - return -1; + return -1 } for (i = 0, n = cl; i < n; ++i) { - tmp = _compare(current[i], next[i]); + tmp = _compare(current[i], next[i]) if (tmp == 1) { - return 1; + return 1 } else if (tmp == -1) { - return -1; + return -1 } } - return 0; + return 0 } - return -1; + return -1 } else if (typeof next === 'object') { - return 1; + return 1 } else if (isNaN(next) && !isNaN(current)) { if (current == 0) { - return 0; + return 0 } - return (current < 0 ? 1 : -1); + return (current < 0 ? 1 : -1) } else if (isNaN(current) && !isNaN(next)) { if (next == 0) { - return 0; + return 0 } - return (next > 0 ? 1 : -1); + return (next > 0 ? 1 : -1) } if (next == current) { - return 0; + return 0 } - return (next > current ? 1 : -1); - }; //function _compare + return (next > current ? 1 : -1) + } // function _compare if (argc === 0) { - throw new Error('At least one value should be passed to max()'); + throw new Error('At least one value should be passed to max()') } else if (argc === 1) { if (typeof argv[0] === 'object') { - ar = _obj2Array(argv[0]); + ar = _obj2Array(argv[0]) } else { - throw new Error('Wrong parameter count for max()'); + throw new Error('Wrong parameter count for max()') } if (ar.length === 0) { - throw new Error('Array must contain at least one element for max()'); + throw new Error('Array must contain at least one element for max()') } } else { - ar = argv; + ar = argv } - retVal = ar[0]; + retVal = ar[0] for (i = 1, n = ar.length; i < n; ++i) { if (_compare(retVal, ar[i]) == 1) { - retVal = ar[i]; + retVal = ar[i] } } - return retVal; -} \ No newline at end of file + return retVal +} diff --git a/functions/math/min.js b/functions/math/min.js index c6aa41dfe7..e9d1fc91db 100644 --- a/functions/math/min.js +++ b/functions/math/min.js @@ -1,4 +1,4 @@ -function min() { +function min () { // discuss at: http://phpjs.org/functions/min/ // original by: Onno Marsman // revised by: Onno Marsman @@ -21,92 +21,92 @@ function min() { n = 0, argv = arguments, argc = argv.length, - _obj2Array = function(obj) { + _obj2Array = function (obj) { if (Object.prototype.toString.call(obj) === '[object Array]') { - return obj; + return obj } - var ar = []; + var ar = [] for (var i in obj) { if (obj.hasOwnProperty(i)) { - ar.push(obj[i]); + ar.push(obj[i]) } } - return ar; - }, //function _obj2Array - _compare = function(current, next) { + return ar + }, // function _obj2Array + _compare = function (current, next) { var i = 0, n = 0, tmp = 0, nl = 0, - cl = 0; + cl = 0 if (current === next) { - return 0; + return 0 } else if (typeof current === 'object') { if (typeof next === 'object') { - current = _obj2Array(current); - next = _obj2Array(next); - cl = current.length; - nl = next.length; + current = _obj2Array(current) + next = _obj2Array(next) + cl = current.length + nl = next.length if (nl > cl) { - return 1; + return 1 } else if (nl < cl) { - return -1; + return -1 } for (i = 0, n = cl; i < n; ++i) { - tmp = _compare(current[i], next[i]); + tmp = _compare(current[i], next[i]) if (tmp == 1) { - return 1; + return 1 } else if (tmp == -1) { - return -1; + return -1 } } - return 0; + return 0 } - return -1; + return -1 } else if (typeof next === 'object') { - return 1; + return 1 } else if (isNaN(next) && !isNaN(current)) { if (current == 0) { - return 0; + return 0 } - return (current < 0 ? 1 : -1); + return (current < 0 ? 1 : -1) } else if (isNaN(current) && !isNaN(next)) { if (next == 0) { - return 0; + return 0 } - return (next > 0 ? 1 : -1); + return (next > 0 ? 1 : -1) } if (next == current) { - return 0; + return 0 } - return (next > current ? 1 : -1); - }; //function _compare + return (next > current ? 1 : -1) + } // function _compare if (argc === 0) { - throw new Error('At least one value should be passed to min()'); + throw new Error('At least one value should be passed to min()') } else if (argc === 1) { if (typeof argv[0] === 'object') { - ar = _obj2Array(argv[0]); + ar = _obj2Array(argv[0]) } else { - throw new Error('Wrong parameter count for min()'); + throw new Error('Wrong parameter count for min()') } if (ar.length === 0) { - throw new Error('Array must contain at least one element for min()'); + throw new Error('Array must contain at least one element for min()') } } else { - ar = argv; + ar = argv } - retVal = ar[0]; + retVal = ar[0] for (i = 1, n = ar.length; i < n; ++i) { if (_compare(retVal, ar[i]) == -1) { - retVal = ar[i]; + retVal = ar[i] } } - return retVal; -} \ No newline at end of file + return retVal +} diff --git a/functions/math/mt_getrandmax.js b/functions/math/mt_getrandmax.js index b79e694f8f..fd4495adce 100644 --- a/functions/math/mt_getrandmax.js +++ b/functions/math/mt_getrandmax.js @@ -1,8 +1,8 @@ -function mt_getrandmax() { +function mt_getrandmax () { // discuss at: http://phpjs.org/functions/mt_getrandmax/ // original by: Onno Marsman // example 1: mt_getrandmax(); // returns 1: 2147483647 - return 2147483647; -} \ No newline at end of file + return 2147483647 +} diff --git a/functions/math/mt_rand.js b/functions/math/mt_rand.js index d3a99c9647..f3d1b2458e 100644 --- a/functions/math/mt_rand.js +++ b/functions/math/mt_rand.js @@ -1,4 +1,4 @@ -function mt_rand(min, max) { +function mt_rand (min, max) { // discuss at: http://phpjs.org/functions/mt_rand/ // original by: Onno Marsman // improved by: Brett Zamir (http://brett-zamir.me) @@ -6,15 +6,15 @@ function mt_rand(min, max) { // example 1: mt_rand(1, 1); // returns 1: 1 - var argc = arguments.length; + var argc = arguments.length if (argc === 0) { - min = 0; - max = 2147483647; + min = 0 + max = 2147483647 } else if (argc === 1) { - throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given'); + throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given') } else { - min = parseInt(min, 10); - max = parseInt(max, 10); + min = parseInt(min, 10) + max = parseInt(max, 10) } - return Math.floor(Math.random() * (max - min + 1)) + min; -} \ No newline at end of file + return Math.floor(Math.random() * (max - min + 1)) + min +} diff --git a/functions/math/octdec.js b/functions/math/octdec.js index 9ec037c2fd..54e5a2f15b 100644 --- a/functions/math/octdec.js +++ b/functions/math/octdec.js @@ -1,10 +1,10 @@ -function octdec(oct_string) { +function octdec (oct_string) { // discuss at: http://phpjs.org/functions/octdec/ // original by: Philippe Baumann // example 1: octdec('77'); // returns 1: 63 oct_string = (oct_string + '') - .replace(/[^0-7]/gi, ''); - return parseInt(oct_string, 8); -} \ No newline at end of file + .replace(/[^0-7]/gi, '') + return parseInt(oct_string, 8) +} diff --git a/functions/math/pi.js b/functions/math/pi.js index 15519f4d82..3a49c36edb 100644 --- a/functions/math/pi.js +++ b/functions/math/pi.js @@ -1,9 +1,9 @@ -function pi() { +function pi () { // discuss at: http://phpjs.org/functions/pi/ // original by: Onno Marsman // improved by: dude // example 1: pi(8723321.4); // returns 1: 3.141592653589793 - return 3.141592653589793; // Math.PI -} \ No newline at end of file + return 3.141592653589793 // Math.PI +} diff --git a/functions/math/pow.js b/functions/math/pow.js index dfaa7cf7ef..e95d8d0e4d 100644 --- a/functions/math/pow.js +++ b/functions/math/pow.js @@ -1,8 +1,8 @@ -function pow(base, exp) { +function pow (base, exp) { // discuss at: http://phpjs.org/functions/pow/ // original by: Onno Marsman // example 1: pow(8723321.4, 7); // returns 1: 3.8439091680778995e+48 - return Math.pow(base, exp); -} \ No newline at end of file + return Math.pow(base, exp) +} diff --git a/functions/math/rad2deg.js b/functions/math/rad2deg.js index 7fdff20c87..b61ee53de7 100644 --- a/functions/math/rad2deg.js +++ b/functions/math/rad2deg.js @@ -1,9 +1,9 @@ -function rad2deg(angle) { +function rad2deg (angle) { // discuss at: http://phpjs.org/functions/rad2deg/ // original by: Enrique Gonzalez // improved by: Brett Zamir (http://brett-zamir.me) // example 1: rad2deg(3.141592653589793); // returns 1: 180 - return angle * 57.29577951308232; // angle / Math.PI * 180 -} \ No newline at end of file + return angle * 57.29577951308232 // angle / Math.PI * 180 +} diff --git a/functions/math/rand.js b/functions/math/rand.js index 6a01b28aed..a91a950ddb 100644 --- a/functions/math/rand.js +++ b/functions/math/rand.js @@ -1,4 +1,4 @@ -function rand(min, max) { +function rand (min, max) { // discuss at: http://phpjs.org/functions/rand/ // original by: Leslie Hoare // bugfixed by: Onno Marsman @@ -6,14 +6,14 @@ function rand(min, max) { // example 1: rand(1, 1); // returns 1: 1 - var argc = arguments.length; + var argc = arguments.length if (argc === 0) { - min = 0; - max = 2147483647; + min = 0 + max = 2147483647 } else if (argc === 1) { - throw new Error('Warning: rand() expects exactly 2 parameters, 1 given'); + throw new Error('Warning: rand() expects exactly 2 parameters, 1 given') } - return Math.floor(Math.random() * (max - min + 1)) + min; + return Math.floor(Math.random() * (max - min + 1)) + min /* // See note above for an explanation of the following alternative code @@ -51,4 +51,4 @@ function rand(min, max) { } return number; */ -} \ No newline at end of file +} diff --git a/functions/math/round.js b/functions/math/round.js index 58c14936fe..5409a0278b 100644 --- a/functions/math/round.js +++ b/functions/math/round.js @@ -1,4 +1,4 @@ -function round(value, precision, mode) { +function round (value, precision, mode) { // discuss at: http://phpjs.org/functions/round/ // original by: Philip Peterson // revised by: Onno Marsman @@ -25,35 +25,35 @@ function round(value, precision, mode) { // example 5: round(58551.799999999996, 2); // returns 5: 58551.8 - var m, f, isHalf, sgn; // helper variables + var m, f, isHalf, sgn // helper variables // making sure precision is integer - precision |= 0; - m = Math.pow(10, precision); - value *= m; + precision |= 0 + m = Math.pow(10, precision) + value *= m // sign of the number - sgn = (value > 0) | -(value < 0); - isHalf = value % 1 === 0.5 * sgn; - f = Math.floor(value); + sgn = (value > 0) | -(value < 0) + isHalf = value % 1 === 0.5 * sgn + f = Math.floor(value) if (isHalf) { switch (mode) { - case 'PHP_ROUND_HALF_DOWN': + case 'PHP_ROUND_HALF_DOWN': // rounds .5 toward zero - value = f + (sgn < 0); - break; - case 'PHP_ROUND_HALF_EVEN': + value = f + (sgn < 0) + break + case 'PHP_ROUND_HALF_EVEN': // rouds .5 towards the next even integer - value = f + (f % 2 * sgn); - break; - case 'PHP_ROUND_HALF_ODD': + value = f + (f % 2 * sgn) + break + case 'PHP_ROUND_HALF_ODD': // rounds .5 towards the next odd integer - value = f + !(f % 2); - break; - default: + value = f + !(f % 2) + break + default: // rounds .5 away from zero - value = f + (sgn > 0); + value = f + (sgn > 0) } } - return (isHalf ? value : Math.round(value)) / m; -} \ No newline at end of file + return (isHalf ? value : Math.round(value)) / m +} diff --git a/functions/math/sin.js b/functions/math/sin.js index 7a8a62f170..9cb038f7a1 100644 --- a/functions/math/sin.js +++ b/functions/math/sin.js @@ -1,8 +1,8 @@ -function sin(arg) { +function sin (arg) { // discuss at: http://phpjs.org/functions/sin/ // original by: Onno Marsman // example 1: Math.ceil(sin(8723321.4) * 10000000); // returns 1: -9834330 - return Math.sin(arg); -} \ No newline at end of file + return Math.sin(arg) +} diff --git a/functions/math/sinh.js b/functions/math/sinh.js index a6e8882c4f..3ac9140177 100644 --- a/functions/math/sinh.js +++ b/functions/math/sinh.js @@ -1,8 +1,8 @@ -function sinh(arg) { +function sinh (arg) { // discuss at: http://phpjs.org/functions/sinh/ // original by: Onno Marsman // example 1: sinh(-0.9834330348825909); // returns 1: -1.1497971402636502 - return (Math.exp(arg) - Math.exp(-arg)) / 2; -} \ No newline at end of file + return (Math.exp(arg) - Math.exp(-arg)) / 2 +} diff --git a/functions/math/sqrt.js b/functions/math/sqrt.js index 43dc4b8284..7fe5daebec 100644 --- a/functions/math/sqrt.js +++ b/functions/math/sqrt.js @@ -1,8 +1,8 @@ -function sqrt(arg) { +function sqrt (arg) { // discuss at: http://phpjs.org/functions/sqrt/ // original by: Onno Marsman // example 1: sqrt(8723321.4); // returns 1: 2953.5269424875746 - return Math.sqrt(arg); -} \ No newline at end of file + return Math.sqrt(arg) +} diff --git a/functions/math/tan.js b/functions/math/tan.js index da8f9bebe8..c26a9fa325 100644 --- a/functions/math/tan.js +++ b/functions/math/tan.js @@ -1,8 +1,8 @@ -function tan(arg) { +function tan (arg) { // discuss at: http://phpjs.org/functions/tan/ // original by: Onno Marsman // example 1: Math.ceil(tan(8723321.4) * 10000000); // returns 1: 54251849 - return Math.tan(arg); -} \ No newline at end of file + return Math.tan(arg) +} diff --git a/functions/math/tanh.js b/functions/math/tanh.js index 5dc0920f80..c53ca87f8e 100644 --- a/functions/math/tanh.js +++ b/functions/math/tanh.js @@ -1,9 +1,9 @@ -function tanh(arg) { +function tanh (arg) { // discuss at: http://phpjs.org/functions/tanh/ // original by: Onno Marsman // imprived by: Robert Eisele (http://www.xarg.org/) // example 1: tanh(5.4251848798444815); // returns 1: 0.9999612058841574 - return 1 - 2 / (Math.exp(2 * arg) + 1); -} \ No newline at end of file + return 1 - 2 / (Math.exp(2 * arg) + 1) +} diff --git a/functions/misc/pack.js b/functions/misc/pack.js index 7f5e20fe6e..a511743b61 100644 --- a/functions/misc/pack.js +++ b/functions/misc/pack.js @@ -1,4 +1,4 @@ -function pack(format) { +function pack (format) { // discuss at: http://phpjs.org/functions/pack/ // original by: Tim de Koning (http://www.kingsquare.nl) // parts by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) @@ -24,229 +24,229 @@ function pack(format) { argument = '', i = 0, r = [], - instruction, quantifier, word, precisionBits, exponentBits, extraNullCount; + instruction, quantifier, word, precisionBits, exponentBits, extraNullCount // vars used by float encoding var bias, minExp, maxExp, minUnnormExp, status, exp, len, bin, signal, n, intPart, floatPart, lastBit, rounded, j, - k, tmpResult; + k, tmpResult while (formatPointer < format.length) { - instruction = format.charAt(formatPointer); - quantifier = ''; - formatPointer++; + instruction = format.charAt(formatPointer) + quantifier = '' + formatPointer++ while ((formatPointer < format.length) && (format.charAt(formatPointer) .match(/[\d\*]/) !== null)) { - quantifier += format.charAt(formatPointer); - formatPointer++; + quantifier += format.charAt(formatPointer) + formatPointer++ } if (quantifier === '') { - quantifier = '1'; + quantifier = '1' } // Now pack variables: 'quantifier' times 'instruction' switch (instruction) { - case 'a': + case 'a': // NUL-padded string - case 'A': + case 'A': // SPACE-padded string - if (typeof arguments[argumentPointer] === 'undefined') { - throw new Error('Warning: pack() Type ' + instruction + ': not enough arguments'); - } else { - argument = String(arguments[argumentPointer]); - } - if (quantifier === '*') { - quantifier = argument.length; - } - for (i = 0; i < quantifier; i++) { - if (typeof argument[i] === 'undefined') { + if (typeof arguments[argumentPointer] === 'undefined') { + throw new Error('Warning: pack() Type ' + instruction + ': not enough arguments') + } else { + argument = String(arguments[argumentPointer]) + } + if (quantifier === '*') { + quantifier = argument.length + } + for (i = 0; i < quantifier; i++) { + if (typeof argument[i] === 'undefined') { if (instruction === 'a') { - result += String.fromCharCode(0); + result += String.fromCharCode(0) } else { - result += ' '; + result += ' ' } } else { - result += argument[i]; + result += argument[i] + } } - } - argumentPointer++; - break; - case 'h': + argumentPointer++ + break + case 'h': // Hex string, low nibble first - case 'H': + case 'H': // Hex string, high nibble first - if (typeof arguments[argumentPointer] === 'undefined') { - throw new Error('Warning: pack() Type ' + instruction + ': not enough arguments'); - } else { - argument = arguments[argumentPointer]; - } - if (quantifier === '*') { - quantifier = argument.length; - } - if (quantifier > argument.length) { - throw new Error('Warning: pack() Type ' + instruction + ': not enough characters in string'); - } - - for (i = 0; i < quantifier; i += 2) { + if (typeof arguments[argumentPointer] === 'undefined') { + throw new Error('Warning: pack() Type ' + instruction + ': not enough arguments') + } else { + argument = arguments[argumentPointer] + } + if (quantifier === '*') { + quantifier = argument.length + } + if (quantifier > argument.length) { + throw new Error('Warning: pack() Type ' + instruction + ': not enough characters in string') + } + + for (i = 0; i < quantifier; i += 2) { // Always get per 2 bytes... - word = argument[i]; - if (((i + 1) >= quantifier) || typeof argument[i + 1] === 'undefined') { - word += '0'; + word = argument[i] + if (((i + 1) >= quantifier) || typeof argument[i + 1] === 'undefined') { + word += '0' } else { - word += argument[i + 1]; + word += argument[i + 1] } // The fastest way to reverse? - if (instruction === 'h') { - word = word[1] + word[0]; + if (instruction === 'h') { + word = word[1] + word[0] } - result += String.fromCharCode(parseInt(word, 16)); - } - argumentPointer++; - break; + result += String.fromCharCode(parseInt(word, 16)) + } + argumentPointer++ + break - case 'c': + case 'c': // signed char - case 'C': + case 'C': // unsigned char // c and C is the same in pack - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(arguments[argumentPointer]); - argumentPointer++; - } - break; - - case 's': + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(arguments[argumentPointer]) + argumentPointer++ + } + break + + case 's': // signed short (always 16 bit, machine byte order) - case 'S': + case 'S': // unsigned short (always 16 bit, machine byte order) - case 'v': + case 'v': // s and S is the same in pack - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(arguments[argumentPointer] & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF); - argumentPointer++; - } - break; - - case 'n': + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(arguments[argumentPointer] & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF) + argumentPointer++ + } + break + + case 'n': // unsigned short (always 16 bit, big endian byte order) - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] & 0xFF); - argumentPointer++; - } - break; - - case 'i': + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] & 0xFF) + argumentPointer++ + } + break + + case 'i': // signed integer (machine dependent size and byte order) - case 'I': + case 'I': // unsigned integer (machine dependent size and byte order) - case 'l': + case 'l': // signed long (always 32 bit, machine byte order) - case 'L': + case 'L': // unsigned long (always 32 bit, machine byte order) - case 'V': + case 'V': // unsigned long (always 32 bit, little endian byte order) - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(arguments[argumentPointer] & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 16 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 24 & 0xFF); - argumentPointer++; - } - - break; - case 'N': + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(arguments[argumentPointer] & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 16 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 24 & 0xFF) + argumentPointer++ + } + + break + case 'N': // unsigned long (always 32 bit, big endian byte order) - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(arguments[argumentPointer] >> 24 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 16 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF); - result += String.fromCharCode(arguments[argumentPointer] & 0xFF); - argumentPointer++; - } - break; - - case 'f': + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(arguments[argumentPointer] >> 24 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 16 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] >> 8 & 0xFF) + result += String.fromCharCode(arguments[argumentPointer] & 0xFF) + argumentPointer++ + } + break + + case 'f': // float (machine dependent size and representation) - case 'd': + case 'd': // double (machine dependent size and representation) // version based on IEEE754 - precisionBits = 23; - exponentBits = 8; - if (instruction === 'd') { - precisionBits = 52; - exponentBits = 11; - } - - if (quantifier === '*') { - quantifier = arguments.length - argumentPointer; - } - if (quantifier > (arguments.length - argumentPointer)) { - throw new Error('Warning: pack() Type ' + instruction + ': too few arguments'); - } - for (i = 0; i < quantifier; i++) { - argument = arguments[argumentPointer]; - bias = Math.pow(2, exponentBits - 1) - 1; - minExp = -bias + 1; - maxExp = bias; - minUnnormExp = minExp - precisionBits; - status = isNaN(n = parseFloat(argument)) || n === -Infinity || n === +Infinity ? n : 0; - exp = 0; - len = 2 * bias + 1 + precisionBits + 3; - bin = new Array(len); - signal = (n = status !== 0 ? 0 : n) < 0; - n = Math.abs(n); - intPart = Math.floor(n); - floatPart = n - intPart; - - for (k = len; k;) { - bin[--k] = 0; - } - for (k = bias + 2; intPart && k;) { - bin[--k] = intPart % 2; - intPart = Math.floor(intPart / 2); - } - for (k = bias + 1; floatPart > 0 && k; --floatPart) { - (bin[++k] = ((floatPart *= 2) >= 1) - 0); - } - for (k = -1; ++k < len && !bin[k];) {} - - if (bin[(lastBit = precisionBits - 1 + (k = (exp = bias + 1 - k) >= minExp && exp <= maxExp ? k + 1 : + precisionBits = 23 + exponentBits = 8 + if (instruction === 'd') { + precisionBits = 52 + exponentBits = 11 + } + + if (quantifier === '*') { + quantifier = arguments.length - argumentPointer + } + if (quantifier > (arguments.length - argumentPointer)) { + throw new Error('Warning: pack() Type ' + instruction + ': too few arguments') + } + for (i = 0; i < quantifier; i++) { + argument = arguments[argumentPointer] + bias = Math.pow(2, exponentBits - 1) - 1 + minExp = -bias + 1 + maxExp = bias + minUnnormExp = minExp - precisionBits + status = isNaN(n = parseFloat(argument)) || n === -Infinity || n === +Infinity ? n : 0 + exp = 0 + len = 2 * bias + 1 + precisionBits + 3 + bin = new Array(len) + signal = (n = status !== 0 ? 0 : n) < 0 + n = Math.abs(n) + intPart = Math.floor(n) + floatPart = n - intPart + + for (k = len; k;) { + bin[--k] = 0 + } + for (k = bias + 2; intPart && k;) { + bin[--k] = intPart % 2 + intPart = Math.floor(intPart / 2) + } + for (k = bias + 1; floatPart > 0 && k; --floatPart) { + (bin[++k] = ((floatPart *= 2) >= 1) - 0) + } + for (k = -1; ++k < len && !bin[k];) {} + + if (bin[(lastBit = precisionBits - 1 + (k = (exp = bias + 1 - k) >= minExp && exp <= maxExp ? k + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { if (!(rounded = bin[lastBit])) { for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]) {} @@ -255,104 +255,104 @@ function pack(format) { (bin[j] = !bin[j] - 0) && (rounded = 0)) {} } - for (k = k - 2 < 0 ? -1 : k - 3; ++k < len && !bin[k];) {} + for (k = k - 2 < 0 ? -1 : k - 3; ++k < len && !bin[k];) {} - if ((exp = bias + 1 - k) >= minExp && exp <= maxExp) { - ++k; + if ((exp = bias + 1 - k) >= minExp && exp <= maxExp) { + ++k } else { if (exp < minExp) { - if (exp !== bias + 1 - len && exp < minUnnormExp) { /*"encodeFloat::float underflow" */ } - k = bias + 1 - (exp = minExp - 1); + if (exp !== bias + 1 - len && exp < minUnnormExp) { /* "encodeFloat::float underflow" */ } + k = bias + 1 - (exp = minExp - 1) } } - if (intPart || status !== 0) { - exp = maxExp + 1; - k = bias + 2; + if (intPart || status !== 0) { + exp = maxExp + 1 + k = bias + 2 if (status === -Infinity) { - signal = 1; + signal = 1 } else if (isNaN(status)) { - bin[k] = 1; + bin[k] = 1 } } - n = Math.abs(exp + bias); - tmpResult = ''; + n = Math.abs(exp + bias) + tmpResult = '' - for (j = exponentBits + 1; --j;) { - tmpResult = (n % 2) + tmpResult; - n = n >>= 1; + for (j = exponentBits + 1; --j;) { + tmpResult = (n % 2) + tmpResult + n = n >>= 1 } - n = 0; - j = 0; - k = (tmpResult = (signal ? '1' : '0') + tmpResult + bin.slice(k, k + precisionBits) + n = 0 + j = 0 + k = (tmpResult = (signal ? '1' : '0') + tmpResult + bin.slice(k, k + precisionBits) .join('')) - .length; - r = []; + .length + r = [] - for (; k;) { - n += (1 << j) * tmpResult.charAt(--k); + for (; k;) { + n += (1 << j) * tmpResult.charAt(--k) if (j === 7) { - r[r.length] = String.fromCharCode(n); - n = 0; + r[r.length] = String.fromCharCode(n) + n = 0 } - j = (j + 1) % 8; + j = (j + 1) % 8 } - r[r.length] = n ? String.fromCharCode(n) : ''; - result += r.join(''); - argumentPointer++; - } - break; + r[r.length] = n ? String.fromCharCode(n) : '' + result += r.join('') + argumentPointer++ + } + break - case 'x': + case 'x': // NUL byte - if (quantifier === '*') { - throw new Error('Warning: pack(): Type x: \'*\' ignored'); - } - for (i = 0; i < quantifier; i++) { - result += String.fromCharCode(0); - } - break; - - case 'X': + if (quantifier === '*') { + throw new Error('Warning: pack(): Type x: \'*\' ignored') + } + for (i = 0; i < quantifier; i++) { + result += String.fromCharCode(0) + } + break + + case 'X': // Back up one byte - if (quantifier === '*') { - throw new Error('Warning: pack(): Type X: \'*\' ignored'); - } - for (i = 0; i < quantifier; i++) { - if (result.length === 0) { - throw new Error('Warning: pack(): Type X:' + ' outside of string'); + if (quantifier === '*') { + throw new Error('Warning: pack(): Type X: \'*\' ignored') + } + for (i = 0; i < quantifier; i++) { + if (result.length === 0) { + throw new Error('Warning: pack(): Type X:' + ' outside of string') } else { - result = result.substring(0, result.length - 1); + result = result.substring(0, result.length - 1) } - } - break; + } + break - case '@': + case '@': // NUL-fill to absolute position - if (quantifier === '*') { - throw new Error('Warning: pack(): Type X: \'*\' ignored'); - } - if (quantifier > result.length) { - extraNullCount = quantifier - result.length; - for (i = 0; i < extraNullCount; i++) { - result += String.fromCharCode(0); - } - } - if (quantifier < result.length) { - result = result.substring(0, quantifier); - } - break; - - default: - throw new Error('Warning: pack() Type ' + instruction + ': unknown format code'); + if (quantifier === '*') { + throw new Error('Warning: pack(): Type X: \'*\' ignored') + } + if (quantifier > result.length) { + extraNullCount = quantifier - result.length + for (i = 0; i < extraNullCount; i++) { + result += String.fromCharCode(0) + } + } + if (quantifier < result.length) { + result = result.substring(0, quantifier) + } + break + + default: + throw new Error('Warning: pack() Type ' + instruction + ': unknown format code') } } if (argumentPointer < arguments.length) { - throw new Error('Warning: pack(): ' + (arguments.length - argumentPointer) + ' arguments unused'); + throw new Error('Warning: pack(): ' + (arguments.length - argumentPointer) + ' arguments unused') } - return result; -} \ No newline at end of file + return result +} diff --git a/functions/misc/time_sleep_until.js b/functions/misc/time_sleep_until.js index 289649c964..0c1f1f0a75 100644 --- a/functions/misc/time_sleep_until.js +++ b/functions/misc/time_sleep_until.js @@ -1,4 +1,4 @@ -function time_sleep_until(timestamp) { +function time_sleep_until (timestamp) { // discuss at: http://phpjs.org/functions/time_sleep_until/ // original by: Brett Zamir (http://brett-zamir.me) // note: For study purposes. Current implementation could lock up the user's browser. @@ -8,5 +8,5 @@ function time_sleep_until(timestamp) { // returns 1: true while (new Date() < timestamp * 1000) {} - return true; -} \ No newline at end of file + return true +} diff --git a/functions/misc/uniqid.js b/functions/misc/uniqid.js index 18eb432ed5..121f7708a8 100644 --- a/functions/misc/uniqid.js +++ b/functions/misc/uniqid.js @@ -1,4 +1,4 @@ -function uniqid(prefix, more_entropy) { +function uniqid (prefix, more_entropy) { // discuss at: http://phpjs.org/functions/uniqid/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // revised by: Kankrelune (http://www.webfaktory.info/) @@ -12,48 +12,48 @@ function uniqid(prefix, more_entropy) { // returns 3: 'bara20285b23dfd1.31879087' if (typeof prefix === 'undefined') { - prefix = ''; + prefix = '' } - var retId; - var formatSeed = function(seed, reqWidth) { + var retId + var formatSeed = function (seed, reqWidth) { seed = parseInt(seed, 10) - .toString(16); // to hex str + .toString(16) // to hex str if (reqWidth < seed.length) { // so long we split - return seed.slice(seed.length - reqWidth); + return seed.slice(seed.length - reqWidth) } if (reqWidth > seed.length) { // so short we pad return Array(1 + (reqWidth - seed.length)) - .join('0') + seed; + .join('0') + seed } - return seed; - }; + return seed + } // BEGIN REDUNDANT if (!this.php_js) { - this.php_js = {}; + this.php_js = {} } // END REDUNDANT if (!this.php_js.uniqidSeed) { // init seed with big random int - this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15); + this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15) } - this.php_js.uniqidSeed++; + this.php_js.uniqidSeed++ // start with prefix, add current milliseconds hex string - retId = prefix; + retId = prefix retId += formatSeed(parseInt(new Date() - .getTime() / 1000, 10), 8); + .getTime() / 1000, 10), 8) // add seed hex string - retId += formatSeed(this.php_js.uniqidSeed, 5); + retId += formatSeed(this.php_js.uniqidSeed, 5) if (more_entropy) { // for more entropy we add a float lower to 10 retId += (Math.random() * 10) .toFixed(8) - .toString(); + .toString() } - return retId; -} \ No newline at end of file + return retId +} diff --git a/functions/net-gopher/gopher_parsedir.js b/functions/net-gopher/gopher_parsedir.js index 71175f0290..b94c3639d0 100644 --- a/functions/net-gopher/gopher_parsedir.js +++ b/functions/net-gopher/gopher_parsedir.js @@ -1,4 +1,4 @@ -function gopher_parsedir(dirent) { +function gopher_parsedir (dirent) { // discuss at: http://phpjs.org/functions/gopher_parsedir/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: var entry = gopher_parsedir('0All about my gopher site.\t/allabout.txt\tgopher.example.com\t70\u000d\u000a'); @@ -22,59 +22,59 @@ function gopher_parsedir(dirent) { * s = Audio file format, primarily a WAV file */ - var entryPattern = /^(.)(.*?)\t(.*?)\t(.*?)\t(.*?)\u000d\u000a$/; - var entry = dirent.match(entryPattern); + var entryPattern = /^(.)(.*?)\t(.*?)\t(.*?)\t(.*?)\u000d\u000a$/ + var entry = dirent.match(entryPattern) if (entry === null) { - throw 'Could not parse the directory entry'; + throw 'Could not parse the directory entry' // return false; } - var type = entry[1]; + var type = entry[1] switch (type) { - case 'i': + case 'i': // GOPHER_INFO - type = 255; - break; - case '1': + type = 255 + break + case '1': // GOPHER_DIRECTORY - type = 1; - break; - case '0': + type = 1 + break + case '0': // GOPHER_DOCUMENT - type = 0; - break; - case '4': + type = 0 + break + case '4': // GOPHER_BINHEX - type = 4; - break; - case '5': + type = 4 + break + case '5': // GOPHER_DOSBINARY - type = 5; - break; - case '6': + type = 5 + break + case '6': // GOPHER_UUENCODED - type = 6; - break; - case '9': + type = 6 + break + case '9': // GOPHER_BINARY - type = 9; - break; - case 'h': + type = 9 + break + case 'h': // GOPHER_HTTP - type = 254; - break; - default: - return { - type : -1, - data : dirent - }; // GOPHER_UNKNOWN + type = 254 + break + default: + return { + type: -1, + data: dirent + } // GOPHER_UNKNOWN } return { - type : type, - title : entry[2], - path : entry[3], - host : entry[4], - port : entry[5] - }; -} \ No newline at end of file + type: type, + title: entry[2], + path: entry[3], + host: entry[4], + port: entry[5] + } +} diff --git a/functions/network/inet_ntop.js b/functions/network/inet_ntop.js index f5f0cd1de7..a4eb08a380 100644 --- a/functions/network/inet_ntop.js +++ b/functions/network/inet_ntop.js @@ -1,4 +1,4 @@ -function inet_ntop(a) { +function inet_ntop (a) { // discuss at: http://phpjs.org/functions/inet_ntop/ // original by: Theriault // example 1: inet_ntop('\x7F\x00\x00\x01'); @@ -8,27 +8,27 @@ function inet_ntop(a) { var i = 0, m = '', - c = []; - a += ''; + c = [] + a += '' if (a.length === 4) { // IPv4 return [ a.charCodeAt(0), a.charCodeAt(1), a.charCodeAt(2), a.charCodeAt(3) - ].join('.'); + ].join('.') } else if (a.length === 16) { // IPv6 for (i = 0; i < 16; i++) { c.push(((a.charCodeAt(i++) << 8) + a.charCodeAt(i)) - .toString(16)); + .toString(16)) } return c.join(':') - .replace(/((^|:)0(?=:|$))+:?/g, function(t) { - m = (t.length > m.length) ? t : m; - return t; + .replace(/((^|:)0(?=:|$))+:?/g, function (t) { + m = (t.length > m.length) ? t : m + return t }) - .replace(m || ' ', '::'); + .replace(m || ' ', '::') } else { // Invalid length - return false; + return false } -} \ No newline at end of file +} diff --git a/functions/network/inet_pton.js b/functions/network/inet_pton.js index a9b203d963..dac38ee3ff 100644 --- a/functions/network/inet_pton.js +++ b/functions/network/inet_pton.js @@ -1,4 +1,4 @@ -function inet_pton(a) { +function inet_pton (a) { // discuss at: http://phpjs.org/functions/inet_pton/ // original by: Theriault // example 1: inet_pton('::'); @@ -6,45 +6,45 @@ function inet_pton(a) { // example 2: inet_pton('127.0.0.1'); // returns 2: '\x7F\x00\x00\x01' - var r, m, x, i, j, f = String.fromCharCode; + var r, m, x, i, j, f = String.fromCharCode // IPv4 - m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/); + m = a.match(/^(?:\d{1,3}(?:\.|$)){4}/) if (m) { - m = m[0].split('.'); - m = f(m[0]) + f(m[1]) + f(m[2]) + f(m[3]); + m = m[0].split('.') + m = f(m[0]) + f(m[1]) + f(m[2]) + f(m[3]) // Return if 4 bytes, otherwise false. - return m.length === 4 ? m : false; + return m.length === 4 ? m : false } - r = /^((?:[\da-f]{1,4}(?::|)){0,8})(::)?((?:[\da-f]{1,4}(?::|)){0,8})$/; + r = /^((?:[\da-f]{1,4}(?::|)){0,8})(::)?((?:[\da-f]{1,4}(?::|)){0,8})$/ // IPv6 - m = a.match(r); + m = a.match(r) if (m) { // Translate each hexadecimal value. for (j = 1; j < 4; j++) { // Indice 2 is :: and if no length, continue. if (j === 2 || m[j].length === 0) { - continue; + continue } - m[j] = m[j].split(':'); + m[j] = m[j].split(':') for (i = 0; i < m[j].length; i++) { - m[j][i] = parseInt(m[j][i], 16); + m[j][i] = parseInt(m[j][i], 16) // Would be NaN if it was blank, return false. if (isNaN(m[j][i])) { // Invalid IP. - return false; + return false } - m[j][i] = f(m[j][i] >> 8) + f(m[j][i] & 0xFF); + m[j][i] = f(m[j][i] >> 8) + f(m[j][i] & 0xFF) } - m[j] = m[j].join(''); + m[j] = m[j].join('') } - x = m[1].length + m[3].length; + x = m[1].length + m[3].length if (x === 16) { - return m[1] + m[3]; + return m[1] + m[3] } else if (x < 16 && m[2].length > 0) { return m[1] + (new Array(16 - x + 1)) - .join('\x00') + m[3]; + .join('\x00') + m[3] } } // Invalid IP. - return false; -} \ No newline at end of file + return false +} diff --git a/functions/network/ip2long.js b/functions/network/ip2long.js index 3a821894e9..466ebc97a4 100644 --- a/functions/network/ip2long.js +++ b/functions/network/ip2long.js @@ -1,4 +1,4 @@ -function ip2long(IP) { +function ip2long (IP) { // discuss at: http://phpjs.org/functions/ip2long/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // improved by: Victor @@ -11,30 +11,30 @@ function ip2long(IP) { // example 3: ip2long('255.255.255.256'); // returns 3: false - var i = 0; + var i = 0 // PHP allows decimal, octal, and hexadecimal IP components. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components. IP = IP.match( /^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i - ); // Verify IP format. + ) // Verify IP format. if (!IP) { // Invalid format. - return false; + return false } // Reuse IP variable for component counter. - IP[0] = 0; + IP[0] = 0 for (i = 1; i < 5; i += 1) { IP[0] += !!((IP[i] || '') - .length); - IP[i] = parseInt(IP[i]) || 0; + .length) + IP[i] = parseInt(IP[i]) || 0 } // Continue to use IP for overflow values. // PHP does not allow any component to overflow. - IP.push(256, 256, 256, 256); + IP.push(256, 256, 256, 256) // Recalculate overflow of last component supplied to make up for missing components. - IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]); + IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]) if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) { - return false; + return false } - return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1; -} \ No newline at end of file + return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1 +} diff --git a/functions/network/long2ip.js b/functions/network/long2ip.js index 619d80d67f..bdcce901e4 100644 --- a/functions/network/long2ip.js +++ b/functions/network/long2ip.js @@ -1,11 +1,11 @@ -function long2ip(ip) { +function long2ip (ip) { // discuss at: http://phpjs.org/functions/long2ip/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // example 1: long2ip( 3221234342 ); // returns 1: '192.0.34.166' if (!isFinite(ip)) - return false; + return false - return [ip >>> 24, ip >>> 16 & 0xFF, ip >>> 8 & 0xFF, ip & 0xFF].join('.'); -} \ No newline at end of file + return [ip >>> 24, ip >>> 16 & 0xFF, ip >>> 8 & 0xFF, ip & 0xFF].join('.') +} diff --git a/functions/network/setcookie.js b/functions/network/setcookie.js index 2cc74c24fb..bf6254155e 100644 --- a/functions/network/setcookie.js +++ b/functions/network/setcookie.js @@ -1,4 +1,4 @@ -function setcookie(name, value, expires, path, domain, secure) { +function setcookie (name, value, expires, path, domain, secure) { // discuss at: http://phpjs.org/functions/setcookie/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // bugfixed by: Andreas @@ -8,5 +8,5 @@ function setcookie(name, value, expires, path, domain, secure) { // example 1: setcookie('author_name', 'Kevin van Zonneveld'); // returns 1: true - return this.setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure); -} \ No newline at end of file + return this.setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure) +} diff --git a/functions/network/setrawcookie.js b/functions/network/setrawcookie.js index bd98c33937..f10f5c76ae 100644 --- a/functions/network/setrawcookie.js +++ b/functions/network/setrawcookie.js @@ -1,4 +1,4 @@ -function setrawcookie(name, value, expires, path, domain, secure) { +function setrawcookie (name, value, expires, path, domain, secure) { // discuss at: http://phpjs.org/functions/setrawcookie/ // original by: Brett Zamir (http://brett-zamir.me) // original by: setcookie @@ -10,30 +10,30 @@ function setrawcookie(name, value, expires, path, domain, secure) { if (typeof expires === 'string' && (/^\d+$/) .test(expires)) { - expires = parseInt(expires, 10); + expires = parseInt(expires, 10) } if (expires instanceof Date) { - expires = expires.toUTCString(); + expires = expires.toUTCString() } else if (typeof expires === 'number') { expires = (new Date(expires * 1e3)) - .toUTCString(); + .toUTCString() } var r = [name + '=' + value], s = {}, - i = ''; + i = '' s = { - expires : expires, - path : path, - domain : domain - }; + expires: expires, + path: path, + domain: domain + } for (i in s) { if (s.hasOwnProperty(i)) { // Exclude items on Object.prototype - s[i] && r.push(i + '=' + s[i]); + s[i] && r.push(i + '=' + s[i]) } } - return secure && r.push('secure'), this.window.document.cookie = r.join(';'), true; + return secure && r.push('secure'), this.window.document.cookie = r.join(';'), true } diff --git a/functions/pcre/preg_grep.js b/functions/pcre/preg_grep.js index cbf568e1f0..4f2edfaf6b 100644 --- a/functions/pcre/preg_grep.js +++ b/functions/pcre/preg_grep.js @@ -1,4 +1,4 @@ -function preg_grep(pattern, input, flags) { +function preg_grep (pattern, input, flags) { // discuss at: http://phpjs.org/functions/preg_grep/ // original by: Brett Zamir (http://brett-zamir.me) // note: If pass pattern as string, must escape backslashes, even for single quotes @@ -9,30 +9,30 @@ function preg_grep(pattern, input, flags) { // example 1: preg_grep("/^(\\d+)?\\.\\d+$/", arr); // returns 1: {2: 4.5, 5: 4.4} - var p = ''; - var retObj = {}; + var p = '' + var retObj = {} // Todo: put flags as number and do bitwise checks (at least if other flags allowable); see pathinfo() - var invert = (flags === 1 || flags === 'PREG_GREP_INVERT'); + var invert = (flags === 1 || flags === 'PREG_GREP_INVERT') if (typeof pattern === 'string') { - pattern = eval(pattern); + pattern = eval(pattern) } if (invert) { for (p in input) { if ((input[p] + '') .search(pattern) === -1) { - retObj[p] = input[p]; + retObj[p] = input[p] } } } else { for (p in input) { if ((input[p] + '') .search(pattern) !== -1) { - retObj[p] = input[p]; + retObj[p] = input[p] } } } - return retObj; -} \ No newline at end of file + return retObj +} diff --git a/functions/pcre/preg_quote.js b/functions/pcre/preg_quote.js index d47a3b5c40..b0b7199453 100644 --- a/functions/pcre/preg_quote.js +++ b/functions/pcre/preg_quote.js @@ -1,4 +1,4 @@ -function preg_quote(str, delimiter) { +function preg_quote (str, delimiter) { // discuss at: http://phpjs.org/functions/preg_quote/ // original by: booeyOH // improved by: Ates Goral (http://magnetiq.com) @@ -13,5 +13,5 @@ function preg_quote(str, delimiter) { // returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:' return String(str) - .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&'); -} \ No newline at end of file + .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&') +} diff --git a/functions/pcre/sql_regcase.js b/functions/pcre/sql_regcase.js index 4bca058029..c5f528c350 100644 --- a/functions/pcre/sql_regcase.js +++ b/functions/pcre/sql_regcase.js @@ -1,26 +1,26 @@ -function sql_regcase(str) { +function sql_regcase (str) { // discuss at: http://phpjs.org/functions/sql_regcase/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale // example 1: sql_regcase('Foo - bar.'); // returns 1: '[Ff][Oo][Oo] - [Bb][Aa][Rr].' - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) var i = 0, upper = '', lower = '', pos = 0, - retStr = ''; + retStr = '' - upper = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.upper; - lower = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lower; + upper = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.upper + lower = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.lower for (i = 0; i < str.length; i++) { if (((pos = upper.indexOf(str.charAt(i))) !== -1) || ((pos = lower.indexOf(str.charAt(i))) !== -1)) { - retStr += '[' + upper.charAt(pos) + lower.charAt(pos) + ']'; + retStr += '[' + upper.charAt(pos) + lower.charAt(pos) + ']' } else { - retStr += str.charAt(i); + retStr += str.charAt(i) } } - return retStr; -} \ No newline at end of file + return retStr +} diff --git a/functions/strings/addcslashes.js b/functions/strings/addcslashes.js index ddcd204adc..ae5ef38e63 100644 --- a/functions/strings/addcslashes.js +++ b/functions/strings/addcslashes.js @@ -1,4 +1,4 @@ -function addcslashes(str, charlist) { +function addcslashes (str, charlist) { // discuss at: http://phpjs.org/functions/addcslashes/ // original by: Brett Zamir (http://brett-zamir.me) // note: We show double backslashes in the return value example code below because a JavaScript string will not @@ -32,148 +32,148 @@ function addcslashes(str, charlist) { cca = 0, escHexGrp = [], encoded = '', - percentHex = /%([\dA-Fa-f]+)/g; - var _pad = function(n, c) { + percentHex = /%([\dA-Fa-f]+)/g + var _pad = function (n, c) { if ((n = n + '') .length < c) { return new Array(++c - n.length) - .join('0') + n; + .join('0') + n } - return n; - }; + return n + } for (i = 0; i < charlist.length; i++) { - c = charlist.charAt(i); - next = charlist.charAt(i + 1); + c = charlist.charAt(i) + next = charlist.charAt(i + 1) if (c === '\\' && next && (/\d/) .test(next)) { // Octal rangeBegin = charlist.slice(i + 1) - .match(/^\d+/)[0]; - octalLength = rangeBegin.length; - postOctalPos = i + octalLength + 1; + .match(/^\d+/)[0] + octalLength = rangeBegin.length + postOctalPos = i + octalLength + 1 if (charlist.charAt(postOctalPos) + charlist.charAt(postOctalPos + 1) === '..') { // Octal begins range - begin = rangeBegin.charCodeAt(0); + begin = rangeBegin.charCodeAt(0) if ((/\\\d/) .test(charlist.charAt(postOctalPos + 2) + charlist.charAt(postOctalPos + 3))) { // Range ends with octal rangeEnd = charlist.slice(postOctalPos + 3) - .match(/^\d+/)[0]; + .match(/^\d+/)[0] // Skip range end backslash - i += 1; + i += 1 } else if (charlist.charAt(postOctalPos + 2)) { // Range ends with character - rangeEnd = charlist.charAt(postOctalPos + 2); + rangeEnd = charlist.charAt(postOctalPos + 2) } else { - throw 'Range with no end point'; + throw 'Range with no end point' } - end = rangeEnd.charCodeAt(0); + end = rangeEnd.charCodeAt(0) if (end > begin) { // Treat as a range for (j = begin; j <= end; j++) { - chrs.push(String.fromCharCode(j)); + chrs.push(String.fromCharCode(j)) } } else { // Supposed to treat period, begin and end as individual characters only, not a range - chrs.push('.', rangeBegin, rangeEnd); + chrs.push('.', rangeBegin, rangeEnd) } // Skip dots and range end (already skipped range end backslash if present) - i += rangeEnd.length + 2; + i += rangeEnd.length + 2 } else { // Octal is by itself - chr = String.fromCharCode(parseInt(rangeBegin, 8)); - chrs.push(chr); + chr = String.fromCharCode(parseInt(rangeBegin, 8)) + chrs.push(chr) } // Skip range begin - i += octalLength; + i += octalLength } else if (next + charlist.charAt(i + 2) === '..') { // Character begins range - rangeBegin = c; - begin = rangeBegin.charCodeAt(0); + rangeBegin = c + begin = rangeBegin.charCodeAt(0) if ((/\\\d/) .test(charlist.charAt(i + 3) + charlist.charAt(i + 4))) { // Range ends with octal rangeEnd = charlist.slice(i + 4) - .match(/^\d+/)[0]; + .match(/^\d+/)[0] // Skip range end backslash - i += 1; + i += 1 } else if (charlist.charAt(i + 3)) { // Range ends with character - rangeEnd = charlist.charAt(i + 3); + rangeEnd = charlist.charAt(i + 3) } else { - throw 'Range with no end point'; + throw 'Range with no end point' } - end = rangeEnd.charCodeAt(0); + end = rangeEnd.charCodeAt(0) if (end > begin) { // Treat as a range for (j = begin; j <= end; j++) { - chrs.push(String.fromCharCode(j)); + chrs.push(String.fromCharCode(j)) } } else { // Supposed to treat period, begin and end as individual characters only, not a range - chrs.push('.', rangeBegin, rangeEnd); + chrs.push('.', rangeBegin, rangeEnd) } // Skip dots and range end (already skipped range end backslash if present) - i += rangeEnd.length + 2; + i += rangeEnd.length + 2 } else { // Character is by itself - chrs.push(c); + chrs.push(c) } } for (i = 0; i < str.length; i++) { - c = str.charAt(i); + c = str.charAt(i) if (chrs.indexOf(c) !== -1) { - target += '\\'; - cca = c.charCodeAt(0); + target += '\\' + cca = c.charCodeAt(0) if (cca < 32 || cca > 126) { // Needs special escaping switch (c) { - case '\n': - target += 'n'; - break; - case '\t': - target += 't'; - break; - case '\u000D': - target += 'r'; - break; - case '\u0007': - target += 'a'; - break; - case '\v': - target += 'v'; - break; - case '\b': - target += 'b'; - break; - case '\f': - target += 'f'; - break; - default: - //target += _pad(cca.toString(8), 3);break; // Sufficient for UTF-16 - encoded = encodeURIComponent(c); + case '\n': + target += 'n' + break + case '\t': + target += 't' + break + case '\u000D': + target += 'r' + break + case '\u0007': + target += 'a' + break + case '\v': + target += 'v' + break + case '\b': + target += 'b' + break + case '\f': + target += 'f' + break + default: + // target += _pad(cca.toString(8), 3);break; // Sufficient for UTF-16 + encoded = encodeURIComponent(c) // 3-length-padded UTF-8 octets - if ((escHexGrp = percentHex.exec(encoded)) !== null) { - target += _pad(parseInt(escHexGrp[1], 16) - .toString(8), 3); // already added a slash above - } - while ((escHexGrp = percentHex.exec(encoded)) !== null) { - target += '\\' + _pad(parseInt(escHexGrp[1], 16) - .toString(8), 3); - } - break; + if ((escHexGrp = percentHex.exec(encoded)) !== null) { + target += _pad(parseInt(escHexGrp[1], 16) + .toString(8), 3) // already added a slash above + } + while ((escHexGrp = percentHex.exec(encoded)) !== null) { + target += '\\' + _pad(parseInt(escHexGrp[1], 16) + .toString(8), 3) + } + break } } else { // Perform regular backslashed escaping - target += c; + target += c } } else { // Just add the character unescaped - target += c; + target += c } } - return target; -} \ No newline at end of file + return target +} diff --git a/functions/strings/addslashes.js b/functions/strings/addslashes.js index 1c805de437..19a5acc2ca 100644 --- a/functions/strings/addslashes.js +++ b/functions/strings/addslashes.js @@ -1,4 +1,4 @@ -function addslashes(str) { +function addslashes (str) { // discuss at: http://phpjs.org/functions/addslashes/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Ates Goral (http://magnetiq.com) @@ -13,5 +13,5 @@ function addslashes(str) { return (str + '') .replace(/[\\"']/g, '\\$&') - .replace(/\u0000/g, '\\0'); -} \ No newline at end of file + .replace(/\u0000/g, '\\0') +} diff --git a/functions/strings/bin2hex.js b/functions/strings/bin2hex.js index c1cd181223..59a23c8aee 100644 --- a/functions/strings/bin2hex.js +++ b/functions/strings/bin2hex.js @@ -1,4 +1,4 @@ -function bin2hex(s) { +function bin2hex (s) { // discuss at: http://phpjs.org/functions/bin2hex/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -10,15 +10,15 @@ function bin2hex(s) { // returns 2: '00' var i, l, o = '', - n; + n - s += ''; + s += '' for (i = 0, l = s.length; i < l; i++) { n = s.charCodeAt(i) - .toString(16); - o += n.length < 2 ? '0' + n : n; + .toString(16) + o += n.length < 2 ? '0' + n : n } - return o; -} \ No newline at end of file + return o +} diff --git a/functions/strings/chop.js b/functions/strings/chop.js index 65a2802e7b..c6a2da8878 100644 --- a/functions/strings/chop.js +++ b/functions/strings/chop.js @@ -1,9 +1,9 @@ -function chop(str, charlist) { +function chop (str, charlist) { // discuss at: http://phpjs.org/functions/chop/ // original by: Paulo Freitas // depends on: rtrim // example 1: rtrim(' Kevin van Zonneveld '); // returns 1: ' Kevin van Zonneveld' - return this.rtrim(str, charlist); -} \ No newline at end of file + return this.rtrim(str, charlist) +} diff --git a/functions/strings/chr.js b/functions/strings/chr.js index 03c5edb9df..8406a590a0 100644 --- a/functions/strings/chr.js +++ b/functions/strings/chr.js @@ -1,4 +1,4 @@ -function chr(codePt) { +function chr (codePt) { // discuss at: http://phpjs.org/functions/chr/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Brett Zamir (http://brett-zamir.me) @@ -11,8 +11,8 @@ function chr(codePt) { // enough for the UTF-16 encoding (JavaScript internal use), to // require representation with two surrogates (reserved non-characters // used for building other characters; the first is "high" and the next "low") - codePt -= 0x10000; - return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF)); + codePt -= 0x10000 + return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF)) } - return String.fromCharCode(codePt); -} \ No newline at end of file + return String.fromCharCode(codePt) +} diff --git a/functions/strings/chunk_split.js b/functions/strings/chunk_split.js index b15649675b..fecece558f 100644 --- a/functions/strings/chunk_split.js +++ b/functions/strings/chunk_split.js @@ -1,4 +1,4 @@ -function chunk_split(body, chunklen, end) { +function chunk_split (body, chunklen, end) { // discuss at: http://phpjs.org/functions/chunk_split/ // original by: Paulo Freitas // input by: Brett Zamir (http://brett-zamir.me) @@ -9,13 +9,13 @@ function chunk_split(body, chunklen, end) { // example 2: chunk_split('Hello world!', 10, '*'); // returns 2: 'Hello worl*d!*' - chunklen = parseInt(chunklen, 10) || 76; - end = end || '\r\n'; + chunklen = parseInt(chunklen, 10) || 76 + end = end || '\r\n' if (chunklen < 1) { - return false; + return false } return body.match(new RegExp('.{0,' + chunklen + '}', 'g')) - .join(end); -} \ No newline at end of file + .join(end) +} diff --git a/functions/strings/convert_cyr_string.js b/functions/strings/convert_cyr_string.js index e8671d7387..e7f1409c80 100644 --- a/functions/strings/convert_cyr_string.js +++ b/functions/strings/convert_cyr_string.js @@ -1,4 +1,4 @@ -function convert_cyr_string(str, from, to) { +function convert_cyr_string (str, from, to) { // discuss at: http://phpjs.org/functions/convert_cyr_string/ // original by: Brett Zamir (http://brett-zamir.me) // note: Assumes and converts to Unicode strings with character @@ -107,63 +107,63 @@ function convert_cyr_string(str, from, to) { 242, 243, 230, 226, 252, 251, 231, 248, 253, 249, 247, 250, 158, 128, 129, 150, 132, 133, 148, 131, 149, 136, 137, 138, 139, 140, 141, 142, 143, 159, 144, 145, 146, 147, 134, 130, 156, 155, 135, 152, 157, 153, 151, 154 - ]; + ] var from_table = null, to_table = null, tmp, i = 0, - retStr = ''; + retStr = '' switch (from.toUpperCase()) { - case 'W': - from_table = _cyr_win1251; - break; - case 'A': - case 'D': - from_table = _cyr_cp866; - break; - case 'I': - from_table = _cyr_iso88595; - break; - case 'M': - from_table = _cyr_mac; - break; - case 'K': - break; - default: + case 'W': + from_table = _cyr_win1251 + break + case 'A': + case 'D': + from_table = _cyr_cp866 + break + case 'I': + from_table = _cyr_iso88595 + break + case 'M': + from_table = _cyr_mac + break + case 'K': + break + default: // warning - throw 'Unknown source charset: ' + from; + throw 'Unknown source charset: ' + from } switch (to.toUpperCase()) { - case 'W': - to_table = _cyr_win1251; - break; - case 'A': - case 'D': - to_table = _cyr_cp866; - break; - case 'I': - to_table = _cyr_iso88595; - break; - case 'M': - to_table = _cyr_mac; - break; - case 'K': - break; - default: + case 'W': + to_table = _cyr_win1251 + break + case 'A': + case 'D': + to_table = _cyr_cp866 + break + case 'I': + to_table = _cyr_iso88595 + break + case 'M': + to_table = _cyr_mac + break + case 'K': + break + default: // fix: make a warning - throw 'Unknown destination charset: ' + to; + throw 'Unknown destination charset: ' + to } if (!str) { - return str; + return str } for (i = 0; i < str.length; i++) { tmp = (from_table === null) ? str.charAt(i) : String.fromCharCode(from_table[str.charAt(i) - .charCodeAt(0)]); - retStr += (to_table === null) ? tmp : String.fromCharCode(to_table[tmp.charCodeAt(0) + 256]); + .charCodeAt(0)]) + retStr += (to_table === null) ? tmp : String.fromCharCode(to_table[tmp.charCodeAt(0) + 256]) } - return retStr; -} \ No newline at end of file + return retStr +} diff --git a/functions/strings/convert_uuencode.js b/functions/strings/convert_uuencode.js index 09af3b161d..2611a14b00 100644 --- a/functions/strings/convert_uuencode.js +++ b/functions/strings/convert_uuencode.js @@ -1,4 +1,4 @@ -function convert_uuencode(str) { +function convert_uuencode (str) { // discuss at: http://phpjs.org/functions/convert_uuencode/ // original by: Ole Vrijenhoek // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -8,75 +8,75 @@ function convert_uuencode(str) { // example 1: convert_uuencode("test\ntext text\r\n"); // returns 1: "0=&5S=`IT97AT('1E>'0-\"@``" - var chr = function(c) { - return String.fromCharCode(c); - }; + var chr = function (c) { + return String.fromCharCode(c) + } if (!str || str === '') { - return chr(0); + return chr(0) } else if (!this.is_scalar(str)) { - return false; + return false } var c = 0, u = 0, i = 0, - a = 0; + a = 0 var encoded = '', tmp1 = '', tmp2 = '', - bytes = {}; + bytes = {} // divide string into chunks of 45 characters - var chunk = function() { - bytes = str.substr(u, 45); + var chunk = function () { + bytes = str.substr(u, 45) for (i in bytes) { - bytes[i] = bytes[i].charCodeAt(0); + bytes[i] = bytes[i].charCodeAt(0) } if (bytes.length != 0) { - return bytes.length; + return bytes.length } else { - return 0; + return 0 } - }; + } while (chunk() !== 0) { - c = chunk(); - u += 45; + c = chunk() + u += 45 // New line encoded data starts with number of bytes encoded. - encoded += chr(c + 32); + encoded += chr(c + 32) // Convert each char in bytes[] to a byte for (i in bytes) { tmp1 = bytes[i].charCodeAt(0) - .toString(2); + .toString(2) while (tmp1.length < 8) { - tmp1 = '0' + tmp1; + tmp1 = '0' + tmp1 } - tmp2 += tmp1; + tmp2 += tmp1 } while (tmp2.length % 6) { - tmp2 = tmp2 + '0'; + tmp2 = tmp2 + '0' } for (i = 0; i <= (tmp2.length / 6) - 1; i++) { - tmp1 = tmp2.substr(a, 6); + tmp1 = tmp2.substr(a, 6) if (tmp1 == '000000') { - encoded += chr(96); + encoded += chr(96) } else { - encoded += chr(parseInt(tmp1, 2) + 32); + encoded += chr(parseInt(tmp1, 2) + 32) } - a += 6; + a += 6 } - a = 0; - tmp2 = ''; - encoded += '\n'; + a = 0 + tmp2 = '' + encoded += '\n' } // Add termination characters - encoded += chr(96) + '\n'; + encoded += chr(96) + '\n' - return encoded; -} \ No newline at end of file + return encoded +} diff --git a/functions/strings/count_chars.js b/functions/strings/count_chars.js index f5664ca9ef..e58bc909fc 100644 --- a/functions/strings/count_chars.js +++ b/functions/strings/count_chars.js @@ -1,4 +1,4 @@ -function count_chars(str, mode) { +function count_chars (str, mode) { // discuss at: http://phpjs.org/functions/count_chars/ // original by: Ates Goral (http://magnetiq.com) // improved by: Jack @@ -13,48 +13,48 @@ function count_chars(str, mode) { var result = {}, resultArr = [], - i; + i str = ('' + str) .split('') .sort() .join('') - .match(/(.)\1*/g); + .match(/(.)\1*/g) if ((mode & 1) == 0) { for (i = 0; i != 256; i++) { - result[i] = 0; + result[i] = 0 } } if (mode === 2 || mode === 4) { for (i = 0; i != str.length; i += 1) { - delete result[str[i].charCodeAt(0)]; + delete result[str[i].charCodeAt(0)] } for (i in result) { - result[i] = (mode === 4) ? String.fromCharCode(i) : 0; + result[i] = (mode === 4) ? String.fromCharCode(i) : 0 } } else if (mode === 3) { for (i = 0; i != str.length; i += 1) { - result[i] = str[i].slice(0, 1); + result[i] = str[i].slice(0, 1) } } else { for (i = 0; i != str.length; i += 1) { - result[str[i].charCodeAt(0)] = str[i].length; + result[str[i].charCodeAt(0)] = str[i].length } } if (mode < 3) { - return result; + return result } for (i in result) { - resultArr.push(result[i]); + resultArr.push(result[i]) } - return resultArr.join(''); -} \ No newline at end of file + return resultArr.join('') +} diff --git a/functions/strings/crc32.js b/functions/strings/crc32.js index 5a6d429404..800bb02996 100644 --- a/functions/strings/crc32.js +++ b/functions/strings/crc32.js @@ -1,4 +1,4 @@ -function crc32(str) { +function crc32 (str) { // discuss at: http://phpjs.org/functions/crc32/ // original by: Webtoolkit.info (http://www.webtoolkit.info/) // improved by: T0bsn @@ -6,20 +6,20 @@ function crc32(str) { // example 1: crc32('Kevin van Zonneveld'); // returns 1: 1249991249 - str = this.utf8_encode(str); + str = this.utf8_encode(str) var table = - '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'; + '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D' - var crc = 0; - var x = 0; - var y = 0; + var crc = 0 + var x = 0 + var y = 0 - crc = crc ^ (-1); + crc = crc ^ (-1) for (var i = 0, iTop = str.length; i < iTop; i++) { - y = (crc ^ str.charCodeAt(i)) & 0xFF; - x = '0x' + table.substr(y * 9, 8); - crc = (crc >>> 8) ^ x; + y = (crc ^ str.charCodeAt(i)) & 0xFF + x = '0x' + table.substr(y * 9, 8) + crc = (crc >>> 8) ^ x } - return crc ^ (-1); -} \ No newline at end of file + return crc ^ (-1) +} diff --git a/functions/strings/echo.js b/functions/strings/echo.js index 0741dfe08b..f0776bc042 100644 --- a/functions/strings/echo.js +++ b/functions/strings/echo.js @@ -1,4 +1,4 @@ -function echo() { +function echo () { // discuss at: http://phpjs.org/functions/echo/ // original by: Philip Peterson // improved by: echo is bad @@ -24,52 +24,52 @@ function echo() { // example 1: echo('

abc

abc

'); // returns 1: undefined - var isNode = typeof module !== 'undefined' && module.exports && typeof global !== "undefined" && {}.toString.call( - global) == '[object global]'; + var isNode = typeof module !== 'undefined' && module.exports && typeof global !== 'undefined' && {}.toString.call( + global) == '[object global]' if (isNode) { - var args = Array.prototype.slice.call(arguments); - return console.log(args.join(' ')); + var args = Array.prototype.slice.call(arguments) + return console.log(args.join(' ')) } - var arg = ''; - var argc = arguments.length; - var argv = arguments; - var i = 0; - var holder, win = this.window; - var d = win.document; - var ns_xhtml = 'http://www.w3.org/1999/xhtml'; + var arg = '' + var argc = arguments.length + var argv = arguments + var i = 0 + var holder, win = this.window + var d = win.document + var ns_xhtml = 'http://www.w3.org/1999/xhtml' // If we're in a XUL context - var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; + var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul' - var stringToDOM = function(str, parent, ns, container) { - var extraNSs = ''; + var stringToDOM = function (str, parent, ns, container) { + var extraNSs = '' if (ns === ns_xul) { - extraNSs = ' xmlns:html="' + ns_xhtml + '"'; + extraNSs = ' xmlns:html="' + ns_xhtml + '"' } - var stringContainer = '<' + container + ' xmlns="' + ns + '"' + extraNSs + '>' + str + ''; - var dils = win.DOMImplementationLS; - var dp = win.DOMParser; - var ax = win.ActiveXObject; + var stringContainer = '<' + container + ' xmlns="' + ns + '"' + extraNSs + '>' + str + '' + var dils = win.DOMImplementationLS + var dp = win.DOMParser + var ax = win.ActiveXObject if (dils && dils.createLSInput && dils.createLSParser) { // Follows the DOM 3 Load and Save standard, but not // implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though // possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could // attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file) - var lsInput = dils.createLSInput(); + var lsInput = dils.createLSInput() // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default - lsInput.stringData = stringContainer; + lsInput.stringData = stringContainer // synchronous, no schema type - var lsParser = dils.createLSParser(1, null); + var lsParser = dils.createLSParser(1, null) return lsParser.parse(lsInput) - .firstChild; + .firstChild } else if (dp) { // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default try { var fc = new dp() - .parseFromString(stringContainer, 'text/xml'); + .parseFromString(stringContainer, 'text/xml') if (fc && fc.documentElement && fc.documentElement.localName !== 'parsererror' && fc.documentElement.namespaceURI !== 'http://www.mozilla.org/newlayout/xml/parsererror.xml') { - return fc.documentElement.firstChild; + return fc.documentElement.firstChild } // If there's a parsing error, we just continue on } catch (e) { @@ -77,11 +77,11 @@ function echo() { } } else if (ax) { // We don't bother with a holder in Explorer as it doesn't support namespaces - var axo = new ax('MSXML2.DOMDocument'); - axo.loadXML(str); - return axo.documentElement; + var axo = new ax('MSXML2.DOMDocument') + axo.loadXML(str) + return axo.documentElement } - /*else if (win.XMLHttpRequest) { + /* else if (win.XMLHttpRequest) { // Supposed to work in older Safari var req = new win.XMLHttpRequest; req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false); @@ -93,7 +93,7 @@ function echo() { }*/ // Document fragment did not work with innerHTML, so we create a temporary element holder // If we're in XHTML, we'll try to allow the XHTML namespace to be available by default - //if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) { + // if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways) if (d.createElementNS && // Browser supports the method (d.documentElement.namespaceURI || // We can use if the document is using a namespace @@ -101,85 +101,85 @@ function echo() { (d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace )) { // Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document - holder = d.createElementNS(ns, container); + holder = d.createElementNS(ns, container) } else { // Document fragment did not work with innerHTML - holder = d.createElement(container); + holder = d.createElement(container) } - holder.innerHTML = str; + holder.innerHTML = str while (holder.firstChild) { - parent.appendChild(holder.firstChild); + parent.appendChild(holder.firstChild) } - return false; + return false // throw 'Your browser does not support DOM parsing as required by echo()'; - }; + } - var ieFix = function(node) { + var ieFix = function (node) { if (node.nodeType === 1) { - var newNode = d.createElement(node.nodeName); - var i, len; + var newNode = d.createElement(node.nodeName) + var i, len if (node.attributes && node.attributes.length > 0) { for (i = 0, len = node.attributes.length; i < len; i++) { - newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName)); + newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName)) } } if (node.childNodes && node.childNodes.length > 0) { for (i = 0, len = node.childNodes.length; i < len; i++) { - newNode.appendChild(ieFix(node.childNodes[i])); + newNode.appendChild(ieFix(node.childNodes[i])) } } - return newNode; + return newNode } else { - return d.createTextNode(node.nodeValue); + return d.createTextNode(node.nodeValue) } - }; + } - var replacer = function(s, m1, m2) { + var replacer = function (s, m1, m2) { // We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.) // Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double if (m1 !== '\\') { - return m1 + eval(m2); + return m1 + eval(m2) } else { - return s; + return s } - }; + } - this.php_js = this.php_js || {}; - var phpjs = this.php_js; - var ini = phpjs.ini; - var obs = phpjs.obs; + this.php_js = this.php_js || {} + var phpjs = this.php_js + var ini = phpjs.ini + var obs = phpjs.obs for (i = 0; i < argc; i++) { - arg = argv[i]; + arg = argv[i] if (ini && ini['phpjs.echo_embedded_vars']) { - arg = arg.replace(/(.?)\{?\$(\w*?\}|\w*)/g, replacer); + arg = arg.replace(/(.?)\{?\$(\w*?\}|\w*)/g, replacer) } if (!phpjs.flushing && obs && obs.length) { // If flushing we output, but otherwise presence of a buffer means caching output - obs[obs.length - 1].buffer += arg; - continue; + obs[obs.length - 1].buffer += arg + continue } if (d.appendChild) { if (d.body) { if (win.navigator.appName === 'Microsoft Internet Explorer') { // We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended - d.body.appendChild(stringToDOM(ieFix(arg))); + d.body.appendChild(stringToDOM(ieFix(arg))) } else { var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div') - .cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default) + .cloneNode(true) // We will not actually append the div tag (just using for providing XHTML namespace by default) if (unappendedLeft) { - d.body.appendChild(unappendedLeft); + d.body.appendChild(unappendedLeft) } } } else { // We will not actually append the description tag (just using for providing XUL namespace by default) - d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description')); + d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description')) } } else if (d.write) { - d.write(arg); + d.write(arg) } else { - console.log(arg); + console.log(arg) } } -} \ No newline at end of file +} diff --git a/functions/strings/explode.js b/functions/strings/explode.js index 2bbf790ee1..20653fd1d2 100644 --- a/functions/strings/explode.js +++ b/functions/strings/explode.js @@ -1,42 +1,42 @@ -function explode(delimiter, string, limit) { +function explode (delimiter, string, limit) { // discuss at: http://phpjs.org/functions/explode/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // example 1: explode(' ', 'Kevin van Zonneveld'); // returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'} - if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null; - if (delimiter === '' || delimiter === false || delimiter === null) return false; + if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null + if (delimiter === '' || delimiter === false || delimiter === null) return false if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string === 'object') { return { - 0 : '' - }; + 0: '' + } } - if (delimiter === true) delimiter = '1'; + if (delimiter === true) delimiter = '1' // Here we go... - delimiter += ''; - string += ''; + delimiter += '' + string += '' - var s = string.split(delimiter); + var s = string.split(delimiter) - if (typeof limit === 'undefined') return s; + if (typeof limit === 'undefined') return s // Support for limit - if (limit === 0) limit = 1; + if (limit === 0) limit = 1 // Positive limit if (limit > 0) { - if (limit >= s.length) return s; + if (limit >= s.length) return s return s.slice(0, limit - 1) .concat([s.slice(limit - 1) .join(delimiter) - ]); + ]) } // Negative limit - if (-limit >= s.length) return []; + if (-limit >= s.length) return [] - s.splice(s.length + limit); - return s; -} \ No newline at end of file + s.splice(s.length + limit) + return s +} diff --git a/functions/strings/get_html_translation_table.js b/functions/strings/get_html_translation_table.js index d3d1c5d1d8..e16696b8be 100644 --- a/functions/strings/get_html_translation_table.js +++ b/functions/strings/get_html_translation_table.js @@ -1,4 +1,4 @@ -function get_html_translation_table(table, quote_style) { +function get_html_translation_table (table, quote_style) { // discuss at: http://phpjs.org/functions/get_html_translation_table/ // original by: Philip Peterson // revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -21,143 +21,143 @@ function get_html_translation_table(table, quote_style) { var entities = {}, hash_map = {}, - decimal; + decimal var constMappingTable = {}, - constMappingQuoteStyle = {}; + constMappingQuoteStyle = {} var useTable = {}, - useQuoteStyle = {}; + useQuoteStyle = {} // Translate arguments - constMappingTable[0] = 'HTML_SPECIALCHARS'; - constMappingTable[1] = 'HTML_ENTITIES'; - constMappingQuoteStyle[0] = 'ENT_NOQUOTES'; - constMappingQuoteStyle[2] = 'ENT_COMPAT'; - constMappingQuoteStyle[3] = 'ENT_QUOTES'; + constMappingTable[0] = 'HTML_SPECIALCHARS' + constMappingTable[1] = 'HTML_ENTITIES' + constMappingQuoteStyle[0] = 'ENT_NOQUOTES' + constMappingQuoteStyle[2] = 'ENT_COMPAT' + constMappingQuoteStyle[3] = 'ENT_QUOTES' - useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS'; + useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS' useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : - 'ENT_COMPAT'; + 'ENT_COMPAT' if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') { - throw new Error('Table: ' + useTable + ' not supported'); + throw new Error('Table: ' + useTable + ' not supported') // return false; } - entities['38'] = '&'; + entities['38'] = '&' if (useTable === 'HTML_ENTITIES') { - entities['160'] = ' '; - entities['161'] = '¡'; - entities['162'] = '¢'; - entities['163'] = '£'; - entities['164'] = '¤'; - entities['165'] = '¥'; - entities['166'] = '¦'; - entities['167'] = '§'; - entities['168'] = '¨'; - entities['169'] = '©'; - entities['170'] = 'ª'; - entities['171'] = '«'; - entities['172'] = '¬'; - entities['173'] = '­'; - entities['174'] = '®'; - entities['175'] = '¯'; - entities['176'] = '°'; - entities['177'] = '±'; - entities['178'] = '²'; - entities['179'] = '³'; - entities['180'] = '´'; - entities['181'] = 'µ'; - entities['182'] = '¶'; - entities['183'] = '·'; - entities['184'] = '¸'; - entities['185'] = '¹'; - entities['186'] = 'º'; - entities['187'] = '»'; - entities['188'] = '¼'; - entities['189'] = '½'; - entities['190'] = '¾'; - entities['191'] = '¿'; - entities['192'] = 'À'; - entities['193'] = 'Á'; - entities['194'] = 'Â'; - entities['195'] = 'Ã'; - entities['196'] = 'Ä'; - entities['197'] = 'Å'; - entities['198'] = 'Æ'; - entities['199'] = 'Ç'; - entities['200'] = 'È'; - entities['201'] = 'É'; - entities['202'] = 'Ê'; - entities['203'] = 'Ë'; - entities['204'] = 'Ì'; - entities['205'] = 'Í'; - entities['206'] = 'Î'; - entities['207'] = 'Ï'; - entities['208'] = 'Ð'; - entities['209'] = 'Ñ'; - entities['210'] = 'Ò'; - entities['211'] = 'Ó'; - entities['212'] = 'Ô'; - entities['213'] = 'Õ'; - entities['214'] = 'Ö'; - entities['215'] = '×'; - entities['216'] = 'Ø'; - entities['217'] = 'Ù'; - entities['218'] = 'Ú'; - entities['219'] = 'Û'; - entities['220'] = 'Ü'; - entities['221'] = 'Ý'; - entities['222'] = 'Þ'; - entities['223'] = 'ß'; - entities['224'] = 'à'; - entities['225'] = 'á'; - entities['226'] = 'â'; - entities['227'] = 'ã'; - entities['228'] = 'ä'; - entities['229'] = 'å'; - entities['230'] = 'æ'; - entities['231'] = 'ç'; - entities['232'] = 'è'; - entities['233'] = 'é'; - entities['234'] = 'ê'; - entities['235'] = 'ë'; - entities['236'] = 'ì'; - entities['237'] = 'í'; - entities['238'] = 'î'; - entities['239'] = 'ï'; - entities['240'] = 'ð'; - entities['241'] = 'ñ'; - entities['242'] = 'ò'; - entities['243'] = 'ó'; - entities['244'] = 'ô'; - entities['245'] = 'õ'; - entities['246'] = 'ö'; - entities['247'] = '÷'; - entities['248'] = 'ø'; - entities['249'] = 'ù'; - entities['250'] = 'ú'; - entities['251'] = 'û'; - entities['252'] = 'ü'; - entities['253'] = 'ý'; - entities['254'] = 'þ'; - entities['255'] = 'ÿ'; + entities['160'] = ' ' + entities['161'] = '¡' + entities['162'] = '¢' + entities['163'] = '£' + entities['164'] = '¤' + entities['165'] = '¥' + entities['166'] = '¦' + entities['167'] = '§' + entities['168'] = '¨' + entities['169'] = '©' + entities['170'] = 'ª' + entities['171'] = '«' + entities['172'] = '¬' + entities['173'] = '­' + entities['174'] = '®' + entities['175'] = '¯' + entities['176'] = '°' + entities['177'] = '±' + entities['178'] = '²' + entities['179'] = '³' + entities['180'] = '´' + entities['181'] = 'µ' + entities['182'] = '¶' + entities['183'] = '·' + entities['184'] = '¸' + entities['185'] = '¹' + entities['186'] = 'º' + entities['187'] = '»' + entities['188'] = '¼' + entities['189'] = '½' + entities['190'] = '¾' + entities['191'] = '¿' + entities['192'] = 'À' + entities['193'] = 'Á' + entities['194'] = 'Â' + entities['195'] = 'Ã' + entities['196'] = 'Ä' + entities['197'] = 'Å' + entities['198'] = 'Æ' + entities['199'] = 'Ç' + entities['200'] = 'È' + entities['201'] = 'É' + entities['202'] = 'Ê' + entities['203'] = 'Ë' + entities['204'] = 'Ì' + entities['205'] = 'Í' + entities['206'] = 'Î' + entities['207'] = 'Ï' + entities['208'] = 'Ð' + entities['209'] = 'Ñ' + entities['210'] = 'Ò' + entities['211'] = 'Ó' + entities['212'] = 'Ô' + entities['213'] = 'Õ' + entities['214'] = 'Ö' + entities['215'] = '×' + entities['216'] = 'Ø' + entities['217'] = 'Ù' + entities['218'] = 'Ú' + entities['219'] = 'Û' + entities['220'] = 'Ü' + entities['221'] = 'Ý' + entities['222'] = 'Þ' + entities['223'] = 'ß' + entities['224'] = 'à' + entities['225'] = 'á' + entities['226'] = 'â' + entities['227'] = 'ã' + entities['228'] = 'ä' + entities['229'] = 'å' + entities['230'] = 'æ' + entities['231'] = 'ç' + entities['232'] = 'è' + entities['233'] = 'é' + entities['234'] = 'ê' + entities['235'] = 'ë' + entities['236'] = 'ì' + entities['237'] = 'í' + entities['238'] = 'î' + entities['239'] = 'ï' + entities['240'] = 'ð' + entities['241'] = 'ñ' + entities['242'] = 'ò' + entities['243'] = 'ó' + entities['244'] = 'ô' + entities['245'] = 'õ' + entities['246'] = 'ö' + entities['247'] = '÷' + entities['248'] = 'ø' + entities['249'] = 'ù' + entities['250'] = 'ú' + entities['251'] = 'û' + entities['252'] = 'ü' + entities['253'] = 'ý' + entities['254'] = 'þ' + entities['255'] = 'ÿ' } if (useQuoteStyle !== 'ENT_NOQUOTES') { - entities['34'] = '"'; + entities['34'] = '"' } if (useQuoteStyle === 'ENT_QUOTES') { - entities['39'] = '''; + entities['39'] = ''' } - entities['60'] = '<'; - entities['62'] = '>'; + entities['60'] = '<' + entities['62'] = '>' // ascii decimals to real symbols for (decimal in entities) { if (entities.hasOwnProperty(decimal)) { - hash_map[String.fromCharCode(decimal)] = entities[decimal]; + hash_map[String.fromCharCode(decimal)] = entities[decimal] } } - return hash_map; -} \ No newline at end of file + return hash_map +} diff --git a/functions/strings/hex2bin.js b/functions/strings/hex2bin.js index 55af718875..d5c698dfad 100644 --- a/functions/strings/hex2bin.js +++ b/functions/strings/hex2bin.js @@ -1,4 +1,4 @@ -function hex2bin(s) { +function hex2bin (s) { // discuss at: http://phpjs.org/functions/hex2bin/ // original by: Dumitru Uzun (http://duzun.me) // example 1: hex2bin('44696d61'); @@ -10,16 +10,16 @@ function hex2bin(s) { var ret = [], i = 0, - l; + l - s += ''; + s += '' for (l = s.length; i < l; i += 2) { - var c = parseInt(s.substr(i, 1), 16); - var k = parseInt(s.substr(i + 1, 1), 16); - if (isNaN(c) || isNaN(k)) return false; - ret.push((c << 4) | k); + var c = parseInt(s.substr(i, 1), 16) + var k = parseInt(s.substr(i + 1, 1), 16) + if (isNaN(c) || isNaN(k)) return false + ret.push((c << 4) | k) } - return String.fromCharCode.apply(String, ret); -} \ No newline at end of file + return String.fromCharCode.apply(String, ret) +} diff --git a/functions/strings/html_entity_decode.js b/functions/strings/html_entity_decode.js index ea463fdd4f..2f7438b702 100644 --- a/functions/strings/html_entity_decode.js +++ b/functions/strings/html_entity_decode.js @@ -1,4 +1,4 @@ -function html_entity_decode(string, quote_style) { +function html_entity_decode (string, quote_style) { // discuss at: http://phpjs.org/functions/html_entity_decode/ // original by: john (http://www.jd-tech.net) // input by: ger @@ -20,25 +20,25 @@ function html_entity_decode(string, quote_style) { var hash_map = {}, symbol = '', tmp_str = '', - entity = ''; - tmp_str = string.toString(); + entity = '' + tmp_str = string.toString() if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) { - return false; + return false } // fix & problem // http://phpjs.org/functions/get_html_translation_table:416#comment_97660 - delete(hash_map['&']); - hash_map['&'] = '&'; + delete (hash_map['&']) + hash_map['&'] = '&' for (symbol in hash_map) { - entity = hash_map[symbol]; + entity = hash_map[symbol] tmp_str = tmp_str.split(entity) - .join(symbol); + .join(symbol) } tmp_str = tmp_str.split(''') - .join("'"); + .join("'") - return tmp_str; -} \ No newline at end of file + return tmp_str +} diff --git a/functions/strings/htmlentities.js b/functions/strings/htmlentities.js index c66270b0dd..f382648047 100644 --- a/functions/strings/htmlentities.js +++ b/functions/strings/htmlentities.js @@ -1,4 +1,4 @@ -function htmlentities(string, quote_style, charset, double_encode) { +function htmlentities (string, quote_style, charset, double_encode) { // discuss at: http://phpjs.org/functions/htmlentities/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -18,32 +18,32 @@ function htmlentities(string, quote_style, charset, double_encode) { // returns 2: 'foo'bar' var hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style), - symbol = ''; + symbol = '' - string = string == null ? '' : string + ''; + string = string == null ? '' : string + '' if (!hash_map) { - return false; + return false } if (quote_style && quote_style === 'ENT_QUOTES') { - hash_map["'"] = '''; + hash_map["'"] = ''' } - double_encode = double_encode == null || !!double_encode; + double_encode = double_encode == null || !!double_encode - var regex = new RegExp("&(?:#\\d+|#x[\\da-f]+|[a-zA-Z][\\da-z]*);|[" + + var regex = new RegExp('&(?:#\\d+|#x[\\da-f]+|[a-zA-Z][\\da-z]*);|[' + Object.keys(hash_map) - .join("") + .join('') // replace regexp special chars - .replace(/([()[\]{}\-.*+?^$|\/\\])/g, "\\$1") + "]", - "g"); + .replace(/([()[\]{}\-.*+?^$|\/\\])/g, '\\$1') + ']', + 'g') - return string.replace(regex, function(ent) { + return string.replace(regex, function (ent) { if (ent.length > 1) { - return double_encode ? hash_map["&"] + ent.substr(1) : ent; + return double_encode ? hash_map['&'] + ent.substr(1) : ent } - return hash_map[ent]; - }); -} \ No newline at end of file + return hash_map[ent] + }) +} diff --git a/functions/strings/htmlspecialchars.js b/functions/strings/htmlspecialchars.js index 9fc54ccbdf..fb4d54bbe9 100644 --- a/functions/strings/htmlspecialchars.js +++ b/functions/strings/htmlspecialchars.js @@ -1,4 +1,4 @@ -function htmlspecialchars(string, quote_style, charset, double_encode) { +function htmlspecialchars (string, quote_style, charset, double_encode) { // discuss at: http://phpjs.org/functions/htmlspecialchars/ // original by: Mirek Slugen // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -21,49 +21,49 @@ function htmlspecialchars(string, quote_style, charset, double_encode) { var optTemp = 0, i = 0, - noquotes = false; + noquotes = false if (typeof quote_style === 'undefined' || quote_style === null) { - quote_style = 2; + quote_style = 2 } - string = string || ''; - string = string.toString(); + string = string || '' + string = string.toString() if (double_encode !== false) { // Put this first to avoid double-encoding - string = string.replace(/&/g, '&'); + string = string.replace(/&/g, '&') } string = string.replace(//g, '>'); + .replace(/>/g, '>') var OPTS = { - 'ENT_NOQUOTES' : 0, - 'ENT_HTML_QUOTE_SINGLE' : 1, - 'ENT_HTML_QUOTE_DOUBLE' : 2, - 'ENT_COMPAT' : 2, - 'ENT_QUOTES' : 3, - 'ENT_IGNORE' : 4 - }; + 'ENT_NOQUOTES': 0, + 'ENT_HTML_QUOTE_SINGLE': 1, + 'ENT_HTML_QUOTE_DOUBLE': 2, + 'ENT_COMPAT': 2, + 'ENT_QUOTES': 3, + 'ENT_IGNORE': 4 + } if (quote_style === 0) { - noquotes = true; + noquotes = true } if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags - quote_style = [].concat(quote_style); + quote_style = [].concat(quote_style) for (i = 0; i < quote_style.length; i++) { // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4 if (OPTS[quote_style[i]] === 0) { - noquotes = true; + noquotes = true } else if (OPTS[quote_style[i]]) { - optTemp = optTemp | OPTS[quote_style[i]]; + optTemp = optTemp | OPTS[quote_style[i]] } } - quote_style = optTemp; + quote_style = optTemp } if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) { - string = string.replace(/'/g, '''); + string = string.replace(/'/g, ''') } if (!noquotes) { - string = string.replace(/"/g, '"'); + string = string.replace(/"/g, '"') } - return string; -} \ No newline at end of file + return string +} diff --git a/functions/strings/htmlspecialchars_decode.js b/functions/strings/htmlspecialchars_decode.js index bdebb135db..b23e3307c2 100644 --- a/functions/strings/htmlspecialchars_decode.js +++ b/functions/strings/htmlspecialchars_decode.js @@ -1,4 +1,4 @@ -function htmlspecialchars_decode(string, quote_style) { +function htmlspecialchars_decode (string, quote_style) { // discuss at: http://phpjs.org/functions/htmlspecialchars_decode/ // original by: Mirek Slugen // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -21,46 +21,46 @@ function htmlspecialchars_decode(string, quote_style) { var optTemp = 0, i = 0, - noquotes = false; + noquotes = false if (typeof quote_style === 'undefined') { - quote_style = 2; + quote_style = 2 } string = string.toString() .replace(/</g, '<') - .replace(/>/g, '>'); + .replace(/>/g, '>') var OPTS = { - 'ENT_NOQUOTES' : 0, - 'ENT_HTML_QUOTE_SINGLE' : 1, - 'ENT_HTML_QUOTE_DOUBLE' : 2, - 'ENT_COMPAT' : 2, - 'ENT_QUOTES' : 3, - 'ENT_IGNORE' : 4 - }; + 'ENT_NOQUOTES': 0, + 'ENT_HTML_QUOTE_SINGLE': 1, + 'ENT_HTML_QUOTE_DOUBLE': 2, + 'ENT_COMPAT': 2, + 'ENT_QUOTES': 3, + 'ENT_IGNORE': 4 + } if (quote_style === 0) { - noquotes = true; + noquotes = true } if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags - quote_style = [].concat(quote_style); + quote_style = [].concat(quote_style) for (i = 0; i < quote_style.length; i++) { // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4 if (OPTS[quote_style[i]] === 0) { - noquotes = true; + noquotes = true } else if (OPTS[quote_style[i]]) { - optTemp = optTemp | OPTS[quote_style[i]]; + optTemp = optTemp | OPTS[quote_style[i]] } } - quote_style = optTemp; + quote_style = optTemp } if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) { - string = string.replace(/�*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should + string = string.replace(/�*39;/g, "'") // PHP doesn't currently escape if more than one 0, but it should // string = string.replace(/'|�*27;/g, "'"); // This would also be useful here, but not a part of PHP } if (!noquotes) { - string = string.replace(/"/g, '"'); + string = string.replace(/"/g, '"') } // Put this in last place to avoid escape being double-decoded - string = string.replace(/&/g, '&'); + string = string.replace(/&/g, '&') - return string; -} \ No newline at end of file + return string +} diff --git a/functions/strings/implode.js b/functions/strings/implode.js index 891ffb433d..2b04decf32 100644 --- a/functions/strings/implode.js +++ b/functions/strings/implode.js @@ -1,4 +1,4 @@ -function implode(glue, pieces) { +function implode (glue, pieces) { // discuss at: http://phpjs.org/functions/implode/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Waldo Malqui Silva (http://waldo.malqui.info) @@ -11,20 +11,20 @@ function implode(glue, pieces) { var i = '', retVal = '', - tGlue = ''; + tGlue = '' if (arguments.length === 1) { - pieces = glue; - glue = ''; + pieces = glue + glue = '' } if (typeof pieces === 'object') { if (Object.prototype.toString.call(pieces) === '[object Array]') { - return pieces.join(glue); + return pieces.join(glue) } for (i in pieces) { - retVal += tGlue + pieces[i]; - tGlue = glue; + retVal += tGlue + pieces[i] + tGlue = glue } - return retVal; + return retVal } - return pieces; -} \ No newline at end of file + return pieces +} diff --git a/functions/strings/join.js b/functions/strings/join.js index e554b861ba..4f3158a1ce 100644 --- a/functions/strings/join.js +++ b/functions/strings/join.js @@ -1,9 +1,9 @@ -function join(glue, pieces) { +function join (glue, pieces) { // discuss at: http://phpjs.org/functions/join/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // depends on: implode // example 1: join(' ', ['Kevin', 'van', 'Zonneveld']); // returns 1: 'Kevin van Zonneveld' - return this.implode(glue, pieces); -} \ No newline at end of file + return this.implode(glue, pieces) +} diff --git a/functions/strings/lcfirst.js b/functions/strings/lcfirst.js index 5a1a1ca6fa..f5b964194f 100644 --- a/functions/strings/lcfirst.js +++ b/functions/strings/lcfirst.js @@ -1,11 +1,11 @@ -function lcfirst(str) { +function lcfirst (str) { // discuss at: http://phpjs.org/functions/lcfirst/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: lcfirst('Kevin Van Zonneveld'); // returns 1: 'kevin Van Zonneveld' - str += ''; + str += '' var f = str.charAt(0) - .toLowerCase(); - return f + str.substr(1); -} \ No newline at end of file + .toLowerCase() + return f + str.substr(1) +} diff --git a/functions/strings/levenshtein.js b/functions/strings/levenshtein.js index 1518ff91f3..9dee23855d 100644 --- a/functions/strings/levenshtein.js +++ b/functions/strings/levenshtein.js @@ -1,4 +1,4 @@ -function levenshtein(s1, s2, cost_ins, cost_rep, cost_del) { +function levenshtein (s1, s2, cost_ins, cost_rep, cost_del) { // discuss at: http://phpjs.org/functions/levenshtein/ // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) // bugfixed by: Onno Marsman @@ -13,80 +13,80 @@ function levenshtein(s1, s2, cost_ins, cost_rep, cost_del) { // example 3: levenshtein("carrrot", "carrots", 2, 3, 4); // returns 3: 6 - var LEVENSHTEIN_MAX_LENGTH = 255; // PHP limits the function to max 255 character-long strings + var LEVENSHTEIN_MAX_LENGTH = 255 // PHP limits the function to max 255 character-long strings - cost_ins = cost_ins == null ? 1 : +cost_ins; - cost_rep = cost_rep == null ? 1 : +cost_rep; - cost_del = cost_del == null ? 1 : +cost_del; + cost_ins = cost_ins == null ? 1 : +cost_ins + cost_rep = cost_rep == null ? 1 : +cost_rep + cost_del = cost_del == null ? 1 : +cost_del if (s1 == s2) { - return 0; + return 0 } - var l1 = s1.length; - var l2 = s2.length; + var l1 = s1.length + var l2 = s2.length if (l1 === 0) { - return l2 * cost_ins; + return l2 * cost_ins } if (l2 === 0) { - return l1 * cost_del; + return l1 * cost_del } // Enable the 3 lines below to set the same limits on string length as PHP does - /*if (l1 > LEVENSHTEIN_MAX_LENGTH || l2 > LEVENSHTEIN_MAX_LENGTH) { + /* if (l1 > LEVENSHTEIN_MAX_LENGTH || l2 > LEVENSHTEIN_MAX_LENGTH) { return -1; }*/ // BEGIN STATIC - var split = false; + var split = false try { - split = !('0')[0]; + split = !('0')[0] } catch (e) { // Earlier IE may not support access by string index - split = true; + split = true } // END STATIC if (split) { - s1 = s1.split(''); - s2 = s2.split(''); + s1 = s1.split('') + s2 = s2.split('') } - var p1 = new Array(l2 + 1); - var p2 = new Array(l2 + 1); + var p1 = new Array(l2 + 1) + var p2 = new Array(l2 + 1) - var i1, i2, c0, c1, c2, tmp; + var i1, i2, c0, c1, c2, tmp for (i2 = 0; i2 <= l2; i2++) { - p1[i2] = i2 * cost_ins; + p1[i2] = i2 * cost_ins } for (i1 = 0; i1 < l1; i1++) { - p2[0] = p1[0] + cost_del; + p2[0] = p1[0] + cost_del for (i2 = 0; i2 < l2; i2++) { - c0 = p1[i2] + ((s1[i1] == s2[i2]) ? 0 : cost_rep); - c1 = p1[i2 + 1] + cost_del; + c0 = p1[i2] + ((s1[i1] == s2[i2]) ? 0 : cost_rep) + c1 = p1[i2 + 1] + cost_del if (c1 < c0) { - c0 = c1; + c0 = c1 } - c2 = p2[i2] + cost_ins; + c2 = p2[i2] + cost_ins if (c2 < c0) { - c0 = c2; + c0 = c2 } - p2[i2 + 1] = c0; + p2[i2 + 1] = c0 } - tmp = p1; - p1 = p2; - p2 = tmp; + tmp = p1 + p1 = p2 + p2 = tmp } - c0 = p1[l2]; + c0 = p1[l2] - return c0; -} \ No newline at end of file + return c0 +} diff --git a/functions/strings/localeconv.js b/functions/strings/localeconv.js index 0f8ca68f3a..ba69809e5f 100644 --- a/functions/strings/localeconv.js +++ b/functions/strings/localeconv.js @@ -1,4 +1,4 @@ -function localeconv() { +function localeconv () { // discuss at: http://phpjs.org/functions/localeconv/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale @@ -7,19 +7,19 @@ function localeconv() { // returns 1: {decimal_point: '.', thousands_sep: '', positive_sign: '', negative_sign: '-', int_frac_digits: 2, frac_digits: 2, p_cs_precedes: 1, p_sep_by_space: 0, n_cs_precedes: 1, n_sep_by_space: 0, p_sign_posn: 1, n_sign_posn: 1, grouping: [], int_curr_symbol: 'USD ', currency_symbol: '$', mon_decimal_point: '.', mon_thousands_sep: ',', mon_grouping: [3, 3]} var arr = {}, - prop = ''; + prop = '' // BEGIN REDUNDANT // ensure setup of localization variables takes place, if not already - this.setlocale('LC_ALL', 0); + this.setlocale('LC_ALL', 0) // END REDUNDANT // Make copies for (prop in this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC].LC_NUMERIC) { - arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC].LC_NUMERIC[prop]; + arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC].LC_NUMERIC[prop] } for (prop in this.php_js.locales[this.php_js.localeCategories.LC_MONETARY].LC_MONETARY) { - arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY].LC_MONETARY[prop]; + arr[prop] = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY].LC_MONETARY[prop] } - return arr; -} \ No newline at end of file + return arr +} diff --git a/functions/strings/ltrim.js b/functions/strings/ltrim.js index 73b6ca214f..ac879f258f 100644 --- a/functions/strings/ltrim.js +++ b/functions/strings/ltrim.js @@ -1,4 +1,4 @@ -function ltrim(str, charlist) { +function ltrim (str, charlist) { // discuss at: http://phpjs.org/functions/ltrim/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Erkekjetter @@ -8,8 +8,8 @@ function ltrim(str, charlist) { // returns 1: 'Kevin van Zonneveld ' charlist = !charlist ? ' \\s\u00A0' : (charlist + '') - .replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1'); - var re = new RegExp('^[' + charlist + ']+', 'g'); + .replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1') + var re = new RegExp('^[' + charlist + ']+', 'g') return (str + '') - .replace(re, ''); -} \ No newline at end of file + .replace(re, '') +} diff --git a/functions/strings/md5.js b/functions/strings/md5.js index 8e346267a4..1ba67e72e7 100644 --- a/functions/strings/md5.js +++ b/functions/strings/md5.js @@ -1,4 +1,4 @@ -function md5(str) { +function md5 (str) { // discuss at: http://phpjs.org/functions/md5/ // original by: Webtoolkit.info (http://www.webtoolkit.info/) // improved by: Michael White (http://getsprink.com) @@ -10,100 +10,100 @@ function md5(str) { // example 1: md5('Kevin van Zonneveld'); // returns 1: '6e658d4bfcb59cc13f96c14450ac40b9' - var xl; + var xl - var rotateLeft = function(lValue, iShiftBits) { - return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); - }; + var rotateLeft = function (lValue, iShiftBits) { + return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)) + } - var addUnsigned = function(lX, lY) { - var lX4, lY4, lX8, lY8, lResult; - lX8 = (lX & 0x80000000); - lY8 = (lY & 0x80000000); - lX4 = (lX & 0x40000000); - lY4 = (lY & 0x40000000); - lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); + var addUnsigned = function (lX, lY) { + var lX4, lY4, lX8, lY8, lResult + lX8 = (lX & 0x80000000) + lY8 = (lY & 0x80000000) + lX4 = (lX & 0x40000000) + lY4 = (lY & 0x40000000) + lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF) if (lX4 & lY4) { - return (lResult ^ 0x80000000 ^ lX8 ^ lY8); + return (lResult ^ 0x80000000 ^ lX8 ^ lY8) } if (lX4 | lY4) { if (lResult & 0x40000000) { - return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); + return (lResult ^ 0xC0000000 ^ lX8 ^ lY8) } else { - return (lResult ^ 0x40000000 ^ lX8 ^ lY8); + return (lResult ^ 0x40000000 ^ lX8 ^ lY8) } } else { - return (lResult ^ lX8 ^ lY8); + return (lResult ^ lX8 ^ lY8) } - }; + } - var _F = function(x, y, z) { - return (x & y) | ((~x) & z); - }; - var _G = function(x, y, z) { - return (x & z) | (y & (~z)); - }; - var _H = function(x, y, z) { - return (x ^ y ^ z); - }; - var _I = function(x, y, z) { - return (y ^ (x | (~z))); - }; + var _F = function (x, y, z) { + return (x & y) | ((~x) & z) + } + var _G = function (x, y, z) { + return (x & z) | (y & (~z)) + } + var _H = function (x, y, z) { + return (x ^ y ^ z) + } + var _I = function (x, y, z) { + return (y ^ (x | (~z))) + } - var _FF = function(a, b, c, d, x, s, ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - }; + var _FF = function (a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac)) + return addUnsigned(rotateLeft(a, s), b) + } - var _GG = function(a, b, c, d, x, s, ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - }; + var _GG = function (a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac)) + return addUnsigned(rotateLeft(a, s), b) + } - var _HH = function(a, b, c, d, x, s, ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - }; + var _HH = function (a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac)) + return addUnsigned(rotateLeft(a, s), b) + } - var _II = function(a, b, c, d, x, s, ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - }; + var _II = function (a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac)) + return addUnsigned(rotateLeft(a, s), b) + } - var convertToWordArray = function(str) { - var lWordCount; - var lMessageLength = str.length; - var lNumberOfWords_temp1 = lMessageLength + 8; - var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64; - var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16; - var lWordArray = new Array(lNumberOfWords - 1); - var lBytePosition = 0; - var lByteCount = 0; + var convertToWordArray = function (str) { + var lWordCount + var lMessageLength = str.length + var lNumberOfWords_temp1 = lMessageLength + 8 + var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64 + var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16 + var lWordArray = new Array(lNumberOfWords - 1) + var lBytePosition = 0 + var lByteCount = 0 while (lByteCount < lMessageLength) { - lWordCount = (lByteCount - (lByteCount % 4)) / 4; - lBytePosition = (lByteCount % 4) * 8; - lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition)); - lByteCount++; + lWordCount = (lByteCount - (lByteCount % 4)) / 4 + lBytePosition = (lByteCount % 4) * 8 + lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition)) + lByteCount++ } - lWordCount = (lByteCount - (lByteCount % 4)) / 4; - lBytePosition = (lByteCount % 4) * 8; - lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); - lWordArray[lNumberOfWords - 2] = lMessageLength << 3; - lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; - return lWordArray; - }; + lWordCount = (lByteCount - (lByteCount % 4)) / 4 + lBytePosition = (lByteCount % 4) * 8 + lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition) + lWordArray[lNumberOfWords - 2] = lMessageLength << 3 + lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29 + return lWordArray + } - var wordToHex = function(lValue) { + var wordToHex = function (lValue) { var wordToHexValue = '', wordToHexValue_temp = '', - lByte, lCount; + lByte, lCount for (lCount = 0; lCount <= 3; lCount++) { - lByte = (lValue >>> (lCount * 8)) & 255; - wordToHexValue_temp = '0' + lByte.toString(16); - wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2); + lByte = (lValue >>> (lCount * 8)) & 255 + wordToHexValue_temp = '0' + lByte.toString(16) + wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2) } - return wordToHexValue; - }; + return wordToHexValue + } var x = [], k, AA, BB, CC, DD, a, b, c, d, S11 = 7, @@ -121,92 +121,92 @@ function md5(str) { S41 = 6, S42 = 10, S43 = 15, - S44 = 21; + S44 = 21 - str = this.utf8_encode(str); - x = convertToWordArray(str); - a = 0x67452301; - b = 0xEFCDAB89; - c = 0x98BADCFE; - d = 0x10325476; + str = this.utf8_encode(str) + x = convertToWordArray(str) + a = 0x67452301 + b = 0xEFCDAB89 + c = 0x98BADCFE + d = 0x10325476 - xl = x.length; + xl = x.length for (k = 0; k < xl; k += 16) { - AA = a; - BB = b; - CC = c; - DD = d; - a = _FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); - d = _FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); - c = _FF(c, d, a, b, x[k + 2], S13, 0x242070DB); - b = _FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); - a = _FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); - d = _FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); - c = _FF(c, d, a, b, x[k + 6], S13, 0xA8304613); - b = _FF(b, c, d, a, x[k + 7], S14, 0xFD469501); - a = _FF(a, b, c, d, x[k + 8], S11, 0x698098D8); - d = _FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); - c = _FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); - b = _FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); - a = _FF(a, b, c, d, x[k + 12], S11, 0x6B901122); - d = _FF(d, a, b, c, x[k + 13], S12, 0xFD987193); - c = _FF(c, d, a, b, x[k + 14], S13, 0xA679438E); - b = _FF(b, c, d, a, x[k + 15], S14, 0x49B40821); - a = _GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); - d = _GG(d, a, b, c, x[k + 6], S22, 0xC040B340); - c = _GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); - b = _GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); - a = _GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); - d = _GG(d, a, b, c, x[k + 10], S22, 0x2441453); - c = _GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); - b = _GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); - a = _GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); - d = _GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); - c = _GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); - b = _GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); - a = _GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); - d = _GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); - c = _GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); - b = _GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); - a = _HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); - d = _HH(d, a, b, c, x[k + 8], S32, 0x8771F681); - c = _HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); - b = _HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); - a = _HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); - d = _HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); - c = _HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); - b = _HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); - a = _HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); - d = _HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); - c = _HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); - b = _HH(b, c, d, a, x[k + 6], S34, 0x4881D05); - a = _HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); - d = _HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); - c = _HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); - b = _HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); - a = _II(a, b, c, d, x[k + 0], S41, 0xF4292244); - d = _II(d, a, b, c, x[k + 7], S42, 0x432AFF97); - c = _II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); - b = _II(b, c, d, a, x[k + 5], S44, 0xFC93A039); - a = _II(a, b, c, d, x[k + 12], S41, 0x655B59C3); - d = _II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); - c = _II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); - b = _II(b, c, d, a, x[k + 1], S44, 0x85845DD1); - a = _II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); - d = _II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); - c = _II(c, d, a, b, x[k + 6], S43, 0xA3014314); - b = _II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); - a = _II(a, b, c, d, x[k + 4], S41, 0xF7537E82); - d = _II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); - c = _II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); - b = _II(b, c, d, a, x[k + 9], S44, 0xEB86D391); - a = addUnsigned(a, AA); - b = addUnsigned(b, BB); - c = addUnsigned(c, CC); - d = addUnsigned(d, DD); + AA = a + BB = b + CC = c + DD = d + a = _FF(a, b, c, d, x[k + 0], S11, 0xD76AA478) + d = _FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756) + c = _FF(c, d, a, b, x[k + 2], S13, 0x242070DB) + b = _FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE) + a = _FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF) + d = _FF(d, a, b, c, x[k + 5], S12, 0x4787C62A) + c = _FF(c, d, a, b, x[k + 6], S13, 0xA8304613) + b = _FF(b, c, d, a, x[k + 7], S14, 0xFD469501) + a = _FF(a, b, c, d, x[k + 8], S11, 0x698098D8) + d = _FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF) + c = _FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1) + b = _FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE) + a = _FF(a, b, c, d, x[k + 12], S11, 0x6B901122) + d = _FF(d, a, b, c, x[k + 13], S12, 0xFD987193) + c = _FF(c, d, a, b, x[k + 14], S13, 0xA679438E) + b = _FF(b, c, d, a, x[k + 15], S14, 0x49B40821) + a = _GG(a, b, c, d, x[k + 1], S21, 0xF61E2562) + d = _GG(d, a, b, c, x[k + 6], S22, 0xC040B340) + c = _GG(c, d, a, b, x[k + 11], S23, 0x265E5A51) + b = _GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA) + a = _GG(a, b, c, d, x[k + 5], S21, 0xD62F105D) + d = _GG(d, a, b, c, x[k + 10], S22, 0x2441453) + c = _GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681) + b = _GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8) + a = _GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6) + d = _GG(d, a, b, c, x[k + 14], S22, 0xC33707D6) + c = _GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87) + b = _GG(b, c, d, a, x[k + 8], S24, 0x455A14ED) + a = _GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905) + d = _GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8) + c = _GG(c, d, a, b, x[k + 7], S23, 0x676F02D9) + b = _GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A) + a = _HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942) + d = _HH(d, a, b, c, x[k + 8], S32, 0x8771F681) + c = _HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122) + b = _HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C) + a = _HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44) + d = _HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9) + c = _HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60) + b = _HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70) + a = _HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6) + d = _HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA) + c = _HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085) + b = _HH(b, c, d, a, x[k + 6], S34, 0x4881D05) + a = _HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039) + d = _HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5) + c = _HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8) + b = _HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665) + a = _II(a, b, c, d, x[k + 0], S41, 0xF4292244) + d = _II(d, a, b, c, x[k + 7], S42, 0x432AFF97) + c = _II(c, d, a, b, x[k + 14], S43, 0xAB9423A7) + b = _II(b, c, d, a, x[k + 5], S44, 0xFC93A039) + a = _II(a, b, c, d, x[k + 12], S41, 0x655B59C3) + d = _II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92) + c = _II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D) + b = _II(b, c, d, a, x[k + 1], S44, 0x85845DD1) + a = _II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F) + d = _II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0) + c = _II(c, d, a, b, x[k + 6], S43, 0xA3014314) + b = _II(b, c, d, a, x[k + 13], S44, 0x4E0811A1) + a = _II(a, b, c, d, x[k + 4], S41, 0xF7537E82) + d = _II(d, a, b, c, x[k + 11], S42, 0xBD3AF235) + c = _II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB) + b = _II(b, c, d, a, x[k + 9], S44, 0xEB86D391) + a = addUnsigned(a, AA) + b = addUnsigned(b, BB) + c = addUnsigned(c, CC) + d = addUnsigned(d, DD) } - var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d); + var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d) - return temp.toLowerCase(); -} \ No newline at end of file + return temp.toLowerCase() +} diff --git a/functions/strings/md5_file.js b/functions/strings/md5_file.js index 06538703b3..bedc9e485f 100644 --- a/functions/strings/md5_file.js +++ b/functions/strings/md5_file.js @@ -1,4 +1,4 @@ -function md5_file(str_filename) { +function md5_file (str_filename) { // discuss at: http://phpjs.org/functions/md5_file/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Brett Zamir (http://brett-zamir.me) @@ -9,13 +9,13 @@ function md5_file(str_filename) { // example 1: md5_file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm'); // returns 1: '202cb962ac59075b964b07152d234b70' - var buf = ''; + var buf = '' - buf = this.file_get_contents(str_filename); + buf = this.file_get_contents(str_filename) if (!buf) { - return false; + return false } - return this.md5(buf); -} \ No newline at end of file + return this.md5(buf) +} diff --git a/functions/strings/metaphone.js b/functions/strings/metaphone.js index 50c88c1dbd..6ad0306034 100644 --- a/functions/strings/metaphone.js +++ b/functions/strings/metaphone.js @@ -1,4 +1,4 @@ -function metaphone(word, max_phonemes) { +function metaphone (word, max_phonemes) { // discuss at: http://phpjs.org/functions/metaphone/ // original by: Greg Frazier // improved by: Brett Zamir (http://brett-zamir.me) @@ -12,27 +12,27 @@ function metaphone(word, max_phonemes) { // example 4: metaphone('batch batcher'); // returns 4: 'BXBXR' - var type = typeof word; + var type = typeof word if (type === 'undefined' || type === 'object' && word !== null) { // weird! - return null; + return null } // infinity and NaN values are treated as strings if (type === 'number') { if (isNaN(word)) { - word = 'NAN'; + word = 'NAN' } else if (!isFinite(word)) { - word = 'INF'; + word = 'INF' } } if (max_phonemes < 0) { - return false; + return false } - max_phonemes = Math.floor(+max_phonemes) || 0; + max_phonemes = Math.floor(+max_phonemes) || 0 // alpha depends on locale, so this var might need an update // or should be turned into a regex @@ -40,19 +40,19 @@ function metaphone(word, max_phonemes) { var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', vowel = 'AEIOU', soft = 'EIY', - leadingNonAlpha = new RegExp('^[^' + alpha + ']+'); + leadingNonAlpha = new RegExp('^[^' + alpha + ']+') - word = typeof word === 'string' ? word : ''; + word = typeof word === 'string' ? word : '' word = word.toUpperCase() - .replace(leadingNonAlpha, ''); + .replace(leadingNonAlpha, '') if (!word) { - return ''; + return '' } - var is = function(p, c) { - return c !== '' && p.indexOf(c) !== -1; - }; + var is = function (p, c) { + return c !== '' && p.indexOf(c) !== -1 + } var i = 0, cc = word.charAt(0), // current char. Short name, because it's used all over the function @@ -63,163 +63,163 @@ function metaphone(word, max_phonemes) { meta = '', // traditional is an internal param that could be exposed // for now let it be a local var - traditional = true; + traditional = true switch (cc) { - case 'A': - meta += nc === 'E' ? nc : cc; - i += 1; - break; - case 'G': - case 'K': - case 'P': - if (nc === 'N') { - meta += nc; - i += 2; - } - break; - case 'W': - if (nc === 'R') { - meta += nc; - i += 2; - } else if (nc === 'H' || is(vowel, nc)) { - meta += 'W'; - i += 2; + case 'A': + meta += nc === 'E' ? nc : cc + i += 1 + break + case 'G': + case 'K': + case 'P': + if (nc === 'N') { + meta += nc + i += 2 + } + break + case 'W': + if (nc === 'R') { + meta += nc + i += 2 + } else if (nc === 'H' || is(vowel, nc)) { + meta += 'W' + i += 2 } - break; - case 'X': - meta += 'S'; - i += 1; - break; - case 'E': - case 'I': - case 'O': - case 'U': - meta += cc; - i++; - break; + break + case 'X': + meta += 'S' + i += 1 + break + case 'E': + case 'I': + case 'O': + case 'U': + meta += cc + i++ + break } for (; i < l && (max_phonemes === 0 || meta.length < max_phonemes); i += 1) { - cc = word.charAt(i); - nc = word.charAt(i + 1); - pc = word.charAt(i - 1); - nnc = word.charAt(i + 2); + cc = word.charAt(i) + nc = word.charAt(i + 1) + pc = word.charAt(i - 1) + nnc = word.charAt(i + 2) if (cc === pc && cc !== 'C') { - continue; + continue } switch (cc) { - case 'B': - if (pc !== 'M') { - meta += cc; - } - break; - case 'C': - if (is(soft, nc)) { - if (nc === 'I' && nnc === 'A') { - meta += 'X'; + case 'B': + if (pc !== 'M') { + meta += cc + } + break + case 'C': + if (is(soft, nc)) { + if (nc === 'I' && nnc === 'A') { + meta += 'X' } else if (pc !== 'S') { - meta += 'S'; + meta += 'S' } - } else if (nc === 'H') { - meta += !traditional && (nnc === 'R' || pc === 'S') ? 'K' : 'X'; - i += 1; - } else { - meta += 'K'; - } - break; - case 'D': - if (nc === 'G' && is(soft, nnc)) { - meta += 'J'; - i += 1; + } else if (nc === 'H') { + meta += !traditional && (nnc === 'R' || pc === 'S') ? 'K' : 'X' + i += 1 } else { - meta += 'T'; + meta += 'K' } - break; - case 'G': - if (nc === 'H') { - if (!(is('BDH', word.charAt(i - 3)) || word.charAt(i - 4) === 'H')) { - meta += 'F'; - i += 1; + break + case 'D': + if (nc === 'G' && is(soft, nnc)) { + meta += 'J' + i += 1 + } else { + meta += 'T' + } + break + case 'G': + if (nc === 'H') { + if (!(is('BDH', word.charAt(i - 3)) || word.charAt(i - 4) === 'H')) { + meta += 'F' + i += 1 } - } else if (nc === 'N') { + } else if (nc === 'N') { if (is(alpha, nnc) && word.substr(i + 1, 3) !== 'NED') { - meta += 'K'; + meta += 'K' } } else if (is(soft, nc) && pc !== 'G') { - meta += 'J'; + meta += 'J' } else { - meta += 'K'; - } - break; - case 'H': - if (is(vowel, nc) && !is('CGPST', pc)) { - meta += cc; + meta += 'K' } - break; - case 'K': - if (pc !== 'C') { - meta += 'K'; - } - break; - case 'P': - meta += nc === 'H' ? 'F' : cc; - break; - case 'Q': - meta += 'K'; - break; - case 'S': - if (nc === 'I' && is('AO', nnc)) { - meta += 'X'; - } else if (nc === 'H') { - meta += 'X'; - i += 1; + break + case 'H': + if (is(vowel, nc) && !is('CGPST', pc)) { + meta += cc + } + break + case 'K': + if (pc !== 'C') { + meta += 'K' + } + break + case 'P': + meta += nc === 'H' ? 'F' : cc + break + case 'Q': + meta += 'K' + break + case 'S': + if (nc === 'I' && is('AO', nnc)) { + meta += 'X' + } else if (nc === 'H') { + meta += 'X' + i += 1 } else if (!traditional && word.substr(i + 1, 3) === 'CHW') { - meta += 'X'; - i += 2; + meta += 'X' + i += 2 } else { - meta += 'S'; + meta += 'S' } - break; - case 'T': - if (nc === 'I' && is('AO', nnc)) { - meta += 'X'; - } else if (nc === 'H') { - meta += '0'; - i += 1; + break + case 'T': + if (nc === 'I' && is('AO', nnc)) { + meta += 'X' + } else if (nc === 'H') { + meta += '0' + i += 1 } else if (word.substr(i + 1, 2) !== 'CH') { - meta += 'T'; - } - break; - case 'V': - meta += 'F'; - break; - case 'W': - case 'Y': - if (is(vowel, nc)) { - meta += cc; + meta += 'T' } - break; - case 'X': - meta += 'KS'; - break; - case 'Z': - meta += 'S'; - break; - case 'F': - case 'J': - case 'L': - case 'M': - case 'N': - case 'R': - meta += cc; - break; + break + case 'V': + meta += 'F' + break + case 'W': + case 'Y': + if (is(vowel, nc)) { + meta += cc + } + break + case 'X': + meta += 'KS' + break + case 'Z': + meta += 'S' + break + case 'F': + case 'J': + case 'L': + case 'M': + case 'N': + case 'R': + meta += cc + break } } - return meta; + return meta /* " abc", "ABK", // skip leading whitespace @@ -339,4 +339,4 @@ function metaphone(word, max_phonemes) { "zigzag", "SKSK", "abc abc", "ABKBK" // eventhough there are two words, second 'a' is ignored */ -} \ No newline at end of file +} diff --git a/functions/strings/money_format.js b/functions/strings/money_format.js index fd57478f95..607c749d6a 100644 --- a/functions/strings/money_format.js +++ b/functions/strings/money_format.js @@ -1,4 +1,4 @@ -function money_format(format, number) { +function money_format (format, number) { // discuss at: http://phpjs.org/functions/money_format/ // original by: Brett Zamir (http://brett-zamir.me) // input by: daniel airton wermann (http://wermann.com.br) @@ -41,84 +41,84 @@ function money_format(format, number) { // Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm if (typeof number !== 'number') { - return null; + return null } // 1: flags, 3: width, 5: left, 7: right, 8: conversion - var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; + var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g // Ensure the locale data we need is set up - this.setlocale('LC_ALL', 0); - var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY']; + this.setlocale('LC_ALL', 0) + var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY'] - var doReplace = function(n0, flags, n2, width, n4, left, n6, right, conversion) { + var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) { var value = '', - repl = ''; + repl = '' if (conversion === '%') { // Percent does not seem to be allowed with intervening content - return '%'; + return '%' } var fill = flags && (/=./) - .test(flags) ? flags.match(/=(.)/)[1] : ' '; // flag: =f (numeric fill) + .test(flags) ? flags.match(/=(.)/)[1] : ' ' // flag: =f (numeric fill) // flag: ! (suppress currency symbol) - var showCurrSymbol = !flags || flags.indexOf('!') === -1; + var showCurrSymbol = !flags || flags.indexOf('!') === -1 // field width: w (minimum field width) - width = parseInt(width, 10) || 0; + width = parseInt(width, 10) || 0 - var neg = number < 0; + var neg = number < 0 // Convert to string - number = number + ''; + number = number + '' // We don't want negative symbol represented here yet - number = neg ? number.slice(1) : number; + number = neg ? number.slice(1) : number - var decpos = number.indexOf('.'); + var decpos = number.indexOf('.') // Get integer portion - var integer = decpos !== -1 ? number.slice(0, decpos) : number; + var integer = decpos !== -1 ? number.slice(0, decpos) : number // Get decimal portion - var fraction = decpos !== -1 ? number.slice(decpos + 1) : ''; + var fraction = decpos !== -1 ? number.slice(decpos + 1) : '' - var _str_splice = function(integerStr, idx, thous_sep) { - var integerArr = integerStr.split(''); - integerArr.splice(idx, 0, thous_sep); - return integerArr.join(''); - }; + var _str_splice = function (integerStr, idx, thous_sep) { + var integerArr = integerStr.split('') + integerArr.splice(idx, 0, thous_sep) + return integerArr.join('') + } - var init_lgth = integer.length; - left = parseInt(left, 10); - var filler = init_lgth < left; + var init_lgth = integer.length + left = parseInt(left, 10) + var filler = init_lgth < left if (filler) { - var fillnum = left - init_lgth; + var fillnum = left - init_lgth integer = new Array(fillnum + 1) - .join(fill) + integer; + .join(fill) + integer } if (flags.indexOf('^') === -1) { // flag: ^ (disable grouping characters (of locale)) // use grouping characters // ',' - var thous_sep = monetary.mon_thousands_sep; + var thous_sep = monetary.mon_thousands_sep // [3] (every 3 digits in U.S.A. locale) - var mon_grouping = monetary.mon_grouping; + var mon_grouping = monetary.mon_grouping if (mon_grouping[0] < integer.length) { for (var i = 0, idx = integer.length; i < mon_grouping.length; i++) { // e.g., 3 - idx -= mon_grouping[i]; + idx -= mon_grouping[i] if (idx <= 0) { - break; + break } if (filler && idx < fillnum) { - thous_sep = fill; + thous_sep = fill } - integer = _str_splice(integer, idx, thous_sep); + integer = _str_splice(integer, idx, thous_sep) } } if (mon_grouping[i - 1] > 0) { // Repeating last grouping (may only be one) until highest portion of integer reached while (idx > mon_grouping[i - 1]) { - idx -= mon_grouping[i - 1]; + idx -= mon_grouping[i - 1] if (filler && idx < fillnum) { - thous_sep = fill; + thous_sep = fill } - integer = _str_splice(integer, idx, thous_sep); + integer = _str_splice(integer, idx, thous_sep) } } } @@ -126,46 +126,46 @@ function money_format(format, number) { // left, right if (right === '0') { // No decimal or fractional digits - value = integer; + value = integer } else { // '.' - var dec_pt = monetary.mon_decimal_point; + var dec_pt = monetary.mon_decimal_point if (right === '' || right === undefined) { - right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits; + right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits } - right = parseInt(right, 10); + right = parseInt(right, 10) if (right === 0) { // Only remove fractional portion if explicitly set to zero digits - fraction = ''; - dec_pt = ''; + fraction = '' + dec_pt = '' } else if (right < fraction.length) { - fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + ''; + fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + '' if (right > fraction.length) { fraction = new Array(right - fraction.length + 1) - .join('0') + fraction; // prepend with 0's + .join('0') + fraction // prepend with 0's } } else if (right > fraction.length) { fraction += new Array(right - fraction.length + 1) - .join('0'); // pad with 0's + .join('0') // pad with 0's } - value = integer + dec_pt + fraction; + value = integer + dec_pt + fraction } - var symbol = ''; + var symbol = '' if (showCurrSymbol) { // 'i' vs. 'n' ('USD' vs. '$') - symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol; + symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol } - var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn; + var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn // 0: no space between curr. symbol and value // 1: space sep. them unless symb. and sign are adjacent then space sep. them from value // 2: space sep. sign and value unless symb. and sign are adjacent then space separates - var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space; + var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space // p_cs_precedes, n_cs_precedes // positive currency symbol follows value = 0; precedes value = 1 - var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes; + var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes // Assemble symbol/value/sign and possible space as appropriate if (flags.indexOf('(') !== -1) { @@ -174,77 +174,77 @@ function money_format(format, number) { // an impact here (as they do below), but assuming for now behaves as sign_posn 0 as // far as localized sep_by_space and sign_posn behavior repl = (cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') : '') + value + (!cs_precedes ? ( - sep_by_space === 1 ? ' ' : '') + symbol : ''); + sep_by_space === 1 ? ' ' : '') + symbol : '') if (neg) { - repl = '(' + repl + ')'; + repl = '(' + repl + ')' } else { - repl = ' ' + repl + ' '; + repl = ' ' + repl + ' ' } } else { // '+' is default // '' - var pos_sign = monetary.positive_sign; + var pos_sign = monetary.positive_sign // '-' - var neg_sign = monetary.negative_sign; - var sign = neg ? (neg_sign) : (pos_sign); - var otherSign = neg ? (pos_sign) : (neg_sign); - var signPadding = ''; + var neg_sign = monetary.negative_sign + var sign = neg ? (neg_sign) : (pos_sign) + var otherSign = neg ? (pos_sign) : (neg_sign) + var signPadding = '' if (sign_posn) { // has a sign signPadding = new Array(otherSign.length - sign.length + 1) - .join(' '); + .join(' ') } - var valueAndCS = ''; + var valueAndCS = '' switch (sign_posn) { // 0: parentheses surround value and curr. symbol; // 1: sign precedes them; // 2: sign follows them; // 3: sign immed. precedes curr. symbol; (but may be space between) // 4: sign immed. succeeds curr. symbol; (but may be space between) - case 0: - valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === - 1 ? ' ' : '') + symbol; - repl = '(' + valueAndCS + ')'; - break; - case 1: - valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === - 1 ? ' ' : '') + symbol; - repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS; - break; - case 2: - valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === - 1 ? ' ' : '') + symbol; - repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding; - break; - case 3: - repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === + case 0: + valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === + 1 ? ' ' : '') + symbol + repl = '(' + valueAndCS + ')' + break + case 1: + valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === + 1 ? ' ' : '') + symbol + repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS + break + case 2: + valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === + 1 ? ' ' : '') + symbol + repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding + break + case 3: + repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + sign + signPadding + ( - sep_by_space === 2 ? ' ' : '') + symbol; - break; - case 4: - repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === + sep_by_space === 2 ? ' ' : '') + symbol + break + case 4: + repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol + (sep_by_space === 2 ? - ' ' : '') + sign + signPadding; - break; + ' ' : '') + sign + signPadding + break } } - var padding = width - repl.length; + var padding = width - repl.length if (padding > 0) { padding = new Array(padding + 1) - .join(' '); + .join(' ') // Fix: How does p_sep_by_space affect the count if there is a space? Included in count presumably? if (flags.indexOf('-') !== -1) { // left-justified (pad to right) - repl += padding; + repl += padding } else { // right-justified (pad to left) - repl = padding + repl; + repl = padding + repl } } - return repl; - }; + return repl + } - return format.replace(regex, doReplace); -} \ No newline at end of file + return format.replace(regex, doReplace) +} diff --git a/functions/strings/nl2br.js b/functions/strings/nl2br.js index 109f80e4bd..6e1c8a4896 100644 --- a/functions/strings/nl2br.js +++ b/functions/strings/nl2br.js @@ -1,4 +1,4 @@ -function nl2br(str, is_xhtml) { +function nl2br (str, is_xhtml) { // discuss at: http://phpjs.org/functions/nl2br/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Philip Peterson @@ -16,8 +16,8 @@ function nl2br(str, is_xhtml) { // example 3: nl2br("\nOne\nTwo\n\nThree\n", true); // returns 3: '
\nOne
\nTwo
\n
\nThree
\n' - var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
'; // Adjust comment to avoid issue on phpjs.org display + var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
' // Adjust comment to avoid issue on phpjs.org display return (str + '') - .replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); -} \ No newline at end of file + .replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2') +} diff --git a/functions/strings/nl_langinfo.js b/functions/strings/nl_langinfo.js index 5207eadcc3..043bfaf87b 100644 --- a/functions/strings/nl_langinfo.js +++ b/functions/strings/nl_langinfo.js @@ -1,96 +1,96 @@ -function nl_langinfo(item) { +function nl_langinfo (item) { // discuss at: http://phpjs.org/functions/nl_langinfo/ // original by: Brett Zamir (http://brett-zamir.me) // depends on: setlocale // example 1: nl_langinfo('DAY_1'); // returns 1: 'Sunday' - this.setlocale('LC_ALL', 0); // Ensure locale data is available - var loc = this.php_js.locales[this.php_js.localeCategories.LC_TIME]; + this.setlocale('LC_ALL', 0) // Ensure locale data is available + var loc = this.php_js.locales[this.php_js.localeCategories.LC_TIME] if (item.indexOf('ABDAY_') === 0) { - return loc.LC_TIME.a[parseInt(item.replace(/^ABDAY_/, ''), 10) - 1]; + return loc.LC_TIME.a[parseInt(item.replace(/^ABDAY_/, ''), 10) - 1] } else if (item.indexOf('DAY_') === 0) { - return loc.LC_TIME.A[parseInt(item.replace(/^DAY_/, ''), 10) - 1]; + return loc.LC_TIME.A[parseInt(item.replace(/^DAY_/, ''), 10) - 1] } else if (item.indexOf('ABMON_') === 0) { - return loc.LC_TIME.b[parseInt(item.replace(/^ABMON_/, ''), 10) - 1]; + return loc.LC_TIME.b[parseInt(item.replace(/^ABMON_/, ''), 10) - 1] } else if (item.indexOf('MON_') === 0) { - return loc.LC_TIME.B[parseInt(item.replace(/^MON_/, ''), 10) - 1]; + return loc.LC_TIME.B[parseInt(item.replace(/^MON_/, ''), 10) - 1] } else { switch (item) { // More LC_TIME - case 'AM_STR': - return loc.LC_TIME.p[0]; - case 'PM_STR': - return loc.LC_TIME.p[1]; - case 'D_T_FMT': - return loc.LC_TIME.c; - case 'D_FMT': - return loc.LC_TIME.x; - case 'T_FMT': - return loc.LC_TIME.X; - case 'T_FMT_AMPM': - return loc.LC_TIME.r; - case 'ERA': + case 'AM_STR': + return loc.LC_TIME.p[0] + case 'PM_STR': + return loc.LC_TIME.p[1] + case 'D_T_FMT': + return loc.LC_TIME.c + case 'D_FMT': + return loc.LC_TIME.x + case 'T_FMT': + return loc.LC_TIME.X + case 'T_FMT_AMPM': + return loc.LC_TIME.r + case 'ERA': // all fall-throughs - case 'ERA_YEAR': - case 'ERA_D_T_FMT': - case 'ERA_D_FMT': - case 'ERA_T_FMT': - return loc.LC_TIME[item]; + case 'ERA_YEAR': + case 'ERA_D_T_FMT': + case 'ERA_D_FMT': + case 'ERA_T_FMT': + return loc.LC_TIME[item] } - loc = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY]; + loc = this.php_js.locales[this.php_js.localeCategories.LC_MONETARY] if (item === 'CRNCYSTR') { // alias - item = 'CURRENCY_SYMBOL'; + item = 'CURRENCY_SYMBOL' } switch (item) { - case 'INT_CURR_SYMBOL': + case 'INT_CURR_SYMBOL': // all fall-throughs - case 'CURRENCY_SYMBOL': - case 'MON_DECIMAL_POINT': - case 'MON_THOUSANDS_SEP': - case 'POSITIVE_SIGN': - case 'NEGATIVE_SIGN': - case 'INT_FRAC_DIGITS': - case 'FRAC_DIGITS': - case 'P_CS_PRECEDES': - case 'P_SEP_BY_SPACE': - case 'N_CS_PRECEDES': - case 'N_SEP_BY_SPACE': - case 'P_SIGN_POSN': - case 'N_SIGN_POSN': - return loc.LC_MONETARY[item.toLowerCase()]; - case 'MON_GROUPING': + case 'CURRENCY_SYMBOL': + case 'MON_DECIMAL_POINT': + case 'MON_THOUSANDS_SEP': + case 'POSITIVE_SIGN': + case 'NEGATIVE_SIGN': + case 'INT_FRAC_DIGITS': + case 'FRAC_DIGITS': + case 'P_CS_PRECEDES': + case 'P_SEP_BY_SPACE': + case 'N_CS_PRECEDES': + case 'N_SEP_BY_SPACE': + case 'P_SIGN_POSN': + case 'N_SIGN_POSN': + return loc.LC_MONETARY[item.toLowerCase()] + case 'MON_GROUPING': // Same as above, or return something different since this returns an array? - return loc.LC_MONETARY[item.toLowerCase()]; + return loc.LC_MONETARY[item.toLowerCase()] } - loc = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC]; + loc = this.php_js.locales[this.php_js.localeCategories.LC_NUMERIC] switch (item) { - case 'RADIXCHAR': + case 'RADIXCHAR': // Fall-through - case 'DECIMAL_POINT': - return loc.LC_NUMERIC[item.toLowerCase()]; - case 'THOUSEP': + case 'DECIMAL_POINT': + return loc.LC_NUMERIC[item.toLowerCase()] + case 'THOUSEP': // Fall-through - case 'THOUSANDS_SEP': - return loc.LC_NUMERIC[item.toLowerCase()]; - case 'GROUPING': + case 'THOUSANDS_SEP': + return loc.LC_NUMERIC[item.toLowerCase()] + case 'GROUPING': // Same as above, or return something different since this returns an array? - return loc.LC_NUMERIC[item.toLowerCase()]; + return loc.LC_NUMERIC[item.toLowerCase()] } - loc = this.php_js.locales[this.php_js.localeCategories.LC_MESSAGES]; + loc = this.php_js.locales[this.php_js.localeCategories.LC_MESSAGES] switch (item) { - case 'YESEXPR': + case 'YESEXPR': // all fall-throughs - case 'NOEXPR': - case 'YESSTR': - case 'NOSTR': - return loc.LC_MESSAGES[item]; + case 'NOEXPR': + case 'YESSTR': + case 'NOSTR': + return loc.LC_MESSAGES[item] } - loc = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE]; + loc = this.php_js.locales[this.php_js.localeCategories.LC_CTYPE] if (item === 'CODESET') { - return loc.LC_CTYPE[item]; + return loc.LC_CTYPE[item] } - return false; + return false } -} \ No newline at end of file +} diff --git a/functions/strings/number_format.js b/functions/strings/number_format.js index 195f0ecca0..c9cc5325a4 100644 --- a/functions/strings/number_format.js +++ b/functions/strings/number_format.js @@ -1,4 +1,4 @@ -function number_format(number, decimals, dec_point, thousands_sep) { +function number_format (number, decimals, dec_point, thousands_sep) { // discuss at: http://phpjs.org/functions/number_format/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -50,28 +50,28 @@ function number_format(number, decimals, dec_point, thousands_sep) { // returns 14: '0.00000001' number = (number + '') - .replace(/[^0-9+\-Ee.]/g, ''); + .replace(/[^0-9+\-Ee.]/g, '') var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', - toFixedFix = function(n, prec) { - var k = Math.pow(10, prec); + toFixedFix = function (n, prec) { + var k = Math.pow(10, prec) return '' + (Math.round(n * k) / k) - .toFixed(prec); - }; + .toFixed(prec) + } // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)) - .split('.'); + .split('.') if (s[0].length > 3) { - s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); + s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep) } if ((s[1] || '') .length < prec) { - s[1] = s[1] || ''; + s[1] = s[1] || '' s[1] += new Array(prec - s[1].length + 1) - .join('0'); + .join('0') } - return s.join(dec); -} \ No newline at end of file + return s.join(dec) +} diff --git a/functions/strings/ord.js b/functions/strings/ord.js index 5447f77aae..6519fe9f9e 100644 --- a/functions/strings/ord.js +++ b/functions/strings/ord.js @@ -1,4 +1,4 @@ -function ord(string) { +function ord (string) { // discuss at: http://phpjs.org/functions/ord/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -10,23 +10,23 @@ function ord(string) { // returns 2: 65536 var str = string + '', - code = str.charCodeAt(0); + code = str.charCodeAt(0) if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters) - var hi = code; + var hi = code if (str.length === 1) { // This is just a high surrogate with no following low surrogate, so we return its value; - return code; + return code // we could also throw an error as it is not a complete character, but someone may want to know } - var low = str.charCodeAt(1); - return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; + var low = str.charCodeAt(1) + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000 } if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate // This is just a low surrogate with no preceding high surrogate, so we return its value; - return code; + return code // we could also throw an error as it is not a complete character, but someone may want to know } - return code; -} \ No newline at end of file + return code +} diff --git a/functions/strings/parse_str.js b/functions/strings/parse_str.js index bf685b8106..ef687bb4e0 100644 --- a/functions/strings/parse_str.js +++ b/functions/strings/parse_str.js @@ -1,4 +1,4 @@ -function parse_str(str, array) { +function parse_str (str, array) { // discuss at: http://phpjs.org/functions/parse_str/ // original by: Cagri Ekin // improved by: Michael White (http://getsprink.com) @@ -36,82 +36,82 @@ function parse_str(str, array) { sal = strArr.length, i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value, postLeftBracketPos, keys, keysLen, - fixStr = function(str) { - return decodeURIComponent(str.replace(/\+/g, '%20')); - }; + fixStr = function (str) { + return decodeURIComponent(str.replace(/\+/g, '%20')) + } if (!array) { - array = this.window; + array = this.window } for (i = 0; i < sal; i++) { - tmp = strArr[i].split('='); - key = fixStr(tmp[0]); - value = (tmp.length < 2) ? '' : fixStr(tmp[1]); + tmp = strArr[i].split('=') + key = fixStr(tmp[0]) + value = (tmp.length < 2) ? '' : fixStr(tmp[1]) while (key.charAt(0) === ' ') { - key = key.slice(1); + key = key.slice(1) } if (key.indexOf('\x00') > -1) { - key = key.slice(0, key.indexOf('\x00')); + key = key.slice(0, key.indexOf('\x00')) } if (key && key.charAt(0) !== '[') { - keys = []; - postLeftBracketPos = 0; + keys = [] + postLeftBracketPos = 0 for (j = 0; j < key.length; j++) { if (key.charAt(j) === '[' && !postLeftBracketPos) { - postLeftBracketPos = j + 1; + postLeftBracketPos = j + 1 } else if (key.charAt(j) === ']') { if (postLeftBracketPos) { if (!keys.length) { - keys.push(key.slice(0, postLeftBracketPos - 1)); + keys.push(key.slice(0, postLeftBracketPos - 1)) } - keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos)); - postLeftBracketPos = 0; + keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos)) + postLeftBracketPos = 0 if (key.charAt(j + 1) !== '[') { - break; + break } } } } if (!keys.length) { - keys = [key]; + keys = [key] } for (j = 0; j < keys[0].length; j++) { - chr = keys[0].charAt(j); + chr = keys[0].charAt(j) if (chr === ' ' || chr === '.' || chr === '[') { - keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1); + keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1) } if (chr === '[') { - break; + break } } - obj = array; + obj = array for (j = 0, keysLen = keys.length; j < keysLen; j++) { key = keys[j].replace(/^['"]/, '') - .replace(/['"]$/, ''); - lastIter = j !== keys.length - 1; - lastObj = obj; + .replace(/['"]$/, '') + lastIter = j !== keys.length - 1 + lastObj = obj if ((key !== '' && key !== ' ') || j === 0) { if (obj[key] === undef) { - obj[key] = {}; + obj[key] = {} } - obj = obj[key]; + obj = obj[key] } else { // To insert new dimension - ct = -1; + ct = -1 for (p in obj) { if (obj.hasOwnProperty(p)) { if (+p > ct && p.match(/^\d+$/g)) { - ct = +p; + ct = +p } } } - key = ct + 1; + key = ct + 1 } } - lastObj[key] = value; + lastObj[key] = value } } -} \ No newline at end of file +} diff --git a/functions/strings/printf.js b/functions/strings/printf.js index 3635edfa37..f4a6399e92 100644 --- a/functions/strings/printf.js +++ b/functions/strings/printf.js @@ -1,4 +1,4 @@ -function printf() { +function printf () { // discuss at: http://phpjs.org/functions/printf/ // original by: Ash Searle (http://hexmen.com/blog/) // improved by: Michael White (http://getsprink.com) @@ -7,21 +7,21 @@ function printf() { // example 1: printf("%01.2f", 123.1); // returns 1: 6 - var body, elmt, d = this.window.document; - var ret = ''; + var body, elmt, d = this.window.document + var ret = '' - var HTMLNS = 'http://www.w3.org/1999/xhtml'; + var HTMLNS = 'http://www.w3.org/1999/xhtml' body = d.getElementsByTagNameNS ? (d.getElementsByTagNameNS(HTMLNS, 'body')[0] ? d.getElementsByTagNameNS(HTMLNS, - 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0]; + 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0] if (!body) { - return false; + return false } - ret = this.sprintf.apply(this, arguments); + ret = this.sprintf.apply(this, arguments) - elmt = d.createTextNode(ret); - body.appendChild(elmt); + elmt = d.createTextNode(ret) + body.appendChild(elmt) - return ret.length; -} \ No newline at end of file + return ret.length +} diff --git a/functions/strings/quoted_printable_decode.js b/functions/strings/quoted_printable_decode.js index 9cf198b21b..bd1f022213 100644 --- a/functions/strings/quoted_printable_decode.js +++ b/functions/strings/quoted_printable_decode.js @@ -1,4 +1,4 @@ -function quoted_printable_decode(str) { +function quoted_printable_decode (str) { // discuss at: http://phpjs.org/functions/quoted_printable_decode/ // original by: Ole Vrijenhoek // bugfixed by: Brett Zamir (http://brett-zamir.me) @@ -19,9 +19,9 @@ function quoted_printable_decode(str) { RFC2045Decode2IN = /=([0-9A-F]{2})/gim, // the RFC states against decoding lower case encodings, but following apparent PHP behavior // RFC2045Decode2IN = /=([0-9A-F]{2})/gm, - RFC2045Decode2OUT = function(sMatch, sHex) { - return String.fromCharCode(parseInt(sHex, 16)); - }; + RFC2045Decode2OUT = function (sMatch, sHex) { + return String.fromCharCode(parseInt(sHex, 16)) + } return str.replace(RFC2045Decode1, '') - .replace(RFC2045Decode2IN, RFC2045Decode2OUT); -} \ No newline at end of file + .replace(RFC2045Decode2IN, RFC2045Decode2OUT) +} diff --git a/functions/strings/quoted_printable_encode.js b/functions/strings/quoted_printable_encode.js index 014cf474ae..25f68a71a0 100644 --- a/functions/strings/quoted_printable_encode.js +++ b/functions/strings/quoted_printable_encode.js @@ -1,4 +1,4 @@ -function quoted_printable_encode(str) { +function quoted_printable_encode (str) { // discuss at: http://phpjs.org/functions/quoted_printable_encode/ // original by: Theriault // improved by: Brett Zamir (http://brett-zamir.me) @@ -12,27 +12,27 @@ function quoted_printable_encode(str) { var hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'], RFC2045Encode1IN = / \r\n|\r\n|[^!-<>-~ ]/gm, - RFC2045Encode1OUT = function(sMatch) { + RFC2045Encode1OUT = function (sMatch) { // Encode space before CRLF sequence to prevent spaces from being stripped // Keep hard line breaks intact; CRLF sequences if (sMatch.length > 1) { - return sMatch.replace(' ', '=20'); + return sMatch.replace(' ', '=20') } // Encode matching character - var chr = sMatch.charCodeAt(0); - return '=' + hexChars[((chr >>> 4) & 15)] + hexChars[(chr & 15)]; - }; + var chr = sMatch.charCodeAt(0) + return '=' + hexChars[((chr >>> 4) & 15)] + hexChars[(chr & 15)] + } // Split lines to 75 characters; the reason it's 75 and not 76 is because softline breaks are preceeded by an equal sign; which would be the 76th character. // However, if the last line/string was exactly 76 characters, then a softline would not be needed. PHP currently softbreaks anyway; so this function replicates PHP. RFC2045Encode2IN = /.{1,72}(?!\r\n)[^=]{0,3}/g, - RFC2045Encode2OUT = function(sMatch) { + RFC2045Encode2OUT = function (sMatch) { if (sMatch.substr(sMatch.length - 2) === '\r\n') { - return sMatch; + return sMatch } - return sMatch + '=\r\n'; - }; + return sMatch + '=\r\n' + } str = str.replace(RFC2045Encode1IN, RFC2045Encode1OUT) - .replace(RFC2045Encode2IN, RFC2045Encode2OUT); + .replace(RFC2045Encode2IN, RFC2045Encode2OUT) // Strip last softline break - return str.substr(0, str.length - 3); -} \ No newline at end of file + return str.substr(0, str.length - 3) +} diff --git a/functions/strings/quotemeta.js b/functions/strings/quotemeta.js index cbb0666b9a..0f8f6a180c 100644 --- a/functions/strings/quotemeta.js +++ b/functions/strings/quotemeta.js @@ -1,9 +1,9 @@ -function quotemeta(str) { +function quotemeta (str) { // discuss at: http://phpjs.org/functions/quotemeta/ // original by: Paulo Freitas // example 1: quotemeta(". + * ? ^ ( $ )"); // returns 1: '\\. \\+ \\* \\? \\^ \\( \\$ \\)' return (str + '') - .replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1'); -} \ No newline at end of file + .replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1') +} diff --git a/functions/strings/rtrim.js b/functions/strings/rtrim.js index 8984939db1..5970bcc7bf 100644 --- a/functions/strings/rtrim.js +++ b/functions/strings/rtrim.js @@ -1,4 +1,4 @@ -function rtrim(str, charlist) { +function rtrim (str, charlist) { // discuss at: http://phpjs.org/functions/rtrim/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // input by: Erkekjetter @@ -10,8 +10,8 @@ function rtrim(str, charlist) { // returns 1: ' Kevin van Zonneveld' charlist = !charlist ? ' \\s\u00A0' : (charlist + '') - .replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1'); - var re = new RegExp('[' + charlist + ']+$', 'g'); + .replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1') + var re = new RegExp('[' + charlist + ']+$', 'g') return (str + '') - .replace(re, ''); -} \ No newline at end of file + .replace(re, '') +} diff --git a/functions/strings/setlocale.js b/functions/strings/setlocale.js index f830f83f81..60fd556369 100644 --- a/functions/strings/setlocale.js +++ b/functions/strings/setlocale.js @@ -1,4 +1,4 @@ -function setlocale(category, locale) { +function setlocale (category, locale) { // discuss at: http://phpjs.org/functions/setlocale/ // original by: Brett Zamir (http://brett-zamir.me) // original by: Blues at http://hacks.bluesmoon.info/strftime/strftime.js @@ -15,25 +15,25 @@ function setlocale(category, locale) { var categ = '', cats = [], i = 0, - d = this.window.document; + d = this.window.document // BEGIN STATIC - var _copy = function _copy(orig) { + var _copy = function _copy (orig) { if (orig instanceof RegExp) { - return new RegExp(orig); + return new RegExp(orig) } else if (orig instanceof Date) { - return new Date(orig); + return new Date(orig) } - var newObj = {}; + var newObj = {} for (var i in orig) { if (typeof orig[i] === 'object') { - newObj[i] = _copy(orig[i]); + newObj[i] = _copy(orig[i]) } else { - newObj[i] = orig[i]; + newObj[i] = orig[i] } } - return newObj; - }; + return newObj + } // Function usable by a ngettext implementation (apparently not an accessible part of setlocale(), but locale-specific) // See http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms though amended with others from @@ -43,311 +43,311 @@ function setlocale(category, locale) { // Need to look into http://cldr.unicode.org/ (maybe future JavaScript); Dojo has some functions (under new BSD), // including JSON conversions of LDML XML from CLDR: http://bugs.dojotoolkit.org/browser/dojo/trunk/cldr // and docs at http://api.dojotoolkit.org/jsdoc/HEAD/dojo.cldr - var _nplurals1 = function(n) { + var _nplurals1 = function (n) { // e.g., Japanese - return 0; - }; - var _nplurals2a = function(n) { + return 0 + } + var _nplurals2a = function (n) { // e.g., English - return n !== 1 ? 1 : 0; - }; - var _nplurals2b = function(n) { + return n !== 1 ? 1 : 0 + } + var _nplurals2b = function (n) { // e.g., French - return n > 1 ? 1 : 0; - }; - var _nplurals2c = function(n) { + return n > 1 ? 1 : 0 + } + var _nplurals2c = function (n) { // e.g., Icelandic (MDC) - return n % 10 === 1 && n % 100 !== 11 ? 0 : 1; - }; - var _nplurals3a = function(n) { + return n % 10 === 1 && n % 100 !== 11 ? 0 : 1 + } + var _nplurals3a = function (n) { // e.g., Latvian (MDC has a different order from gettext) - return n % 10 === 1 && n % 100 !== 11 ? 0 : n !== 0 ? 1 : 2; - }; - var _nplurals3b = function(n) { + return n % 10 === 1 && n % 100 !== 11 ? 0 : n !== 0 ? 1 : 2 + } + var _nplurals3b = function (n) { // e.g., Scottish Gaelic - return n === 1 ? 0 : n === 2 ? 1 : 2; - }; - var _nplurals3c = function(n) { + return n === 1 ? 0 : n === 2 ? 1 : 2 + } + var _nplurals3c = function (n) { // e.g., Romanian - return n === 1 ? 0 : (n === 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2; - }; - var _nplurals3d = function(n) { + return n === 1 ? 0 : (n === 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2 + } + var _nplurals3d = function (n) { // e.g., Lithuanian (MDC has a different order from gettext) - return n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; - }; - var _nplurals3e = function(n) { + return n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2 + } + var _nplurals3e = function (n) { // e.g., Croatian return n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : - 2; - }; - var _nplurals3f = function(n) { + 2 + } + var _nplurals3f = function (n) { // e.g., Slovak - return n === 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2; - }; - var _nplurals3g = function(n) { + return n === 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2 + } + var _nplurals3g = function (n) { // e.g., Polish - return n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; - }; - var _nplurals3h = function(n) { + return n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2 + } + var _nplurals3h = function (n) { // e.g., Macedonian (MDC) - return n % 10 === 1 ? 0 : n % 10 === 2 ? 1 : 2; - }; - var _nplurals4a = function(n) { + return n % 10 === 1 ? 0 : n % 10 === 2 ? 1 : 2 + } + var _nplurals4a = function (n) { // e.g., Slovenian - return n % 100 === 1 ? 0 : n % 100 === 2 ? 1 : n % 100 === 3 || n % 100 === 4 ? 2 : 3; - }; - var _nplurals4b = function(n) { + return n % 100 === 1 ? 0 : n % 100 === 2 ? 1 : n % 100 === 3 || n % 100 === 4 ? 2 : 3 + } + var _nplurals4b = function (n) { // e.g., Maltese (MDC) - return n === 1 ? 0 : n === 0 || (n % 100 && n % 100 <= 10) ? 1 : n % 100 >= 11 && n % 100 <= 19 ? 2 : 3; - }; - var _nplurals5 = function(n) { + return n === 1 ? 0 : n === 0 || (n % 100 && n % 100 <= 10) ? 1 : n % 100 >= 11 && n % 100 <= 19 ? 2 : 3 + } + var _nplurals5 = function (n) { // e.g., Irish Gaeilge (MDC) - return n === 1 ? 0 : n === 2 ? 1 : n >= 3 && n <= 6 ? 2 : n >= 7 && n <= 10 ? 3 : 4; - }; - var _nplurals6 = function(n) { + return n === 1 ? 0 : n === 2 ? 1 : n >= 3 && n <= 6 ? 2 : n >= 7 && n <= 10 ? 3 : 4 + } + var _nplurals6 = function (n) { // e.g., Arabic (MDC) - Per MDC puts 0 as last group return n === 0 ? 5 : n === 1 ? 0 : n === 2 ? 1 : n % 100 >= 3 && n % 100 <= 10 ? 2 : n % 100 >= 11 && n % 100 <= - 99 ? 3 : 4; - }; + 99 ? 3 : 4 + } // END STATIC // BEGIN REDUNDANT try { - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} } catch (e) { - this.php_js = {}; + this.php_js = {} } - var phpjs = this.php_js; + var phpjs = this.php_js // Reconcile Windows vs. *nix locale names? // Allow different priority orders of languages, esp. if implement gettext as in // LANGUAGE env. var.? (e.g., show German if French is not available) if (!phpjs.locales) { // Can add to the locales - phpjs.locales = {}; + phpjs.locales = {} phpjs.locales.en = { - 'LC_COLLATE' : // For strcoll + 'LC_COLLATE': // For strcoll - function(str1, str2) { + function (str1, str2) { // Fix: This one taken from strcmp, but need for other locales; we don't use localeCompare since its locale is not settable - return (str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1); - }, - 'LC_CTYPE' : { + return (str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1) + }, + 'LC_CTYPE': { // Need to change any of these for English as opposed to C? - an : /^[A-Za-z\d]+$/g, - al : /^[A-Za-z]+$/g, - ct : /^[\u0000-\u001F\u007F]+$/g, - dg : /^[\d]+$/g, - gr : /^[\u0021-\u007E]+$/g, - lw : /^[a-z]+$/g, - pr : /^[\u0020-\u007E]+$/g, - pu : /^[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]+$/g, - sp : /^[\f\n\r\t\v ]+$/g, - up : /^[A-Z]+$/g, - xd : /^[A-Fa-f\d]+$/g, - CODESET : 'UTF-8', + an: /^[A-Za-z\d]+$/g, + al: /^[A-Za-z]+$/g, + ct: /^[\u0000-\u001F\u007F]+$/g, + dg: /^[\d]+$/g, + gr: /^[\u0021-\u007E]+$/g, + lw: /^[a-z]+$/g, + pr: /^[\u0020-\u007E]+$/g, + pu: /^[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]+$/g, + sp: /^[\f\n\r\t\v ]+$/g, + up: /^[A-Z]+$/g, + xd: /^[A-Fa-f\d]+$/g, + CODESET: 'UTF-8', // Used by sql_regcase - lower : 'abcdefghijklmnopqrstuvwxyz', - upper : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + lower: 'abcdefghijklmnopqrstuvwxyz', + upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' }, - 'LC_TIME' : { + 'LC_TIME': { // Comments include nl_langinfo() constant equivalents and any changes from Blues' implementation - a : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // ABDAY_ - A : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // DAY_ - b : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // ABMON_ - B : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', + B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], // MON_ - c : '%a %d %b %Y %r %Z', + c: '%a %d %b %Y %r %Z', // D_T_FMT // changed %T to %r per results - p : ['AM', 'PM'], + p: ['AM', 'PM'], // AM_STR/PM_STR - P : ['am', 'pm'], + P: ['am', 'pm'], // Not available in nl_langinfo() - r : '%I:%M:%S %p', + r: '%I:%M:%S %p', // T_FMT_AMPM (Fixed for all locales) - x : '%m/%d/%Y', + x: '%m/%d/%Y', // D_FMT // switched order of %m and %d; changed %y to %Y (C uses %y) - X : '%r', + X: '%r', // T_FMT // changed from %T to %r (%T is default for C, not English US) // Following are from nl_langinfo() or http://www.cptec.inpe.br/sx4/sx4man2/g1ab02e/strftime.4.html - alt_digits : '', + alt_digits: '', // e.g., ordinal - ERA : '', - ERA_YEAR : '', - ERA_D_T_FMT : '', - ERA_D_FMT : '', - ERA_T_FMT : '' + ERA: '', + ERA_YEAR: '', + ERA_D_T_FMT: '', + ERA_D_FMT: '', + ERA_T_FMT: '' }, // Assuming distinction between numeric and monetary is thus: // See below for C locale - 'LC_MONETARY' : { + 'LC_MONETARY': { // based on Windows "english" (English_United States.1252) locale - int_curr_symbol : 'USD', - currency_symbol : '$', - mon_decimal_point : '.', - mon_thousands_sep : ',', - mon_grouping : [3], + int_curr_symbol: 'USD', + currency_symbol: '$', + mon_decimal_point: '.', + mon_thousands_sep: ',', + mon_grouping: [3], // use mon_thousands_sep; "" for no grouping; additional array members indicate successive group lengths after first group (e.g., if to be 1,23,456, could be [3, 2]) - positive_sign : '', - negative_sign : '-', - int_frac_digits : 2, + positive_sign: '', + negative_sign: '-', + int_frac_digits: 2, // Fractional digits only for money defaults? - frac_digits : 2, - p_cs_precedes : 1, + frac_digits: 2, + p_cs_precedes: 1, // positive currency symbol follows value = 0; precedes value = 1 - p_sep_by_space : 0, + p_sep_by_space: 0, // 0: no space between curr. symbol and value; 1: space sep. them unless symb. and sign are adjacent then space sep. them from value; 2: space sep. sign and value unless symb. and sign are adjacent then space separates - n_cs_precedes : 1, + n_cs_precedes: 1, // see p_cs_precedes - n_sep_by_space : 0, + n_sep_by_space: 0, // see p_sep_by_space - p_sign_posn : 3, + p_sign_posn: 3, // 0: parentheses surround quantity and curr. symbol; 1: sign precedes them; 2: sign follows them; 3: sign immed. precedes curr. symbol; 4: sign immed. succeeds curr. symbol - n_sign_posn : 0 // see p_sign_posn + n_sign_posn: 0 // see p_sign_posn }, - 'LC_NUMERIC' : { + 'LC_NUMERIC': { // based on Windows "english" (English_United States.1252) locale - decimal_point : '.', - thousands_sep : ',', - grouping : [3] // see mon_grouping, but for non-monetary values (use thousands_sep) + decimal_point: '.', + thousands_sep: ',', + grouping: [3] // see mon_grouping, but for non-monetary values (use thousands_sep) }, - 'LC_MESSAGES' : { - YESEXPR : '^[yY].*', - NOEXPR : '^[nN].*', - YESSTR : '', - NOSTR : '' + 'LC_MESSAGES': { + YESEXPR: '^[yY].*', + NOEXPR: '^[nN].*', + YESSTR: '', + NOSTR: '' }, - nplurals : _nplurals2a - }; - phpjs.locales.en_US = _copy(phpjs.locales.en); - phpjs.locales.en_US.LC_TIME.c = '%a %d %b %Y %r %Z'; - phpjs.locales.en_US.LC_TIME.x = '%D'; - phpjs.locales.en_US.LC_TIME.X = '%r'; + nplurals: _nplurals2a + } + phpjs.locales.en_US = _copy(phpjs.locales.en) + phpjs.locales.en_US.LC_TIME.c = '%a %d %b %Y %r %Z' + phpjs.locales.en_US.LC_TIME.x = '%D' + phpjs.locales.en_US.LC_TIME.X = '%r' // The following are based on *nix settings - phpjs.locales.en_US.LC_MONETARY.int_curr_symbol = 'USD '; - phpjs.locales.en_US.LC_MONETARY.p_sign_posn = 1; - phpjs.locales.en_US.LC_MONETARY.n_sign_posn = 1; - phpjs.locales.en_US.LC_MONETARY.mon_grouping = [3, 3]; - phpjs.locales.en_US.LC_NUMERIC.thousands_sep = ''; - phpjs.locales.en_US.LC_NUMERIC.grouping = []; + phpjs.locales.en_US.LC_MONETARY.int_curr_symbol = 'USD ' + phpjs.locales.en_US.LC_MONETARY.p_sign_posn = 1 + phpjs.locales.en_US.LC_MONETARY.n_sign_posn = 1 + phpjs.locales.en_US.LC_MONETARY.mon_grouping = [3, 3] + phpjs.locales.en_US.LC_NUMERIC.thousands_sep = '' + phpjs.locales.en_US.LC_NUMERIC.grouping = [] - phpjs.locales.en_GB = _copy(phpjs.locales.en); - phpjs.locales.en_GB.LC_TIME.r = '%l:%M:%S %P %Z'; + phpjs.locales.en_GB = _copy(phpjs.locales.en) + phpjs.locales.en_GB.LC_TIME.r = '%l:%M:%S %P %Z' - phpjs.locales.en_AU = _copy(phpjs.locales.en_GB); + phpjs.locales.en_AU = _copy(phpjs.locales.en_GB) // Assume C locale is like English (?) (We need C locale for LC_CTYPE) - phpjs.locales.C = _copy(phpjs.locales.en); - phpjs.locales.C.LC_CTYPE.CODESET = 'ANSI_X3.4-1968'; + phpjs.locales.C = _copy(phpjs.locales.en) + phpjs.locales.C.LC_CTYPE.CODESET = 'ANSI_X3.4-1968' phpjs.locales.C.LC_MONETARY = { - int_curr_symbol : '', - currency_symbol : '', - mon_decimal_point : '', - mon_thousands_sep : '', - mon_grouping : [], - p_cs_precedes : 127, - p_sep_by_space : 127, - n_cs_precedes : 127, - n_sep_by_space : 127, - p_sign_posn : 127, - n_sign_posn : 127, - positive_sign : '', - negative_sign : '', - int_frac_digits : 127, - frac_digits : 127 - }; + int_curr_symbol: '', + currency_symbol: '', + mon_decimal_point: '', + mon_thousands_sep: '', + mon_grouping: [], + p_cs_precedes: 127, + p_sep_by_space: 127, + n_cs_precedes: 127, + n_sep_by_space: 127, + p_sign_posn: 127, + n_sign_posn: 127, + positive_sign: '', + negative_sign: '', + int_frac_digits: 127, + frac_digits: 127 + } phpjs.locales.C.LC_NUMERIC = { - decimal_point : '.', - thousands_sep : '', - grouping : [] - }; + decimal_point: '.', + thousands_sep: '', + grouping: [] + } // D_T_FMT - phpjs.locales.C.LC_TIME.c = '%a %b %e %H:%M:%S %Y'; + phpjs.locales.C.LC_TIME.c = '%a %b %e %H:%M:%S %Y' // D_FMT - phpjs.locales.C.LC_TIME.x = '%m/%d/%y'; + phpjs.locales.C.LC_TIME.x = '%m/%d/%y' // T_FMT - phpjs.locales.C.LC_TIME.X = '%H:%M:%S'; - phpjs.locales.C.LC_MESSAGES.YESEXPR = '^[yY]'; - phpjs.locales.C.LC_MESSAGES.NOEXPR = '^[nN]'; + phpjs.locales.C.LC_TIME.X = '%H:%M:%S' + phpjs.locales.C.LC_MESSAGES.YESEXPR = '^[yY]' + phpjs.locales.C.LC_MESSAGES.NOEXPR = '^[nN]' - phpjs.locales.fr = _copy(phpjs.locales.en); - phpjs.locales.fr.nplurals = _nplurals2b; - phpjs.locales.fr.LC_TIME.a = ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam']; - phpjs.locales.fr.LC_TIME.A = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi']; + phpjs.locales.fr = _copy(phpjs.locales.en) + phpjs.locales.fr.nplurals = _nplurals2b + phpjs.locales.fr.LC_TIME.a = ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'] + phpjs.locales.fr.LC_TIME.A = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'] phpjs.locales.fr.LC_TIME.b = ['jan', 'f\u00E9v', 'mar', 'avr', 'mai', 'jun', 'jui', 'ao\u00FB', 'sep', 'oct', 'nov', 'd\u00E9c' - ]; + ] phpjs.locales.fr.LC_TIME.B = ['janvier', 'f\u00E9vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'ao\u00FBt', 'septembre', 'octobre', 'novembre', 'd\u00E9cembre' - ]; - phpjs.locales.fr.LC_TIME.c = '%a %d %b %Y %T %Z'; - phpjs.locales.fr.LC_TIME.p = ['', '']; - phpjs.locales.fr.LC_TIME.P = ['', '']; - phpjs.locales.fr.LC_TIME.x = '%d.%m.%Y'; - phpjs.locales.fr.LC_TIME.X = '%T'; + ] + phpjs.locales.fr.LC_TIME.c = '%a %d %b %Y %T %Z' + phpjs.locales.fr.LC_TIME.p = ['', ''] + phpjs.locales.fr.LC_TIME.P = ['', ''] + phpjs.locales.fr.LC_TIME.x = '%d.%m.%Y' + phpjs.locales.fr.LC_TIME.X = '%T' - phpjs.locales.fr_CA = _copy(phpjs.locales.fr); - phpjs.locales.fr_CA.LC_TIME.x = '%Y-%m-%d'; + phpjs.locales.fr_CA = _copy(phpjs.locales.fr) + phpjs.locales.fr_CA.LC_TIME.x = '%Y-%m-%d' } if (!phpjs.locale) { - phpjs.locale = 'en_US'; - var NS_XHTML = 'http://www.w3.org/1999/xhtml'; - var NS_XML = 'http://www.w3.org/XML/1998/namespace'; + phpjs.locale = 'en_US' + var NS_XHTML = 'http://www.w3.org/1999/xhtml' + var NS_XML = 'http://www.w3.org/XML/1998/namespace' if (d.getElementsByTagNameNS && d.getElementsByTagNameNS(NS_XHTML, 'html')[0]) { if (d.getElementsByTagNameNS(NS_XHTML, 'html')[0].getAttributeNS && d.getElementsByTagNameNS(NS_XHTML, 'html')[0].getAttributeNS(NS_XML, 'lang')) { - phpjs.locale = d.getElementsByTagName(NS_XHTML, 'html')[0].getAttributeNS(NS_XML, 'lang'); + phpjs.locale = d.getElementsByTagName(NS_XHTML, 'html')[0].getAttributeNS(NS_XML, 'lang') } else if (d.getElementsByTagNameNS(NS_XHTML, 'html')[0].lang) { // XHTML 1.0 only - phpjs.locale = d.getElementsByTagNameNS(NS_XHTML, 'html')[0].lang; + phpjs.locale = d.getElementsByTagNameNS(NS_XHTML, 'html')[0].lang } } else if (d.getElementsByTagName('html')[0] && d.getElementsByTagName('html')[0].lang) { - phpjs.locale = d.getElementsByTagName('html')[0].lang; + phpjs.locale = d.getElementsByTagName('html')[0].lang } } // PHP-style - phpjs.locale = phpjs.locale.replace('-', '_'); + phpjs.locale = phpjs.locale.replace('-', '_') // Fix locale if declared locale hasn't been defined if (!(phpjs.locale in phpjs.locales)) { if (phpjs.locale.replace(/_[a-zA-Z]+$/, '') in phpjs.locales) { - phpjs.locale = phpjs.locale.replace(/_[a-zA-Z]+$/, ''); + phpjs.locale = phpjs.locale.replace(/_[a-zA-Z]+$/, '') } } if (!phpjs.localeCategories) { phpjs.localeCategories = { - 'LC_COLLATE' : phpjs.locale, + 'LC_COLLATE': phpjs.locale, // for string comparison, see strcoll() - 'LC_CTYPE' : phpjs.locale, + 'LC_CTYPE': phpjs.locale, // for character classification and conversion, for example strtoupper() - 'LC_MONETARY' : phpjs.locale, + 'LC_MONETARY': phpjs.locale, // for localeconv() - 'LC_NUMERIC' : phpjs.locale, + 'LC_NUMERIC': phpjs.locale, // for decimal separator (See also localeconv()) - 'LC_TIME' : phpjs.locale, + 'LC_TIME': phpjs.locale, // for date and time formatting with strftime() - 'LC_MESSAGES' : phpjs.locale // for system responses (available if PHP was compiled with libintl) - }; + 'LC_MESSAGES': phpjs.locale // for system responses (available if PHP was compiled with libintl) + } } // END REDUNDANT if (locale === null || locale === '') { - locale = this.getenv(category) || this.getenv('LANG'); + locale = this.getenv(category) || this.getenv('LANG') } else if (Object.prototype.toString.call(locale) === '[object Array]') { for (i = 0; i < locale.length; i++) { if (!(locale[i] in this.php_js.locales)) { if (i === locale.length - 1) { // none found - return false; + return false } - continue; + continue } - locale = locale[i]; - break; + locale = locale[i] + break } } @@ -356,25 +356,25 @@ function setlocale(category, locale) { if (category === 'LC_ALL') { for (categ in this.php_js.localeCategories) { // Add ".UTF-8" or allow ".@latint", etc. to the end? - cats.push(categ + '=' + this.php_js.localeCategories[categ]); + cats.push(categ + '=' + this.php_js.localeCategories[categ]) } - return cats.join(';'); + return cats.join(';') } - return this.php_js.localeCategories[category]; + return this.php_js.localeCategories[category] } if (!(locale in this.php_js.locales)) { // Locale not found - return false; + return false } // Set and get locale if (category === 'LC_ALL') { for (categ in this.php_js.localeCategories) { - this.php_js.localeCategories[categ] = locale; + this.php_js.localeCategories[categ] = locale } } else { - this.php_js.localeCategories[category] = locale; + this.php_js.localeCategories[category] = locale } - return locale; -} \ No newline at end of file + return locale +} diff --git a/functions/strings/sha1.js b/functions/strings/sha1.js index 2d9ded1c59..e21a84c7fb 100644 --- a/functions/strings/sha1.js +++ b/functions/strings/sha1.js @@ -1,4 +1,4 @@ -function sha1(str) { +function sha1 (str) { // discuss at: http://phpjs.org/functions/sha1/ // original by: Webtoolkit.info (http://www.webtoolkit.info/) // improved by: Michael White (http://getsprink.com) @@ -7,12 +7,12 @@ function sha1(str) { // example 1: sha1('Kevin van Zonneveld'); // returns 1: '54916d2e62f65b3afa6e192e6a601cdbe5cb5897' - var rotate_left = function(n, s) { - var t4 = (n << s) | (n >>> (32 - s)); - return t4; - }; + var rotate_left = function (n, s) { + var t4 = (n << s) | (n >>> (32 - s)) + return t4 + } - /*var lsb_hex = function (val) { + /* var lsb_hex = function (val) { // Not in use; needed? var str=""; var i; @@ -27,121 +27,121 @@ function sha1(str) { return str; };*/ - var cvt_hex = function(val) { - var str = ''; - var i; - var v; + var cvt_hex = function (val) { + var str = '' + var i + var v for (i = 7; i >= 0; i--) { - v = (val >>> (i * 4)) & 0x0f; - str += v.toString(16); + v = (val >>> (i * 4)) & 0x0f + str += v.toString(16) } - return str; - }; - - var blockstart; - var i, j; - var W = new Array(80); - var H0 = 0x67452301; - var H1 = 0xEFCDAB89; - var H2 = 0x98BADCFE; - var H3 = 0x10325476; - var H4 = 0xC3D2E1F0; - var A, B, C, D, E; - var temp; + return str + } + + var blockstart + var i, j + var W = new Array(80) + var H0 = 0x67452301 + var H1 = 0xEFCDAB89 + var H2 = 0x98BADCFE + var H3 = 0x10325476 + var H4 = 0xC3D2E1F0 + var A, B, C, D, E + var temp // utf8_encode - str = unescape(encodeURIComponent(str)); - var str_len = str.length; + str = unescape(encodeURIComponent(str)) + var str_len = str.length - var word_array = []; + var word_array = [] for (i = 0; i < str_len - 3; i += 4) { - j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3); - word_array.push(j); + j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3) + word_array.push(j) } switch (str_len % 4) { - case 0: - i = 0x080000000; - break; - case 1: - i = str.charCodeAt(str_len - 1) << 24 | 0x0800000; - break; - case 2: - i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000; - break; - case 3: - i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << - 8 | 0x80; - break; + case 0: + i = 0x080000000 + break + case 1: + i = str.charCodeAt(str_len - 1) << 24 | 0x0800000 + break + case 2: + i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000 + break + case 3: + i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << + 8 | 0x80 + break } - word_array.push(i); + word_array.push(i) while ((word_array.length % 16) != 14) { - word_array.push(0); + word_array.push(0) } - word_array.push(str_len >>> 29); - word_array.push((str_len << 3) & 0x0ffffffff); + word_array.push(str_len >>> 29) + word_array.push((str_len << 3) & 0x0ffffffff) for (blockstart = 0; blockstart < word_array.length; blockstart += 16) { for (i = 0; i < 16; i++) { - W[i] = word_array[blockstart + i]; + W[i] = word_array[blockstart + i] } for (i = 16; i <= 79; i++) { - W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1) } - A = H0; - B = H1; - C = H2; - D = H3; - E = H4; + A = H0 + B = H1 + C = H2 + D = H3 + E = H4 for (i = 0; i <= 19; i++) { - temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; - E = D; - D = C; - C = rotate_left(B, 30); - B = A; - A = temp; + temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff + E = D + D = C + C = rotate_left(B, 30) + B = A + A = temp } for (i = 20; i <= 39; i++) { - temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff; - E = D; - D = C; - C = rotate_left(B, 30); - B = A; - A = temp; + temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff + E = D + D = C + C = rotate_left(B, 30) + B = A + A = temp } for (i = 40; i <= 59; i++) { - temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff; - E = D; - D = C; - C = rotate_left(B, 30); - B = A; - A = temp; + temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff + E = D + D = C + C = rotate_left(B, 30) + B = A + A = temp } for (i = 60; i <= 79; i++) { - temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff; - E = D; - D = C; - C = rotate_left(B, 30); - B = A; - A = temp; + temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff + E = D + D = C + C = rotate_left(B, 30) + B = A + A = temp } - H0 = (H0 + A) & 0x0ffffffff; - H1 = (H1 + B) & 0x0ffffffff; - H2 = (H2 + C) & 0x0ffffffff; - H3 = (H3 + D) & 0x0ffffffff; - H4 = (H4 + E) & 0x0ffffffff; + H0 = (H0 + A) & 0x0ffffffff + H1 = (H1 + B) & 0x0ffffffff + H2 = (H2 + C) & 0x0ffffffff + H3 = (H3 + D) & 0x0ffffffff + H4 = (H4 + E) & 0x0ffffffff } - temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); - return temp.toLowerCase(); -} \ No newline at end of file + temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4) + return temp.toLowerCase() +} diff --git a/functions/strings/sha1_file.js b/functions/strings/sha1_file.js index b28b81888e..09772a04b6 100644 --- a/functions/strings/sha1_file.js +++ b/functions/strings/sha1_file.js @@ -1,4 +1,4 @@ -function sha1_file(str_filename) { +function sha1_file (str_filename) { // discuss at: http://phpjs.org/functions/sha1_file/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // depends on: file_get_contents @@ -7,7 +7,7 @@ function sha1_file(str_filename) { // example 1: sha1_file('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm'); // returns 1: '40bd001563085fc35165329ea1ff5c5ecbdbbeef' - var buf = this.file_get_contents(str_filename); + var buf = this.file_get_contents(str_filename) - return this.sha1(buf); -} \ No newline at end of file + return this.sha1(buf) +} diff --git a/functions/strings/similar_text.js b/functions/strings/similar_text.js index bee708c549..ca070b51fa 100644 --- a/functions/strings/similar_text.js +++ b/functions/strings/similar_text.js @@ -1,4 +1,4 @@ -function similar_text(first, second, percent) { +function similar_text (first, second, percent) { // discuss at: http://phpjs.org/functions/similar_text/ // original by: Rafał Kukawski (http://blog.kukawski.pl) // bugfixed by: Chris McMacken @@ -10,50 +10,50 @@ function similar_text(first, second, percent) { // returns 2: 0 if (first === null || second === null || typeof first === 'undefined' || typeof second === 'undefined') { - return 0; + return 0 } - first += ''; - second += ''; + first += '' + second += '' var pos1 = 0, pos2 = 0, max = 0, firstLength = first.length, secondLength = second.length, - p, q, l, sum; + p, q, l, sum - max = 0; + max = 0 for (p = 0; p < firstLength; p++) { for (q = 0; q < secondLength; q++) { for (l = 0; (p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++) - ; + ; if (l > max) { - max = l; - pos1 = p; - pos2 = q; + max = l + pos1 = p + pos2 = q } } } - sum = max; + sum = max if (sum) { if (pos1 && pos2) { - sum += this.similar_text(first.substr(0, pos1), second.substr(0, pos2)); + sum += this.similar_text(first.substr(0, pos1), second.substr(0, pos2)) } if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) { sum += this.similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, - secondLength - pos2 - max)); + secondLength - pos2 - max)) } } if (!percent) { - return sum; + return sum } else { - return (sum * 200) / (firstLength + secondLength); + return (sum * 200) / (firstLength + secondLength) } -} \ No newline at end of file +} diff --git a/functions/strings/soundex.js b/functions/strings/soundex.js index ad9b4e3fef..410a205015 100644 --- a/functions/strings/soundex.js +++ b/functions/strings/soundex.js @@ -1,4 +1,4 @@ -function soundex(str) { +function soundex (str) { // discuss at: http://phpjs.org/functions/soundex/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // original by: Arnout Kazemier (http://www.3rd-Eden.com) @@ -16,46 +16,46 @@ function soundex(str) { // returns 3: 'E460' str = (str + '') - .toUpperCase(); + .toUpperCase() if (!str) { - return ''; + return '' } var sdx = [0, 0, 0, 0], m = { - B : 1, - F : 1, - P : 1, - V : 1, - C : 2, - G : 2, - J : 2, - K : 2, - Q : 2, - S : 2, - X : 2, - Z : 2, - D : 3, - T : 3, - L : 4, - M : 5, - N : 5, - R : 6 + B: 1, + F: 1, + P: 1, + V: 1, + C: 2, + G: 2, + J: 2, + K: 2, + Q: 2, + S: 2, + X: 2, + Z: 2, + D: 3, + T: 3, + L: 4, + M: 5, + N: 5, + R: 6 }, i = 0, j, s = 0, - c, p; + c, p while ((c = str.charAt(i++)) && s < 4) { if (j = m[c]) { if (j !== p) { - sdx[s++] = p = j; + sdx[s++] = p = j } } else { - s += i === 1; - p = 0; + s += i === 1 + p = 0 } } - sdx[0] = str.charAt(0); - return sdx.join(''); -} \ No newline at end of file + sdx[0] = str.charAt(0) + return sdx.join('') +} diff --git a/functions/strings/split.js b/functions/strings/split.js index 9405d7ad73..62d8cad263 100644 --- a/functions/strings/split.js +++ b/functions/strings/split.js @@ -1,9 +1,9 @@ -function split(delimiter, string) { +function split (delimiter, string) { // discuss at: http://phpjs.org/functions/split/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // depends on: explode // example 1: split(' ', 'Kevin van Zonneveld'); // returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'} - return this.explode(delimiter, string); -} \ No newline at end of file + return this.explode(delimiter, string) +} diff --git a/functions/strings/sprintf.js b/functions/strings/sprintf.js index e0575cd46f..d849eec7b9 100644 --- a/functions/strings/sprintf.js +++ b/functions/strings/sprintf.js @@ -1,4 +1,4 @@ -function sprintf() { +function sprintf () { // discuss at: http://phpjs.org/functions/sprintf/ // original by: Ash Searle (http://hexmen.com/blog/) // improved by: Michael White (http://getsprink.com) @@ -21,170 +21,170 @@ function sprintf() { // example 5: sprintf('%-03s', 'E'); // returns 5: 'E00' - var regex = /%%|%(\d+\$)?([\-+\'#0 ]*)(\*\d+\$|\*|\d+)?(?:\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g; - var a = arguments; - var i = 0; - var format = a[i++]; + var regex = /%%|%(\d+\$)?([\-+\'#0 ]*)(\*\d+\$|\*|\d+)?(?:\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g + var a = arguments + var i = 0 + var format = a[i++] // pad() - var pad = function(str, len, chr, leftJustify) { + var pad = function (str, len, chr, leftJustify) { if (!chr) { - chr = ' '; + chr = ' ' } var padding = (str.length >= len) ? '' : new Array(1 + len - str.length >>> 0) - .join(chr); - return leftJustify ? str + padding : padding + str; - }; + .join(chr) + return leftJustify ? str + padding : padding + str + } // justify() - var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) { - var diff = minWidth - value.length; + var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) { + var diff = minWidth - value.length if (diff > 0) { if (leftJustify || !zeroPad) { - value = pad(value, minWidth, customPadChar, leftJustify); + value = pad(value, minWidth, customPadChar, leftJustify) } else { - value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length); + value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length) } } - return value; - }; + return value + } // formatBaseX() - var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) { + var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) { // Note: casts negative numbers to positive ones - var number = value >>> 0; + var number = value >>> 0 prefix = (prefix && number && { - '2' : '0b', - '8' : '0', - '16' : '0x' - }[base]) || ''; - value = prefix + pad(number.toString(base), precision || 0, '0', false); - return justify(value, prefix, leftJustify, minWidth, zeroPad); - }; + '2': '0b', + '8': '0', + '16': '0x' + }[base]) || '' + value = prefix + pad(number.toString(base), precision || 0, '0', false) + return justify(value, prefix, leftJustify, minWidth, zeroPad) + } // formatString() - var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) { + var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) { if (precision !== null && precision !== undefined) { - value = value.slice(0, precision); + value = value.slice(0, precision) } - return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar); - }; + return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar) + } // doFormat() - var doFormat = function(substring, valueIndex, flags, minWidth, precision, type) { - var number, prefix, method, textTransform, value; + var doFormat = function (substring, valueIndex, flags, minWidth, precision, type) { + var number, prefix, method, textTransform, value if (substring === '%%') { - return '%'; + return '%' } // parse flags - var leftJustify = false; - var positivePrefix = ''; - var zeroPad = false; - var prefixBaseX = false; - var customPadChar = ' '; - var flagsl = flags.length; - var j; + var leftJustify = false + var positivePrefix = '' + var zeroPad = false + var prefixBaseX = false + var customPadChar = ' ' + var flagsl = flags.length + var j for (j = 0; flags && j < flagsl; j++) { switch (flags.charAt(j)) { - case ' ': - positivePrefix = ' '; - break; - case '+': - positivePrefix = '+'; - break; - case '-': - leftJustify = true; - break; - case "'": - customPadChar = flags.charAt(j + 1); - break; - case '0': - zeroPad = true; - customPadChar = '0'; - break; - case '#': - prefixBaseX = true; - break; + case ' ': + positivePrefix = ' ' + break + case '+': + positivePrefix = '+' + break + case '-': + leftJustify = true + break + case "'": + customPadChar = flags.charAt(j + 1) + break + case '0': + zeroPad = true + customPadChar = '0' + break + case '#': + prefixBaseX = true + break } } // parameters may be null, undefined, empty-string or real valued // we want to ignore null, undefined and empty-string values if (!minWidth) { - minWidth = 0; + minWidth = 0 } else if (minWidth === '*') { - minWidth = +a[i++]; + minWidth = +a[i++] } else if (minWidth.charAt(0) === '*') { - minWidth = +a[minWidth.slice(1, -1)]; + minWidth = +a[minWidth.slice(1, -1)] } else { - minWidth = +minWidth; + minWidth = +minWidth } // Note: undocumented perl feature: if (minWidth < 0) { - minWidth = -minWidth; - leftJustify = true; + minWidth = -minWidth + leftJustify = true } if (!isFinite(minWidth)) { - throw new Error('sprintf: (minimum-)width must be finite'); + throw new Error('sprintf: (minimum-)width must be finite') } if (!precision) { - precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type === 'd') ? 0 : undefined; + precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type === 'd') ? 0 : undefined } else if (precision === '*') { - precision = +a[i++]; + precision = +a[i++] } else if (precision.charAt(0) === '*') { - precision = +a[precision.slice(1, -1)]; + precision = +a[precision.slice(1, -1)] } else { - precision = +precision; + precision = +precision } // grab value using valueIndex if required? - value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++]; + value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++] switch (type) { - case 's': - return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar); - case 'c': - return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad); - case 'b': - return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad); - case 'o': - return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad); - case 'x': - return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad); - case 'X': - return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad) - .toUpperCase(); - case 'u': - return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad); - case 'i': - case 'd': - number = +value || 0; + case 's': + return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar) + case 'c': + return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad) + case 'b': + return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad) + case 'o': + return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad) + case 'x': + return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad) + case 'X': + return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad) + .toUpperCase() + case 'u': + return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad) + case 'i': + case 'd': + number = +value || 0 // Plain Math.round doesn't just truncate - number = Math.round(number - number % 1); - prefix = number < 0 ? '-' : positivePrefix; - value = prefix + pad(String(Math.abs(number)), precision, '0', false); - return justify(value, prefix, leftJustify, minWidth, zeroPad); - case 'e': - case 'E': - case 'f': // Should handle locales (as per setlocale) - case 'F': - case 'g': - case 'G': - number = +value; - prefix = number < 0 ? '-' : positivePrefix; - method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())]; - textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2]; - value = prefix + Math.abs(number)[method](precision); - return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform](); - default: - return substring; + number = Math.round(number - number % 1) + prefix = number < 0 ? '-' : positivePrefix + value = prefix + pad(String(Math.abs(number)), precision, '0', false) + return justify(value, prefix, leftJustify, minWidth, zeroPad) + case 'e': + case 'E': + case 'f': // Should handle locales (as per setlocale) + case 'F': + case 'g': + case 'G': + number = +value + prefix = number < 0 ? '-' : positivePrefix + method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())] + textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2] + value = prefix + Math.abs(number)[method](precision) + return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]() + default: + return substring } - }; + } - return format.replace(regex, doFormat); -} \ No newline at end of file + return format.replace(regex, doFormat) +} diff --git a/functions/strings/sscanf.js b/functions/strings/sscanf.js index 1b13ec5a4e..adef152ec8 100644 --- a/functions/strings/sscanf.js +++ b/functions/strings/sscanf.js @@ -1,4 +1,4 @@ -function sscanf(str, format) { +function sscanf (str, format) { // discuss at: http://phpjs.org/functions/sscanf/ // original by: Brett Zamir (http://brett-zamir.me) // note: Since JS does not support scalar reference variables, any additional arguments to the function will @@ -19,106 +19,106 @@ function sscanf(str, format) { _NWS = /\S/, args = arguments, that = this, - digit; + digit - var _setExtraConversionSpecs = function(offset) { + var _setExtraConversionSpecs = function (offset) { // Since a mismatched character sets us off track from future legitimate finds, we just scan // to the end for any other conversion specifications (besides a percent literal), setting them to null // sscanf seems to disallow all conversion specification components (of sprintf) except for type specifiers // Do not allow % in last char. class - //var matches = format.match(/%[+-]?([ 0]|'.)?-?\d*(\.\d+)?[bcdeufFosxX]/g); + // var matches = format.match(/%[+-]?([ 0]|'.)?-?\d*(\.\d+)?[bcdeufFosxX]/g); var matches = format.slice(offset) - .match(/%[cdeEufgosxX]/g); // Do not allow % in last char. class; + .match(/%[cdeEufgosxX]/g) // Do not allow % in last char. class; // b, F,G give errors in PHP, but 'g', though also disallowed, doesn't if (matches) { - var lgth = matches.length; + var lgth = matches.length while (lgth--) { - retArr.push(null); + retArr.push(null) } } - return _finish(); - }; + return _finish() + } - var _finish = function() { + var _finish = function () { if (args.length === 2) { - return retArr; + return retArr } for (var i = 0; i < retArr.length; ++i) { - that.window[args[i + 2]] = retArr[i]; + that.window[args[i + 2]] = retArr[i] } - return i; - }; + return i + } - var _addNext = function(j, regex, cb) { + var _addNext = function (j, regex, cb) { if (assign) { - var remaining = str.slice(j); - var check = width ? remaining.substr(0, width) : remaining; - var match = regex.exec(check); + var remaining = str.slice(j) + var check = width ? remaining.substr(0, width) : remaining + var match = regex.exec(check) var testNull = retArr[digit !== undefined ? digit : retArr.length] = match ? (cb ? cb.apply(null, match) : - match[0]) : null; + match[0]) : null if (testNull === null) { - throw 'No match in string'; + throw 'No match in string' } - return j + match[0].length; + return j + match[0].length } - return j; - }; + return j + } if (arguments.length < 2) { - throw 'Not enough arguments passed to sscanf'; + throw 'Not enough arguments passed to sscanf' } // PROCESS for (var i = 0, j = 0; i < format.length; i++) { var width = 0, - assign = true; + assign = true if (format.charAt(i) === '%') { if (format.charAt(i + 1) === '%') { if (str.charAt(j) === '%') { // a matched percent literal // skip beyond duplicated percent - ++i, ++j; - continue; + ++i, ++j + continue } // Format indicated a percent literal, but not actually present - return _setExtraConversionSpecs(i + 2); + return _setExtraConversionSpecs(i + 2) } // CHARACTER FOLLOWING PERCENT IS NOT A PERCENT // We need 'g' set to get lastIndex - var prePattern = new RegExp('^(?:(\\d+)\\$)?(\\*)?(\\d*)([hlL]?)', 'g'); + var prePattern = new RegExp('^(?:(\\d+)\\$)?(\\*)?(\\d*)([hlL]?)', 'g') - var preConvs = prePattern.exec(format.slice(i + 1)); + var preConvs = prePattern.exec(format.slice(i + 1)) - var tmpDigit = digit; + var tmpDigit = digit if (tmpDigit && preConvs[1] === undefined) { - throw 'All groups in sscanf() must be expressed as numeric if any have already been used'; + throw 'All groups in sscanf() must be expressed as numeric if any have already been used' } - digit = preConvs[1] ? parseInt(preConvs[1], 10) - 1 : undefined; + digit = preConvs[1] ? parseInt(preConvs[1], 10) - 1 : undefined - assign = !preConvs[2]; - width = parseInt(preConvs[3], 10); - var sizeCode = preConvs[4]; - i += prePattern.lastIndex; + assign = !preConvs[2] + width = parseInt(preConvs[3], 10) + var sizeCode = preConvs[4] + i += prePattern.lastIndex // Fix: Does PHP do anything with these? Seems not to matter if (sizeCode) { // This would need to be processed later switch (sizeCode) { - case 'h': + case 'h': // Treats subsequent as short int (for d,i,n) or unsigned short int (for o,u,x) - case 'l': + case 'l': // Treats subsequent as long int (for d,i,n), or unsigned long int (for o,u,x); // or as double (for e,f,g) instead of float or wchar_t instead of char - case 'L': + case 'L': // Treats subsequent as long double (for e,f,g) - break; - default: - throw 'Unexpected size specifier in sscanf()!'; - break; + break + default: + throw 'Unexpected size specifier in sscanf()!' + break } } // PROCESS CHARACTER @@ -128,135 +128,135 @@ function sscanf(str, format) { // Also http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sscanf.html // p, S, C arguments in C function not available // DOCUMENTED UNDER SSCANF - case 'F': + case 'F': // Not supported in PHP sscanf; the argument is treated as a float, and // presented as a floating-point number (non-locale aware) // sscanf doesn't support locales, so no need for two (see %f) - break; - case 'g': + break + case 'g': // Not supported in PHP sscanf; shorter of %e and %f // Irrelevant to input conversion - break; - case 'G': + break + case 'G': // Not supported in PHP sscanf; shorter of %E and %f // Irrelevant to input conversion - break; - case 'b': + break + case 'b': // Not supported in PHP sscanf; the argument is treated as an integer, and presented as a binary number // Not supported - couldn't distinguish from other integers - break; - case 'i': + break + case 'i': // Integer with base detection (Equivalent of 'd', but base 0 instead of 10) - j = _addNext(j, /([+-])?(?:(?:0x([\da-fA-F]+))|(?:0([0-7]+))|(\d+))/, function(num, sign, hex, + j = _addNext(j, /([+-])?(?:(?:0x([\da-fA-F]+))|(?:0([0-7]+))|(\d+))/, function (num, sign, hex, oct, dec) { - return hex ? parseInt(num, 16) : oct ? parseInt(num, 8) : parseInt(num, 10); - }); - break; - case 'n': + return hex ? parseInt(num, 16) : oct ? parseInt(num, 8) : parseInt(num, 10) + }) + break + case 'n': // Number of characters processed so far - retArr[digit !== undefined ? digit : retArr.length - 1] = j; - break; + retArr[digit !== undefined ? digit : retArr.length - 1] = j + break // DOCUMENTED UNDER SPRINTF - case 'c': + case 'c': // Get character; suppresses skipping over whitespace! (but shouldn't be whitespace in format anyways, so no difference here) // Non-greedy match - j = _addNext(j, new RegExp('.{1,' + (width || 1) + '}')); - break; - case 'D': + j = _addNext(j, new RegExp('.{1,' + (width || 1) + '}')) + break + case 'D': // sscanf documented decimal number; equivalent of 'd'; - case 'd': + case 'd': // Optionally signed decimal integer - j = _addNext(j, /([+-])?(?:0*)(\d+)/, function(num, sign, dec) { + j = _addNext(j, /([+-])?(?:0*)(\d+)/, function (num, sign, dec) { // Ignores initial zeroes, unlike %i and parseInt() - var decInt = parseInt((sign || '') + dec, 10); - if (decInt < 0) { + var decInt = parseInt((sign || '') + dec, 10) + if (decInt < 0) { // PHP also won't allow less than -2147483648 // integer overflow with negative - return decInt < -2147483648 ? -2147483648 : decInt; + return decInt < -2147483648 ? -2147483648 : decInt } else { // PHP also won't allow greater than -2147483647 - return decInt < 2147483647 ? decInt : 2147483647; + return decInt < 2147483647 ? decInt : 2147483647 } - }); - break; - case 'f': + }) + break + case 'f': // Although sscanf doesn't support locales, this is used instead of '%F'; seems to be same as %e - case 'E': + case 'E': // These don't discriminate here as both allow exponential float of either case - case 'e': - j = _addNext(j, /([+-])?(?:0*)(\d*\.?\d*(?:[eE]?\d+)?)/, function(num, sign, dec) { - if (dec === '.') { - return null; + case 'e': + j = _addNext(j, /([+-])?(?:0*)(\d*\.?\d*(?:[eE]?\d+)?)/, function (num, sign, dec) { + if (dec === '.') { + return null } // Ignores initial zeroes, unlike %i and parseFloat() - return parseFloat((sign || '') + dec); - }); - break; - case 'u': + return parseFloat((sign || '') + dec) + }) + break + case 'u': // unsigned decimal integer // We won't deal with integer overflows due to signs - j = _addNext(j, /([+-])?(?:0*)(\d+)/, function(num, sign, dec) { + j = _addNext(j, /([+-])?(?:0*)(\d+)/, function (num, sign, dec) { // Ignores initial zeroes, unlike %i and parseInt() - var decInt = parseInt(dec, 10); - if (sign === '-') { + var decInt = parseInt(dec, 10) + if (sign === '-') { // PHP also won't allow greater than 4294967295 // integer overflow with negative - return 4294967296 - decInt; + return 4294967296 - decInt } else { - return decInt < 4294967295 ? decInt : 4294967295; + return decInt < 4294967295 ? decInt : 4294967295 } - }); - break; - case 'o': + }) + break + case 'o': // Octal integer // Fix: add overflows as above? - j = _addNext(j, /([+-])?(?:0([0-7]+))/, function(num, sign, oct) { - return parseInt(num, 8); - }); - break; - case 's': + j = _addNext(j, /([+-])?(?:0([0-7]+))/, function (num, sign, oct) { + return parseInt(num, 8) + }) + break + case 's': // Greedy match - j = _addNext(j, /\S+/); - break; - case 'X': + j = _addNext(j, /\S+/) + break + case 'X': // Same as 'x'? - case 'x': + case 'x': // Fix: add overflows as above? // Initial 0x not necessary here - j = _addNext(j, /([+-])?(?:(?:0x)?([\da-fA-F]+))/, function(num, sign, hex) { - return parseInt(num, 16); - }); - break; - case '': + j = _addNext(j, /([+-])?(?:(?:0x)?([\da-fA-F]+))/, function (num, sign, hex) { + return parseInt(num, 16) + }) + break + case '': // If no character left in expression - throw 'Missing character after percent mark in sscanf() format argument'; - default: - throw 'Unrecognized character after percent mark in sscanf() format argument'; + throw 'Missing character after percent mark in sscanf() format argument' + default: + throw 'Unrecognized character after percent mark in sscanf() format argument' } } catch (e) { if (e === 'No match in string') { // Allow us to exit - return _setExtraConversionSpecs(i + 2); + return _setExtraConversionSpecs(i + 2) } // Calculate skipping beyond initial percent too - }++i; + }++i } else if (format.charAt(i) !== str.charAt(j)) { // Fix: Double-check i whitespace ignored in string and/or formats - _NWS.lastIndex = 0; + _NWS.lastIndex = 0 if ((_NWS) .test(str.charAt(j)) || str.charAt(j) === '') { // Whitespace doesn't need to be an exact match) - return _setExtraConversionSpecs(i + 1); + return _setExtraConversionSpecs(i + 1) } else { // Adjust strings when encounter non-matching whitespace, so they align in future checks above // Ok to replace with j++;? - str = str.slice(0, j) + str.slice(j + 1); - i--; + str = str.slice(0, j) + str.slice(j + 1) + i-- } } else { - j++; + j++ } } // POST-PROCESSING - return _finish(); -} \ No newline at end of file + return _finish() +} diff --git a/functions/strings/str_getcsv.js b/functions/strings/str_getcsv.js index 1376b9991f..735e42f727 100644 --- a/functions/strings/str_getcsv.js +++ b/functions/strings/str_getcsv.js @@ -1,4 +1,4 @@ -function str_getcsv(input, delimiter, enclosure, escape) { +function str_getcsv (input, delimiter, enclosure, escape) { // discuss at: http://phpjs.org/functions/str_getcsv/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: str_getcsv('"abc","def","ghi"'); @@ -22,39 +22,39 @@ function str_getcsv(input, delimiter, enclosure, escape) { Should also test newlines within */ - var i, inpLen, output = []; - var backwards = function(str) { + var i, inpLen, output = [] + var backwards = function (str) { // We need to go backwards to simulate negative look-behind (don't split on - //an escaped enclosure even if followed by the delimiter and another enclosure mark) + // an escaped enclosure even if followed by the delimiter and another enclosure mark) return str.split('') .reverse() - .join(''); - }; - var pq = function(str) { + .join('') + } + var pq = function (str) { // preg_quote() return String(str) - .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<\>\|\:])/g, '\\$1'); - }; + .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<\>\|\:])/g, '\\$1') + } - delimiter = delimiter || ','; - enclosure = enclosure || '"'; - escape = escape || '\\'; - var pqEnc = pq(enclosure); - var pqEsc = pq(escape); + delimiter = delimiter || ',' + enclosure = enclosure || '"' + escape = escape || '\\' + var pqEnc = pq(enclosure) + var pqEsc = pq(escape) input = input.replace(new RegExp('^\\s*' + pqEnc), '') - .replace(new RegExp(pqEnc + '\\s*$'), ''); + .replace(new RegExp(pqEnc + '\\s*$'), '') // PHP behavior may differ by including whitespace even outside of the enclosure input = backwards(input) .split(new RegExp(pqEnc + '\\s*' + pq(delimiter) + '\\s*' + pqEnc + '(?!' + pqEsc + ')', 'g')) - .reverse(); + .reverse() for (i = 0, inpLen = input.length; i < inpLen; i++) { output.push(backwards(input[i]) - .replace(new RegExp(pqEsc + pqEnc, 'g'), enclosure)); + .replace(new RegExp(pqEsc + pqEnc, 'g'), enclosure)) } - return output; -} \ No newline at end of file + return output +} diff --git a/functions/strings/str_ireplace.js b/functions/strings/str_ireplace.js index 13b89379b9..748f185d06 100644 --- a/functions/strings/str_ireplace.js +++ b/functions/strings/str_ireplace.js @@ -1,4 +1,4 @@ -function str_ireplace(search, replace, subject, count) { +function str_ireplace (search, replace, subject, count) { // discuss at: http://phpjs.org/functions/str_ireplace/ // original by: Glen Arason (http://CanadianDomainRegistry.ca) // note: Case-insensitive version of str_replace() @@ -25,73 +25,73 @@ function str_ireplace(search, replace, subject, count) { oi = '', ofjl = '', os = subject, - osa = Object.prototype.toString.call(os) === '[object Array]'; + osa = Object.prototype.toString.call(os) === '[object Array]' if (typeof (search) === 'object') { - temp = search; - search = new Array(); + temp = search + search = new Array() for (i = 0; i < temp.length; i += 1) { - search[i] = temp[i].toLowerCase(); + search[i] = temp[i].toLowerCase() } } else { - search = search.toLowerCase(); + search = search.toLowerCase() } if (typeof (subject) === 'object') { - temp = subject; - subject = new Array(); + temp = subject + subject = new Array() for (i = 0; i < temp.length; i += 1) { - subject[i] = temp[i].toLowerCase(); + subject[i] = temp[i].toLowerCase() } } else { - subject = subject.toLowerCase(); + subject = subject.toLowerCase() } if (typeof (search) === 'object' && typeof (replace) === 'string') { - temp = replace; - replace = new Array(); + temp = replace + replace = new Array() for (i = 0; i < search.length; i += 1) { - replace[i] = temp; + replace[i] = temp } } - temp = ''; - f = [].concat(search); - r = [].concat(replace); - ra = Object.prototype.toString.call(r) === '[object Array]'; - s = subject; - sa = Object.prototype.toString.call(s) === '[object Array]'; - s = [].concat(s); - os = [].concat(os); + temp = '' + f = [].concat(search) + r = [].concat(replace) + ra = Object.prototype.toString.call(r) === '[object Array]' + s = subject + sa = Object.prototype.toString.call(s) === '[object Array]' + s = [].concat(s) + os = [].concat(os) if (count) { - this.window[count] = 0; + this.window[count] = 0 } for (i = 0, sl = s.length; i < sl; i++) { if (s[i] === '') { - continue; + continue } for (j = 0, fl = f.length; j < fl; j++) { - temp = s[i] + ''; - repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; + temp = s[i] + '' + repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0] s[i] = (temp) .split(f[j]) - .join(repl); - otemp = os[i] + ''; - oi = temp.indexOf(f[j]); - ofjl = f[j].length; + .join(repl) + otemp = os[i] + '' + oi = temp.indexOf(f[j]) + ofjl = f[j].length if (oi >= 0) { os[i] = (otemp) .split(otemp.substr(oi, ofjl)) - .join(repl); + .join(repl) } if (count) { this.window[count] += ((temp.split(f[j])) - .length - 1); + .length - 1) } } } - return osa ? os : os[0]; -} \ No newline at end of file + return osa ? os : os[0] +} diff --git a/functions/strings/str_pad.js b/functions/strings/str_pad.js index 2c6751ed84..ec20786973 100644 --- a/functions/strings/str_pad.js +++ b/functions/strings/str_pad.js @@ -1,4 +1,4 @@ -function str_pad(input, pad_length, pad_string, pad_type) { +function str_pad (input, pad_length, pad_string, pad_type) { // discuss at: http://phpjs.org/functions/str_pad/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Michael White (http://getsprink.com) @@ -10,37 +10,37 @@ function str_pad(input, pad_length, pad_string, pad_type) { // returns 2: '------Kevin van Zonneveld-----' var half = '', - pad_to_go; + pad_to_go - var str_pad_repeater = function(s, len) { + var str_pad_repeater = function (s, len) { var collect = '', - i; + i while (collect.length < len) { - collect += s; + collect += s } - collect = collect.substr(0, len); + collect = collect.substr(0, len) - return collect; - }; + return collect + } - input += ''; - pad_string = pad_string !== undefined ? pad_string : ' '; + input += '' + pad_string = pad_string !== undefined ? pad_string : ' ' if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') { - pad_type = 'STR_PAD_RIGHT'; + pad_type = 'STR_PAD_RIGHT' } if ((pad_to_go = pad_length - input.length) > 0) { if (pad_type === 'STR_PAD_LEFT') { - input = str_pad_repeater(pad_string, pad_to_go) + input; + input = str_pad_repeater(pad_string, pad_to_go) + input } else if (pad_type === 'STR_PAD_RIGHT') { - input = input + str_pad_repeater(pad_string, pad_to_go); + input = input + str_pad_repeater(pad_string, pad_to_go) } else if (pad_type === 'STR_PAD_BOTH') { - half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2)); - input = half + input + half; - input = input.substr(0, pad_length); + half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2)) + input = half + input + half + input = input.substr(0, pad_length) } } - return input; -} \ No newline at end of file + return input +} diff --git a/functions/strings/str_repeat.js b/functions/strings/str_repeat.js index 932e30ab3e..d3985f0330 100644 --- a/functions/strings/str_repeat.js +++ b/functions/strings/str_repeat.js @@ -1,4 +1,4 @@ -function str_repeat(input, multiplier) { +function str_repeat (input, multiplier) { // discuss at: http://phpjs.org/functions/str_repeat/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) @@ -6,17 +6,17 @@ function str_repeat(input, multiplier) { // example 1: str_repeat('-=', 10); // returns 1: '-=-=-=-=-=-=-=-=-=-=' - var y = ''; + var y = '' while (true) { if (multiplier & 1) { - y += input; + y += input } - multiplier >>= 1; + multiplier >>= 1 if (multiplier) { - input += input; + input += input } else { - break; + break } } - return y; -} \ No newline at end of file + return y +} diff --git a/functions/strings/str_replace.js b/functions/strings/str_replace.js index 4c02c2572f..45281d3ddc 100644 --- a/functions/strings/str_replace.js +++ b/functions/strings/str_replace.js @@ -1,4 +1,4 @@ -function str_replace(search, replace, subject, count) { +function str_replace (search, replace, subject, count) { // discuss at: http://phpjs.org/functions/str_replace/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Gabriel Paderni @@ -38,39 +38,39 @@ function str_replace(search, replace, subject, count) { r = [].concat(replace), s = subject, ra = Object.prototype.toString.call(r) === '[object Array]', - sa = Object.prototype.toString.call(s) === '[object Array]'; - s = [].concat(s); + sa = Object.prototype.toString.call(s) === '[object Array]' + s = [].concat(s) if (typeof (search) === 'object' && typeof (replace) === 'string') { - temp = replace; - replace = new Array(); + temp = replace + replace = new Array() for (i = 0; i < search.length; i += 1) { - replace[i] = temp; + replace[i] = temp } - temp = ''; - r = [].concat(replace); - ra = Object.prototype.toString.call(r) === '[object Array]'; + temp = '' + r = [].concat(replace) + ra = Object.prototype.toString.call(r) === '[object Array]' } if (count) { - this.window[count] = 0; + this.window[count] = 0 } for (i = 0, sl = s.length; i < sl; i++) { if (s[i] === '') { - continue; + continue } for (j = 0, fl = f.length; j < fl; j++) { - temp = s[i] + ''; - repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; + temp = s[i] + '' + repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0] s[i] = (temp) .split(f[j]) - .join(repl); + .join(repl) if (count) { this.window[count] += ((temp.split(f[j])) - .length - 1); + .length - 1) } } } - return sa ? s : s[0]; -} \ No newline at end of file + return sa ? s : s[0] +} diff --git a/functions/strings/str_rot13.js b/functions/strings/str_rot13.js index 2b6f30dfe7..eaa58b4c80 100644 --- a/functions/strings/str_rot13.js +++ b/functions/strings/str_rot13.js @@ -1,4 +1,4 @@ -function str_rot13(str) { +function str_rot13 (str) { // discuss at: http://phpjs.org/functions/str_rot13/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // improved by: Ates Goral (http://magnetiq.com) @@ -12,7 +12,7 @@ function str_rot13(str) { // returns 3: '33' return (str + '') - .replace(/[a-z]/gi, function(s) { - return String.fromCharCode(s.charCodeAt(0) + (s.toLowerCase() < 'n' ? 13 : -13)); - }); -} \ No newline at end of file + .replace(/[a-z]/gi, function (s) { + return String.fromCharCode(s.charCodeAt(0) + (s.toLowerCase() < 'n' ? 13 : -13)) + }) +} diff --git a/functions/strings/str_shuffle.js b/functions/strings/str_shuffle.js index f3506ed85e..e1c4adf0f8 100644 --- a/functions/strings/str_shuffle.js +++ b/functions/strings/str_shuffle.js @@ -1,4 +1,4 @@ -function str_shuffle(str) { +function str_shuffle (str) { // discuss at: http://phpjs.org/functions/str_shuffle/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: shuffled = str_shuffle("abcdef"); @@ -6,24 +6,24 @@ function str_shuffle(str) { // returns 1: 6 if (arguments.length === 0) { - throw 'Wrong parameter count for str_shuffle()'; + throw 'Wrong parameter count for str_shuffle()' } if (str == null) { - return ''; + return '' } - str += ''; + str += '' var newStr = '', - rand, i = str.length; + rand, i = str.length while (i) { - rand = Math.floor(Math.random() * i); - newStr += str.charAt(rand); - str = str.substring(0, rand) + str.substr(rand + 1); - i--; + rand = Math.floor(Math.random() * i) + newStr += str.charAt(rand) + str = str.substring(0, rand) + str.substr(rand + 1) + i-- } - return newStr; -} \ No newline at end of file + return newStr +} diff --git a/functions/strings/str_split.js b/functions/strings/str_split.js index 9dfb6827bc..651c1c469a 100644 --- a/functions/strings/str_split.js +++ b/functions/strings/str_split.js @@ -1,4 +1,4 @@ -function str_split(string, split_length) { +function str_split (string, split_length) { // discuss at: http://phpjs.org/functions/str_split/ // original by: Martijn Wieringa // improved by: Brett Zamir (http://brett-zamir.me) @@ -10,18 +10,18 @@ function str_split(string, split_length) { // returns 1: ['Hel', 'lo ', 'Fri', 'end'] if (split_length === null) { - split_length = 1; + split_length = 1 } if (string === null || split_length < 1) { - return false; + return false } - string += ''; + string += '' var chunks = [], pos = 0, - len = string.length; + len = string.length while (pos < len) { - chunks.push(string.slice(pos, pos += split_length)); + chunks.push(string.slice(pos, pos += split_length)) } - return chunks; -} \ No newline at end of file + return chunks +} diff --git a/functions/strings/str_word_count.js b/functions/strings/str_word_count.js index 661374eb7f..9f86090d1c 100644 --- a/functions/strings/str_word_count.js +++ b/functions/strings/str_word_count.js @@ -1,4 +1,4 @@ -function str_word_count(str, format, charlist) { +function str_word_count (str, format, charlist) { // discuss at: http://phpjs.org/functions/str_word_count/ // original by: Ole Vrijenhoek // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -27,86 +27,86 @@ function str_word_count(str, format, charlist) { assoc = {}, aC = 0, reg = '', - match = false; + match = false // BEGIN STATIC - var _preg_quote = function(str) { + var _preg_quote = function (str) { return (str + '') - .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1'); - }; - _getWholeChar = function(str, i) { + .replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1') + } + _getWholeChar = function (str, i) { // Use for rare cases of non-BMP characters - var code = str.charCodeAt(i); + var code = str.charCodeAt(i) if (code < 0xD800 || code > 0xDFFF) { - return str.charAt(i); + return str.charAt(i) } if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters) if (str.length <= (i + 1)) { - throw 'High surrogate without following low surrogate'; + throw 'High surrogate without following low surrogate' } - var next = str.charCodeAt(i + 1); + var next = str.charCodeAt(i + 1) if (0xDC00 > next || next > 0xDFFF) { - throw 'High surrogate without following low surrogate'; + throw 'High surrogate without following low surrogate' } - return str.charAt(i) + str.charAt(i + 1); + return str.charAt(i) + str.charAt(i + 1) } // Low surrogate (0xDC00 <= code && code <= 0xDFFF) if (i === 0) { - throw 'Low surrogate without preceding high surrogate'; + throw 'Low surrogate without preceding high surrogate' } - var prev = str.charCodeAt(i - 1); + var prev = str.charCodeAt(i - 1) if (0xD800 > prev || prev > 0xDBFF) { // (could change last hex to 0xDB7F to treat high private surrogates as single characters) - throw 'Low surrogate without preceding high surrogate'; + throw 'Low surrogate without preceding high surrogate' } // We can pass over low surrogates now as the second component in a pair which we have already processed - return false; - }; + return false + } // END STATIC if (cl) { - reg = '^(' + _preg_quote(_getWholeChar(charlist, 0)); + reg = '^(' + _preg_quote(_getWholeChar(charlist, 0)) for (i = 1; i < cl; i++) { if ((chr = _getWholeChar(charlist, i)) === false) { - continue; + continue } - reg += '|' + _preg_quote(chr); + reg += '|' + _preg_quote(chr) } - reg += ')$'; - reg = new RegExp(reg); + reg += ')$' + reg = new RegExp(reg) } for (i = 0; i < len; i++) { if ((c = _getWholeChar(str, i)) === false) { - continue; + continue } match = this.ctype_alpha(c) || (reg && c.search(reg) !== -1) || ((i !== 0 && i !== len - 1) && c === '-') || // No hyphen at beginning or end unless allowed in charlist (or locale) // No apostrophe at beginning unless allowed in charlist (or locale) - (i !== 0 && c === "'"); + (i !== 0 && c === "'") if (match) { if (tmpStr === '' && format === 2) { - aC = i; + aC = i } - tmpStr = tmpStr + c; + tmpStr = tmpStr + c } if (i === len - 1 || !match && tmpStr !== '') { if (format !== 2) { - wArr[wArr.length] = tmpStr; + wArr[wArr.length] = tmpStr } else { - assoc[aC] = tmpStr; + assoc[aC] = tmpStr } - tmpStr = ''; - wC++; + tmpStr = '' + wC++ } } if (!format) { - return wC; + return wC } else if (format === 1) { - return wArr; + return wArr } else if (format === 2) { - return assoc; + return assoc } - throw 'You have supplied an incorrect format'; -} \ No newline at end of file + throw 'You have supplied an incorrect format' +} diff --git a/functions/strings/strcasecmp.js b/functions/strings/strcasecmp.js index cca7658b7f..283672afe5 100644 --- a/functions/strings/strcasecmp.js +++ b/functions/strings/strcasecmp.js @@ -1,4 +1,4 @@ -function strcasecmp(f_string1, f_string2) { +function strcasecmp (f_string1, f_string2) { // discuss at: http://phpjs.org/functions/strcasecmp/ // original by: Martijn Wieringa // bugfixed by: Onno Marsman @@ -6,15 +6,15 @@ function strcasecmp(f_string1, f_string2) { // returns 1: 0 var string1 = (f_string1 + '') - .toLowerCase(); + .toLowerCase() var string2 = (f_string2 + '') - .toLowerCase(); + .toLowerCase() if (string1 > string2) { - return 1; + return 1 } else if (string1 == string2) { - return 0; + return 0 } - return -1; -} \ No newline at end of file + return -1 +} diff --git a/functions/strings/strchr.js b/functions/strings/strchr.js index 9cdff7dd74..da68b7ddb4 100644 --- a/functions/strings/strchr.js +++ b/functions/strings/strchr.js @@ -1,4 +1,4 @@ -function strchr(haystack, needle, bool) { +function strchr (haystack, needle, bool) { // discuss at: http://phpjs.org/functions/strchr/ // original by: Philip Peterson // depends on: strstr @@ -7,5 +7,5 @@ function strchr(haystack, needle, bool) { // example 2: strchr('Kevin van Zonneveld', 'van', true); // returns 2: 'Kevin ' - return this.strstr(haystack, needle, bool); -} \ No newline at end of file + return this.strstr(haystack, needle, bool) +} diff --git a/functions/strings/strcmp.js b/functions/strings/strcmp.js index 3889562283..4d06dfb00b 100644 --- a/functions/strings/strcmp.js +++ b/functions/strings/strcmp.js @@ -1,4 +1,4 @@ -function strcmp(str1, str2) { +function strcmp (str1, str2) { // discuss at: http://phpjs.org/functions/strcmp/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // input by: Steve Hilder @@ -9,5 +9,5 @@ function strcmp(str1, str2) { // example 2: strcmp( 'owald', 'waldo' ); // returns 2: -1 - return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1)); -} \ No newline at end of file + return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1)) +} diff --git a/functions/strings/strcoll.js b/functions/strings/strcoll.js index 8d72fd0358..9aa7abdcf0 100644 --- a/functions/strings/strcoll.js +++ b/functions/strings/strcoll.js @@ -1,4 +1,4 @@ -function strcoll(str1, str2) { +function strcoll (str1, str2) { // discuss at: http://phpjs.org/functions/strcoll/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Brett Zamir (http://brett-zamir.me) @@ -6,9 +6,9 @@ function strcoll(str1, str2) { // example 1: strcoll('a', 'b'); // returns 1: -1 - this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place - var cmp = this.php_js.locales[this.php_js.localeCategories.LC_COLLATE].LC_COLLATE; + this.setlocale('LC_ALL', 0) // ensure setup of localization variables takes place + var cmp = this.php_js.locales[this.php_js.localeCategories.LC_COLLATE].LC_COLLATE // We don't use this as it doesn't allow us to control it via setlocale() // return str1.localeCompare(str2); - return cmp(str1, str2); -} \ No newline at end of file + return cmp(str1, str2) +} diff --git a/functions/strings/strcspn.js b/functions/strings/strcspn.js index 95ae512f3d..3a73a266b8 100644 --- a/functions/strings/strcspn.js +++ b/functions/strings/strcspn.js @@ -1,4 +1,4 @@ -function strcspn(str, mask, start, length) { +function strcspn (str, mask, start, length) { // discuss at: http://phpjs.org/functions/strcspn/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: strcspn('abcdefg123', '1234567890'); @@ -6,16 +6,16 @@ function strcspn(str, mask, start, length) { // example 2: strcspn('123abc', '1234567890'); // returns 2: 3 - start = start ? start : 0; - var count = (length && ((start + length) < str.length)) ? start + length : str.length; + start = start ? start : 0 + var count = (length && ((start + length) < str.length)) ? start + length : str.length strct: for (var i = start, lgth = 0; i < count; i++) { for (var j = 0; j < mask.length; j++) { if (str.charAt(i) .indexOf(mask[j]) !== -1) { - continue strct; + continue strct } - }++lgth; + }++lgth } - return lgth; -} \ No newline at end of file + return lgth +} diff --git a/functions/strings/strip_tags.js b/functions/strings/strip_tags.js index 9cee03b5b3..8a5ce57e74 100644 --- a/functions/strings/strip_tags.js +++ b/functions/strings/strip_tags.js @@ -1,4 +1,4 @@ -function strip_tags(input, allowed) { +function strip_tags (input, allowed) { // discuss at: http://phpjs.org/functions/strip_tags/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Luke Godfrey @@ -35,11 +35,11 @@ function strip_tags(input, allowed) { allowed = (((allowed || '') + '') .toLowerCase() .match(/<[a-z][a-z0-9]*>/g) || []) - .join(''); // making sure the allowed arg is a string containing only tags in lowercase () + .join('') // making sure the allowed arg is a string containing only tags in lowercase () var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, - commentsAndPhpTags = /|<\?(?:php)?[\s\S]*?\?>/gi; + commentsAndPhpTags = /|<\?(?:php)?[\s\S]*?\?>/gi return input.replace(commentsAndPhpTags, '') - .replace(tags, function($0, $1) { - return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; - }); -} \ No newline at end of file + .replace(tags, function ($0, $1) { + return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '' + }) +} diff --git a/functions/strings/stripos.js b/functions/strings/stripos.js index 8f3d62e46a..23ed475abe 100644 --- a/functions/strings/stripos.js +++ b/functions/strings/stripos.js @@ -1,4 +1,4 @@ -function stripos(f_haystack, f_needle, f_offset) { +function stripos (f_haystack, f_needle, f_offset) { // discuss at: http://phpjs.org/functions/stripos/ // original by: Martijn Wieringa // revised by: Onno Marsman @@ -6,13 +6,13 @@ function stripos(f_haystack, f_needle, f_offset) { // returns 1: 0 var haystack = (f_haystack + '') - .toLowerCase(); + .toLowerCase() var needle = (f_needle + '') - .toLowerCase(); - var index = 0; + .toLowerCase() + var index = 0 if ((index = haystack.indexOf(needle, f_offset)) !== -1) { - return index; + return index } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/strings/stripslashes.js b/functions/strings/stripslashes.js index 6aaf011c78..054f13341d 100644 --- a/functions/strings/stripslashes.js +++ b/functions/strings/stripslashes.js @@ -1,4 +1,4 @@ -function stripslashes(str) { +function stripslashes (str) { // discuss at: http://phpjs.org/functions/stripslashes/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Ates Goral (http://magnetiq.com) @@ -16,16 +16,16 @@ function stripslashes(str) { // returns 2: "Kevin\'s code" return (str + '') - .replace(/\\(.?)/g, function(s, n1) { + .replace(/\\(.?)/g, function (s, n1) { switch (n1) { - case '\\': - return '\\'; - case '0': - return '\u0000'; - case '': - return ''; - default: - return n1; + case '\\': + return '\\' + case '0': + return '\u0000' + case '': + return '' + default: + return n1 } - }); -} \ No newline at end of file + }) +} diff --git a/functions/strings/stristr.js b/functions/strings/stristr.js index 8fcf397217..38d14538ef 100644 --- a/functions/strings/stristr.js +++ b/functions/strings/stristr.js @@ -1,4 +1,4 @@ -function stristr(haystack, needle, bool) { +function stristr (haystack, needle, bool) { // discuss at: http://phpjs.org/functions/stristr/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -7,19 +7,19 @@ function stristr(haystack, needle, bool) { // example 2: stristr('Kevin van Zonneveld', 'VAN', true); // returns 2: 'Kevin ' - var pos = 0; + var pos = 0 - haystack += ''; + haystack += '' pos = haystack.toLowerCase() .indexOf((needle + '') - .toLowerCase()); + .toLowerCase()) if (pos == -1) { - return false; + return false } else { if (bool) { - return haystack.substr(0, pos); + return haystack.substr(0, pos) } else { - return haystack.slice(pos); + return haystack.slice(pos) } } -} \ No newline at end of file +} diff --git a/functions/strings/strlen.js b/functions/strings/strlen.js index 687941b939..7df207edc1 100644 --- a/functions/strings/strlen.js +++ b/functions/strings/strlen.js @@ -1,4 +1,4 @@ -function strlen(string) { +function strlen (string) { // discuss at: http://phpjs.org/functions/strlen/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Sakimori @@ -15,51 +15,51 @@ function strlen(string) { // example 2: strlen('A\ud87e\udc04Z'); // returns 2: 3 - var str = string + ''; + var str = string + '' var i = 0, chr = '', - lgth = 0; + lgth = 0 if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] || this.php_js.ini[ 'unicode.semantics'].local_value.toLowerCase() !== 'on') { - return string.length; + return string.length } - var getWholeChar = function(str, i) { - var code = str.charCodeAt(i); + var getWholeChar = function (str, i) { + var code = str.charCodeAt(i) var next = '', - prev = ''; + prev = '' if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters) if (str.length <= (i + 1)) { - throw 'High surrogate without following low surrogate'; + throw 'High surrogate without following low surrogate' } - next = str.charCodeAt(i + 1); + next = str.charCodeAt(i + 1) if (0xDC00 > next || next > 0xDFFF) { - throw 'High surrogate without following low surrogate'; + throw 'High surrogate without following low surrogate' } - return str.charAt(i) + str.charAt(i + 1); + return str.charAt(i) + str.charAt(i + 1) } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate if (i === 0) { - throw 'Low surrogate without preceding high surrogate'; + throw 'Low surrogate without preceding high surrogate' } - prev = str.charCodeAt(i - 1); + prev = str.charCodeAt(i - 1) if (0xD800 > prev || prev > 0xDBFF) { - //(could change last hex to 0xDB7F to treat high private surrogates as single characters) - throw 'Low surrogate without preceding high surrogate'; + // (could change last hex to 0xDB7F to treat high private surrogates as single characters) + throw 'Low surrogate without preceding high surrogate' } // We can pass over low surrogates now as the second component in a pair which we have already processed - return false; + return false } - return str.charAt(i); - }; + return str.charAt(i) + } for (i = 0, lgth = 0; i < str.length; i++) { if ((chr = getWholeChar(str, i)) === false) { - continue; + continue } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part - lgth++; + lgth++ } - return lgth; -} \ No newline at end of file + return lgth +} diff --git a/functions/strings/strnatcasecmp.js b/functions/strings/strnatcasecmp.js index ff99971ee9..e925a193c9 100644 --- a/functions/strings/strnatcasecmp.js +++ b/functions/strings/strnatcasecmp.js @@ -1,4 +1,4 @@ -function strnatcasecmp(str1, str2) { +function strnatcasecmp (str1, str2) { // discuss at: http://phpjs.org/functions/strnatcasecmp/ // original by: Martin Pool // reimplemented by: Pierre-Luc Paour @@ -13,115 +13,115 @@ function strnatcasecmp(str1, str2) { // returns 1: -1 var a = (str1 + '') - .toLowerCase(); + .toLowerCase() var b = (str2 + '') - .toLowerCase(); + .toLowerCase() - var isWhitespaceChar = function(a) { - return a.charCodeAt(0) <= 32; - }; + var isWhitespaceChar = function (a) { + return a.charCodeAt(0) <= 32 + } - var isDigitChar = function(a) { - var charCode = a.charCodeAt(0); - return (charCode >= 48 && charCode <= 57); - }; + var isDigitChar = function (a) { + var charCode = a.charCodeAt(0) + return (charCode >= 48 && charCode <= 57) + } - var compareRight = function(a, b) { - var bias = 0; - var ia = 0; - var ib = 0; + var compareRight = function (a, b) { + var bias = 0 + var ia = 0 + var ib = 0 - var ca; - var cb; + var ca + var cb // The longest run of digits wins. That aside, the greatest // value wins, but we can't know that it will until we've scanned // both numbers to know that they have the same magnitude, so we // remember it in BIAS. for (var cnt = 0; true; ia++, ib++) { - ca = a.charAt(ia); - cb = b.charAt(ib); + ca = a.charAt(ia) + cb = b.charAt(ib) if (!isDigitChar(ca) && !isDigitChar(cb)) { - return bias; + return bias } else if (!isDigitChar(ca)) { - return -1; + return -1 } else if (!isDigitChar(cb)) { - return 1; + return 1 } else if (ca < cb) { if (bias === 0) { - bias = -1; + bias = -1 } } else if (ca > cb) { if (bias === 0) { - bias = 1; + bias = 1 } } else if (ca === '0' && cb === '0') { - return bias; + return bias } } - }; + } var ia = 0, - ib = 0; + ib = 0 var nza = 0, - nzb = 0; - var ca, cb; - var result; + nzb = 0 + var ca, cb + var result while (true) { // only count the number of zeroes leading the last number compared - nza = nzb = 0; + nza = nzb = 0 - ca = a.charAt(ia); - cb = b.charAt(ib); + ca = a.charAt(ia) + cb = b.charAt(ib) // skip over leading spaces or zeros while (isWhitespaceChar(ca) || ca === '0') { if (ca === '0') { - nza++; + nza++ } else { // only count consecutive zeroes - nza = 0; + nza = 0 } - ca = a.charAt(++ia); + ca = a.charAt(++ia) } while (isWhitespaceChar(cb) || cb === '0') { if (cb === '0') { - nzb++; + nzb++ } else { // only count consecutive zeroes - nzb = 0; + nzb = 0 } - cb = b.charAt(++ib); + cb = b.charAt(++ib) } // process run of digits if (isDigitChar(ca) && isDigitChar(cb)) { if ((result = compareRight(a.substring(ia), b.substring(ib))) !== 0) { - return result; + return result } } if (ca === '0' && cb === '0') { // The strings compare the same. Perhaps the caller // will want to call strcmp to break the tie. - return nza - nzb; + return nza - nzb } if (ca < cb) { - return -1; + return -1 } else if (ca > cb) { - return +1; + return +1 } // prevent possible infinite loop if (ia >= a.length && ib >= b.length) return 0; ++ia; - ++ib; + ++ib } -} \ No newline at end of file +} diff --git a/functions/strings/strnatcmp.js b/functions/strings/strnatcmp.js index d3e005980b..84b600ba34 100644 --- a/functions/strings/strnatcmp.js +++ b/functions/strings/strnatcmp.js @@ -1,4 +1,4 @@ -function strnatcmp(f_string1, f_string2, f_version) { +function strnatcmp (f_string1, f_string2, f_version) { // discuss at: http://phpjs.org/functions/strnatcmp/ // original by: Martijn Wieringa // improved by: Michael White (http://getsprink.com) @@ -17,109 +17,109 @@ function strnatcmp(f_string1, f_string2, f_version) { // example 5: strnatcmp('Version 12.15', 'Version 12.9', true); // returns 5: 6 - var i = 0; + var i = 0 if (f_version == undefined) { - f_version = false; + f_version = false } - var __strnatcmp_split = function(f_string) { - var result = []; - var buffer = ''; - var chr = ''; + var __strnatcmp_split = function (f_string) { + var result = [] + var buffer = '' + var chr = '' var i = 0, - f_stringl = 0; + f_stringl = 0 - var text = true; + var text = true - f_stringl = f_string.length; + f_stringl = f_string.length for (i = 0; i < f_stringl; i++) { - chr = f_string.substring(i, i + 1); + chr = f_string.substring(i, i + 1) if (chr.match(/\d/)) { if (text) { if (buffer.length > 0) { - result[result.length] = buffer; - buffer = ''; + result[result.length] = buffer + buffer = '' } - text = false; + text = false } - buffer += chr; + buffer += chr } else if ((text == false) && (chr === '.') && (i < (f_string.length - 1)) && (f_string.substring(i + 1, i + 2) .match(/\d/))) { - result[result.length] = buffer; - buffer = ''; + result[result.length] = buffer + buffer = '' } else { if (text == false) { if (buffer.length > 0) { - result[result.length] = parseInt(buffer, 10); - buffer = ''; + result[result.length] = parseInt(buffer, 10) + buffer = '' } - text = true; + text = true } - buffer += chr; + buffer += chr } } if (buffer.length > 0) { if (text) { - result[result.length] = buffer; + result[result.length] = buffer } else { - result[result.length] = parseInt(buffer, 10); + result[result.length] = parseInt(buffer, 10) } } - return result; - }; + return result + } - var array1 = __strnatcmp_split(f_string1 + ''); - var array2 = __strnatcmp_split(f_string2 + ''); + var array1 = __strnatcmp_split(f_string1 + '') + var array2 = __strnatcmp_split(f_string2 + '') - var len = array1.length; - var text = true; + var len = array1.length + var text = true - var result = -1; - var r = 0; + var result = -1 + var r = 0 if (len > array2.length) { - len = array2.length; - result = 1; + len = array2.length + result = 1 } for (i = 0; i < len; i++) { if (isNaN(array1[i])) { if (isNaN(array2[i])) { - text = true; + text = true if ((r = this.strcmp(array1[i], array2[i])) != 0) { - return r; + return r } } else if (text) { - return 1; + return 1 } else { - return -1; + return -1 } } else if (isNaN(array2[i])) { if (text) { - return -1; + return -1 } else { - return 1; + return 1 } } else { if (text || f_version) { if ((r = (array1[i] - array2[i])) != 0) { - return r; + return r } } else { if ((r = this.strcmp(array1[i].toString(), array2[i].toString())) != 0) { - return r; + return r } } - text = false; + text = false } } - return result; -} \ No newline at end of file + return result +} diff --git a/functions/strings/strncasecmp.js b/functions/strings/strncasecmp.js index 285774c01c..19d2d029eb 100644 --- a/functions/strings/strncasecmp.js +++ b/functions/strings/strncasecmp.js @@ -1,4 +1,4 @@ -function strncasecmp(argStr1, argStr2, len) { +function strncasecmp (argStr1, argStr2, len) { // discuss at: http://phpjs.org/functions/strncasecmp/ // original by: Saulo Vallory // input by: Nate @@ -15,40 +15,40 @@ function strncasecmp(argStr1, argStr2, len) { // example 5: strncasecmp('Version 12.15', 'Version 12.9', 20); // returns 5: -8 - var diff, i = 0; + var diff, i = 0 var str1 = (argStr1 + '') .toLowerCase() - .substr(0, len); + .substr(0, len) var str2 = (argStr2 + '') .toLowerCase() - .substr(0, len); + .substr(0, len) if (str1.length !== str2.length) { if (str1.length < str2.length) { - len = str1.length; + len = str1.length if (str2.substr(0, str1.length) == str1) { // return the difference of chars - return str1.length - str2.length; + return str1.length - str2.length } } else { - len = str2.length; + len = str2.length // str1 is longer than str2 if (str1.substr(0, str2.length) == str2) { // return the difference of chars - return str1.length - str2.length; + return str1.length - str2.length } } } else { // Avoids trying to get a char that does not exist - len = str1.length; + len = str1.length } for (diff = 0, i = 0; i < len; i++) { - diff = str1.charCodeAt(i) - str2.charCodeAt(i); + diff = str1.charCodeAt(i) - str2.charCodeAt(i) if (diff !== 0) { - return diff; + return diff } } - return 0; -} \ No newline at end of file + return 0 +} diff --git a/functions/strings/strncmp.js b/functions/strings/strncmp.js index 3ef81e5b4b..3ffc1cb79f 100644 --- a/functions/strings/strncmp.js +++ b/functions/strings/strncmp.js @@ -1,4 +1,4 @@ -function strncmp(str1, str2, lgth) { +function strncmp (str1, str2, lgth) { // discuss at: http://phpjs.org/functions/strncmp/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // input by: Steve Hilder @@ -11,9 +11,9 @@ function strncmp(str1, str2, lgth) { // returns 2: -1 var s1 = (str1 + '') - .substr(0, lgth); + .substr(0, lgth) var s2 = (str2 + '') - .substr(0, lgth); + .substr(0, lgth) - return ((s1 == s2) ? 0 : ((s1 > s2) ? 1 : -1)); -} \ No newline at end of file + return ((s1 == s2) ? 0 : ((s1 > s2) ? 1 : -1)) +} diff --git a/functions/strings/strpbrk.js b/functions/strings/strpbrk.js index 704a492de4..2ce0cd8f64 100644 --- a/functions/strings/strpbrk.js +++ b/functions/strings/strpbrk.js @@ -1,4 +1,4 @@ -function strpbrk(haystack, char_list) { +function strpbrk (haystack, char_list) { // discuss at: http://phpjs.org/functions/strpbrk/ // original by: Alfonso Jimenez (http://www.alfonsojimenez.com) // bugfixed by: Onno Marsman @@ -9,8 +9,8 @@ function strpbrk(haystack, char_list) { for (var i = 0, len = haystack.length; i < len; ++i) { if (char_list.indexOf(haystack.charAt(i)) >= 0) { - return haystack.slice(i); + return haystack.slice(i) } } - return false; -} \ No newline at end of file + return false +} diff --git a/functions/strings/strpos.js b/functions/strings/strpos.js index 4965692e3e..b499de959c 100644 --- a/functions/strings/strpos.js +++ b/functions/strings/strpos.js @@ -1,4 +1,4 @@ -function strpos(haystack, needle, offset) { +function strpos (haystack, needle, offset) { // discuss at: http://phpjs.org/functions/strpos/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Onno Marsman @@ -8,6 +8,6 @@ function strpos(haystack, needle, offset) { // returns 1: 14 var i = (haystack + '') - .indexOf(needle, (offset || 0)); - return i === -1 ? false : i; -} \ No newline at end of file + .indexOf(needle, (offset || 0)) + return i === -1 ? false : i +} diff --git a/functions/strings/strrchr.js b/functions/strings/strrchr.js index 5ecc8a5243..522dd08b10 100644 --- a/functions/strings/strrchr.js +++ b/functions/strings/strrchr.js @@ -1,4 +1,4 @@ -function strrchr(haystack, needle) { +function strrchr (haystack, needle) { // discuss at: http://phpjs.org/functions/strrchr/ // original by: Brett Zamir (http://brett-zamir.me) // input by: Jason Wong (http://carrot.org/) @@ -6,16 +6,16 @@ function strrchr(haystack, needle) { // example 1: strrchr("Line 1\nLine 2\nLine 3", 10).substr(1) // returns 1: 'Line 3' - var pos = 0; + var pos = 0 if (typeof needle !== 'string') { - needle = String.fromCharCode(parseInt(needle, 10)); + needle = String.fromCharCode(parseInt(needle, 10)) } - needle = needle.charAt(0); - pos = haystack.lastIndexOf(needle); + needle = needle.charAt(0) + pos = haystack.lastIndexOf(needle) if (pos === -1) { - return false; + return false } - return haystack.substr(pos); -} \ No newline at end of file + return haystack.substr(pos) +} diff --git a/functions/strings/strrev.js b/functions/strings/strrev.js index 4a8dc9f5ce..42b89f475a 100644 --- a/functions/strings/strrev.js +++ b/functions/strings/strrev.js @@ -1,4 +1,4 @@ -function strrev(string) { +function strrev (string) { // discuss at: http://phpjs.org/functions/strrev/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -10,7 +10,7 @@ function strrev(string) { // example 3: strrev('A\uD87E\uDC04Z') === 'Z\uD87E\uDC04A'; // surrogates // returns 3: true - string = string + ''; + string = string + '' // Performance will be enhanced with the next two lines of code commented // out if you don't care about combining characters @@ -20,10 +20,10 @@ function strrev(string) { // We also add the low surrogate range at the beginning here so it will be // maintained with its preceding high surrogate var grapheme_extend = - /(.)([\uDC00-\uDFFF\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065E\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C82\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D02\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F90-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B6-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAA\u1C24-\u1C37\u1DC0-\u1DE6\u1DFE\u1DFF\u20D0-\u20F0\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA67C\uA67D\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA926-\uA92D\uA947-\uA953\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uFB1E\uFE00-\uFE0F\uFE20-\uFE26]+)/g; + /(.)([\uDC00-\uDFFF\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065E\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C82\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D02\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F90-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B6-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAA\u1C24-\u1C37\u1DC0-\u1DE6\u1DFE\u1DFF\u20D0-\u20F0\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA67C\uA67D\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA926-\uA92D\uA947-\uA953\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uFB1E\uFE00-\uFE0F\uFE20-\uFE26]+)/g // Temporarily reverse - string = string.replace(grapheme_extend, '$2$1'); + string = string.replace(grapheme_extend, '$2$1') return string.split('') .reverse() - .join(''); -} \ No newline at end of file + .join('') +} diff --git a/functions/strings/strripos.js b/functions/strings/strripos.js index 31a0fc8c7a..c9f0e866b2 100644 --- a/functions/strings/strripos.js +++ b/functions/strings/strripos.js @@ -1,4 +1,4 @@ -function strripos(haystack, needle, offset) { +function strripos (haystack, needle, offset) { // discuss at: http://phpjs.org/functions/strripos/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -8,22 +8,22 @@ function strripos(haystack, needle, offset) { // returns 1: 16 haystack = (haystack + '') - .toLowerCase(); + .toLowerCase() needle = (needle + '') - .toLowerCase(); + .toLowerCase() - var i = -1; + var i = -1 if (offset) { i = (haystack + '') .slice(offset) - .lastIndexOf(needle); // strrpos' offset indicates starting point of range till end, + .lastIndexOf(needle) // strrpos' offset indicates starting point of range till end, // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning if (i !== -1) { - i += offset; + i += offset } } else { i = (haystack + '') - .lastIndexOf(needle); + .lastIndexOf(needle) } - return i >= 0 ? i : false; -} \ No newline at end of file + return i >= 0 ? i : false +} diff --git a/functions/strings/strrpos.js b/functions/strings/strrpos.js index 77dbd80c62..a781758df2 100644 --- a/functions/strings/strrpos.js +++ b/functions/strings/strrpos.js @@ -1,4 +1,4 @@ -function strrpos(haystack, needle, offset) { +function strrpos (haystack, needle, offset) { // discuss at: http://phpjs.org/functions/strrpos/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -13,18 +13,18 @@ function strrpos(haystack, needle, offset) { // example 4: strrpos('baa', 'a', 2); // returns 4: 2 - var i = -1; + var i = -1 if (offset) { i = (haystack + '') .slice(offset) - .lastIndexOf(needle); // strrpos' offset indicates starting point of range till end, + .lastIndexOf(needle) // strrpos' offset indicates starting point of range till end, // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning if (i !== -1) { - i += offset; + i += offset } } else { i = (haystack + '') - .lastIndexOf(needle); + .lastIndexOf(needle) } - return i >= 0 ? i : false; -} \ No newline at end of file + return i >= 0 ? i : false +} diff --git a/functions/strings/strspn.js b/functions/strings/strspn.js index cb6fcd89db..c634d5b06b 100644 --- a/functions/strings/strspn.js +++ b/functions/strings/strspn.js @@ -1,4 +1,4 @@ -function strspn(str1, str2, start, lgth) { +function strspn (str1, str2, start, lgth) { // discuss at: http://phpjs.org/functions/strspn/ // original by: Valentina De Rosa // improved by: Brett Zamir (http://brett-zamir.me) @@ -7,30 +7,30 @@ function strspn(str1, str2, start, lgth) { // example 2: strspn('foo', 'o', 1, 2); // returns 2: 2 - var found; - var stri; - var strj; - var j = 0; - var i = 0; + var found + var stri + var strj + var j = 0 + var i = 0 - start = start ? (start < 0 ? (str1.length + start) : start) : 0; - lgth = lgth ? ((lgth < 0) ? (str1.length + lgth - start) : lgth) : str1.length - start; - str1 = str1.substr(start, lgth); + start = start ? (start < 0 ? (str1.length + start) : start) : 0 + lgth = lgth ? ((lgth < 0) ? (str1.length + lgth - start) : lgth) : str1.length - start + str1 = str1.substr(start, lgth) for (i = 0; i < str1.length; i++) { - found = 0; - stri = str1.substring(i, i + 1); + found = 0 + stri = str1.substring(i, i + 1) for (j = 0; j <= str2.length; j++) { - strj = str2.substring(j, j + 1); + strj = str2.substring(j, j + 1) if (stri == strj) { - found = 1; - break; + found = 1 + break } } if (found != 1) { - return i; + return i } } - return i; -} \ No newline at end of file + return i +} diff --git a/functions/strings/strstr.js b/functions/strings/strstr.js index fba2eca31f..925cd361b9 100644 --- a/functions/strings/strstr.js +++ b/functions/strings/strstr.js @@ -1,4 +1,4 @@ -function strstr(haystack, needle, bool) { +function strstr (haystack, needle, bool) { // discuss at: http://phpjs.org/functions/strstr/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -12,17 +12,17 @@ function strstr(haystack, needle, bool) { // example 4: strstr('name@example.com', '@', true); // returns 4: 'name' - var pos = 0; + var pos = 0 - haystack += ''; - pos = haystack.indexOf(needle); + haystack += '' + pos = haystack.indexOf(needle) if (pos == -1) { - return false; + return false } else { if (bool) { - return haystack.substr(0, pos); + return haystack.substr(0, pos) } else { - return haystack.slice(pos); + return haystack.slice(pos) } } -} \ No newline at end of file +} diff --git a/functions/strings/strtok.js b/functions/strings/strtok.js index 64c14d4b48..6be8dfe2dc 100644 --- a/functions/strings/strtok.js +++ b/functions/strings/strtok.js @@ -1,4 +1,4 @@ -function strtok(str, tokens) { +function strtok (str, tokens) { // discuss at: http://phpjs.org/functions/strtok/ // original by: Brett Zamir (http://brett-zamir.me) // note: Use tab and newline as tokenizing characters as well @@ -9,23 +9,23 @@ function strtok(str, tokens) { // example 1: $b // returns 1: "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n" - this.php_js = this.php_js || {}; + this.php_js = this.php_js || {} // END REDUNDANT if (tokens === undefined) { - tokens = str; - str = this.php_js.strtokleftOver; + tokens = str + str = this.php_js.strtokleftOver } if (str.length === 0) { - return false; + return false } if (tokens.indexOf(str.charAt(0)) !== -1) { - return this.strtok(str.substr(1), tokens); + return this.strtok(str.substr(1), tokens) } for (var i = 0; i < str.length; i++) { if (tokens.indexOf(str.charAt(i)) !== -1) { - break; + break } } - this.php_js.strtokleftOver = str.substr(i + 1); - return str.substring(0, i); -} \ No newline at end of file + this.php_js.strtokleftOver = str.substr(i + 1) + return str.substring(0, i) +} diff --git a/functions/strings/strtolower.js b/functions/strings/strtolower.js index 92e22664a1..86c131f39b 100644 --- a/functions/strings/strtolower.js +++ b/functions/strings/strtolower.js @@ -1,4 +1,4 @@ -function strtolower(str) { +function strtolower (str) { // discuss at: http://phpjs.org/functions/strtolower/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Onno Marsman @@ -6,5 +6,5 @@ function strtolower(str) { // returns 1: 'kevin van zonneveld' return (str + '') - .toLowerCase(); -} \ No newline at end of file + .toLowerCase() +} diff --git a/functions/strings/strtoupper.js b/functions/strings/strtoupper.js index ea4d1b9a3c..3ec912b847 100644 --- a/functions/strings/strtoupper.js +++ b/functions/strings/strtoupper.js @@ -1,4 +1,4 @@ -function strtoupper(str) { +function strtoupper (str) { // discuss at: http://phpjs.org/functions/strtoupper/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: Onno Marsman @@ -6,5 +6,5 @@ function strtoupper(str) { // returns 1: 'KEVIN VAN ZONNEVELD' return (str + '') - .toUpperCase(); -} \ No newline at end of file + .toUpperCase() +} diff --git a/functions/strings/strtr.js b/functions/strings/strtr.js index 9d53ae5c08..be12809cb1 100644 --- a/functions/strings/strtr.js +++ b/functions/strings/strtr.js @@ -1,4 +1,4 @@ -function strtr(str, from, to) { +function strtr (str, from, to) { // discuss at: http://phpjs.org/functions/strtr/ // original by: Brett Zamir (http://brett-zamir.me) // input by: uestla @@ -33,63 +33,63 @@ function strtr(str, from, to) { tmpStrictForIn = false, fromTypeStr = '', toTypeStr = '', - istr = ''; - var tmpFrom = []; - var tmpTo = []; - var ret = ''; - var match = false; + istr = '' + var tmpFrom = [] + var tmpTo = [] + var ret = '' + var match = false // Received replace_pairs? // Convert to normal from->to chars if (typeof from === 'object') { // Not thread-safe; temporarily set to true - tmpStrictForIn = this.ini_set('phpjs.strictForIn', false); - from = this.krsort(from); - this.ini_set('phpjs.strictForIn', tmpStrictForIn); + tmpStrictForIn = this.ini_set('phpjs.strictForIn', false) + from = this.krsort(from) + this.ini_set('phpjs.strictForIn', tmpStrictForIn) for (fr in from) { if (from.hasOwnProperty(fr)) { - tmpFrom.push(fr); - tmpTo.push(from[fr]); + tmpFrom.push(fr) + tmpTo.push(from[fr]) } } - from = tmpFrom; - to = tmpTo; + from = tmpFrom + to = tmpTo } // Walk through subject and replace chars when needed - lenStr = str.length; - lenFrom = from.length; - fromTypeStr = typeof from === 'string'; - toTypeStr = typeof to === 'string'; + lenStr = str.length + lenFrom = from.length + fromTypeStr = typeof from === 'string' + toTypeStr = typeof to === 'string' for (i = 0; i < lenStr; i++) { - match = false; + match = false if (fromTypeStr) { - istr = str.charAt(i); + istr = str.charAt(i) for (j = 0; j < lenFrom; j++) { if (istr == from.charAt(j)) { - match = true; - break; + match = true + break } } } else { for (j = 0; j < lenFrom; j++) { if (str.substr(i, from[j].length) == from[j]) { - match = true; + match = true // Fast forward - i = (i + from[j].length) - 1; - break; + i = (i + from[j].length) - 1 + break } } } if (match) { - ret += toTypeStr ? to.charAt(j) : to[j]; + ret += toTypeStr ? to.charAt(j) : to[j] } else { - ret += str.charAt(i); + ret += str.charAt(i) } } - return ret; -} \ No newline at end of file + return ret +} diff --git a/functions/strings/substr.js b/functions/strings/substr.js index 5b1ef4a556..da0617df25 100644 --- a/functions/strings/substr.js +++ b/functions/strings/substr.js @@ -1,4 +1,4 @@ -function substr(str, start, len) { +function substr (str, start, len) { // discuss at: http://phpjs.org/functions/substr/ // version: 909.322 // original by: Martijn Wieringa @@ -32,87 +32,87 @@ function substr(str, start, len) { es = 0, el = 0, se = 0, - ret = ''; - str += ''; - var end = str.length; + ret = '' + str += '' + var end = str.length // BEGIN REDUNDANT - this.php_js = this.php_js || {}; - this.php_js.ini = this.php_js.ini || {}; + this.php_js = this.php_js || {} + this.php_js.ini = this.php_js.ini || {} // END REDUNDANT switch ((this.php_js.ini['unicode.semantics'] && this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) { - case 'on': + case 'on': // Full-blown Unicode including non-Basic-Multilingual-Plane characters // strlen() - for (i = 0; i < str.length; i++) { - if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) { - allBMP = false; - break; + for (i = 0; i < str.length; i++) { + if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) { + allBMP = false + break + } } - } - if (!allBMP) { - if (start < 0) { + if (!allBMP) { + if (start < 0) { for (i = end - 1, es = (start += end); i >= es; i--) { if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) { - start--; - es--; + start-- + es-- } } } else { - var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g while ((surrogatePairs.exec(str)) != null) { - var li = surrogatePairs.lastIndex; + var li = surrogatePairs.lastIndex if (li - 2 < start) { - start++; + start++ } else { - break; + break } } } - if (start >= end || start < 0) { - return false; + if (start >= end || start < 0) { + return false } - if (len < 0) { + if (len < 0) { for (i = end - 1, el = (end += len); i >= el; i--) { if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) { - end--; - el--; + end-- + el-- } } if (start > end) { - return false; + return false } - return str.slice(start, end); + return str.slice(start, end) } else { - se = start + len; + se = start + len for (i = start; i < se; i++) { - ret += str.charAt(i); + ret += str.charAt(i) if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) { // Go one further, since one of the "characters" is part of a surrogate pair - se++; + se++ } } - return ret; + return ret + } + break } - break; - } // Fall-through - case 'off': + case 'off': // assumes there are no non-BMP characters; // if there may be such characters, then it is best to turn it on (critical in true XHTML/XML) - default: - if (start < 0) { - start += end; - } - end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start); + default: + if (start < 0) { + start += end + } + end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start) // PHP returns false if start does not fall within the string. // PHP returns false if the calculated end comes before the calculated start. // PHP returns an empty string if start and end are the same. // Otherwise, PHP returns the portion of the string from start to end. - return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end); + return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end) } // Please Netbeans - return undefined; -} \ No newline at end of file + return undefined +} diff --git a/functions/strings/substr_compare.js b/functions/strings/substr_compare.js index 253bb984a0..86b533b91a 100644 --- a/functions/strings/substr_compare.js +++ b/functions/strings/substr_compare.js @@ -1,4 +1,4 @@ -function substr_compare(main_str, str, offset, length, case_insensitivity) { +function substr_compare (main_str, str, offset, length, case_insensitivity) { // discuss at: http://phpjs.org/functions/substr_compare/ // original by: Brett Zamir (http://brett-zamir.me) // original by: strcasecmp, strcmp @@ -6,32 +6,32 @@ function substr_compare(main_str, str, offset, length, case_insensitivity) { // returns 1: 0 if (!offset && offset !== 0) { - throw 'Missing offset for substr_compare()'; + throw 'Missing offset for substr_compare()' } if (offset < 0) { - offset = main_str.length + offset; + offset = main_str.length + offset } if (length && length > (main_str.length - offset)) { - return false; + return false } - length = length || main_str.length - offset; + length = length || main_str.length - offset - main_str = main_str.substr(offset, length); + main_str = main_str.substr(offset, length) // Should only compare up to the desired length - str = str.substr(0, length); + str = str.substr(0, length) if (case_insensitivity) { // Works as strcasecmp main_str = (main_str + '') - .toLowerCase(); + .toLowerCase() str = (str + '') - .toLowerCase(); + .toLowerCase() if (main_str == str) { - return 0; + return 0 } - return (main_str > str) ? 1 : -1; + return (main_str > str) ? 1 : -1 } // Works as strcmp - return ((main_str == str) ? 0 : ((main_str > str) ? 1 : -1)); -} \ No newline at end of file + return ((main_str == str) ? 0 : ((main_str > str) ? 1 : -1)) +} diff --git a/functions/strings/substr_count.js b/functions/strings/substr_count.js index 6f07bc0c03..135595cb94 100644 --- a/functions/strings/substr_count.js +++ b/functions/strings/substr_count.js @@ -1,4 +1,4 @@ -function substr_count(haystack, needle, offset, length) { +function substr_count (haystack, needle, offset, length) { // discuss at: http://phpjs.org/functions/substr_count/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -11,27 +11,27 @@ function substr_count(haystack, needle, offset, length) { // example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10); // returns 3: false - var cnt = 0; + var cnt = 0 - haystack += ''; - needle += ''; + haystack += '' + needle += '' if (isNaN(offset)) { - offset = 0; + offset = 0 } if (isNaN(length)) { - length = 0; + length = 0 } if (needle.length == 0) { - return false; + return false } - offset--; + offset-- while ((offset = haystack.indexOf(needle, offset + 1)) != -1) { if (length > 0 && (offset + needle.length) > length) { - return false; + return false } - cnt++; + cnt++ } - return cnt; -} \ No newline at end of file + return cnt +} diff --git a/functions/strings/substr_replace.js b/functions/strings/substr_replace.js index 2cdb6ccfd0..3e1f3b789d 100644 --- a/functions/strings/substr_replace.js +++ b/functions/strings/substr_replace.js @@ -1,4 +1,4 @@ -function substr_replace(str, replace, start, length) { +function substr_replace (str, replace, start, length) { // discuss at: http://phpjs.org/functions/substr_replace/ // original by: Brett Zamir (http://brett-zamir.me) // example 1: substr_replace('ABCDEFGH:/MNRPQR/', 'bob', 0); @@ -16,12 +16,12 @@ function substr_replace(str, replace, start, length) { // returns 6: 'ABCDEFGH://' if (start < 0) { // start position in str - start = start + str.length; + start = start + str.length } - length = length !== undefined ? length : str.length; + length = length !== undefined ? length : str.length if (length < 0) { - length = length + str.length - start; + length = length + str.length - start } - return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length); -} \ No newline at end of file + return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length) +} diff --git a/functions/strings/trim.js b/functions/strings/trim.js index d3cb7bcad9..4edc0b4229 100644 --- a/functions/strings/trim.js +++ b/functions/strings/trim.js @@ -1,4 +1,4 @@ -function trim(str, charlist) { +function trim (str, charlist) { // discuss at: http://phpjs.org/functions/trim/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: mdsjack (http://www.mdsjack.bo.it) @@ -17,34 +17,34 @@ function trim(str, charlist) { // returns 3: 6 var whitespace, l = 0, - i = 0; - str += ''; + i = 0 + str += '' if (!charlist) { // default list whitespace = - ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000'; + ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000' } else { // preg_quote custom list - charlist += ''; - whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1'); + charlist += '' + whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1') } - l = str.length; + l = str.length for (i = 0; i < l; i++) { if (whitespace.indexOf(str.charAt(i)) === -1) { - str = str.substring(i); - break; + str = str.substring(i) + break } } - l = str.length; + l = str.length for (i = l - 1; i >= 0; i--) { if (whitespace.indexOf(str.charAt(i)) === -1) { - str = str.substring(0, i + 1); - break; + str = str.substring(0, i + 1) + break } } - return whitespace.indexOf(str.charAt(0)) === -1 ? str : ''; -} \ No newline at end of file + return whitespace.indexOf(str.charAt(0)) === -1 ? str : '' +} diff --git a/functions/strings/ucfirst.js b/functions/strings/ucfirst.js index 07e3bc854b..151fe26950 100644 --- a/functions/strings/ucfirst.js +++ b/functions/strings/ucfirst.js @@ -1,4 +1,4 @@ -function ucfirst(str) { +function ucfirst (str) { // discuss at: http://phpjs.org/functions/ucfirst/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Onno Marsman @@ -6,8 +6,8 @@ function ucfirst(str) { // example 1: ucfirst('kevin van zonneveld'); // returns 1: 'Kevin van zonneveld' - str += ''; + str += '' var f = str.charAt(0) - .toUpperCase(); - return f + str.substr(1); -} \ No newline at end of file + .toUpperCase() + return f + str.substr(1) +} diff --git a/functions/strings/ucwords.js b/functions/strings/ucwords.js index 778c11b164..134816b0f5 100644 --- a/functions/strings/ucwords.js +++ b/functions/strings/ucwords.js @@ -1,4 +1,4 @@ -function ucwords(str) { +function ucwords (str) { // discuss at: http://phpjs.org/functions/ucwords/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // improved by: Waldo Malqui Silva (http://waldo.malqui.info) @@ -12,7 +12,7 @@ function ucwords(str) { // returns 2: 'HELLO WORLD' return (str + '') - .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) { - return $1.toUpperCase(); - }); -} \ No newline at end of file + .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) { + return $1.toUpperCase() + }) +} diff --git a/functions/strings/vprintf.js b/functions/strings/vprintf.js index 9630abd961..5a202547ac 100644 --- a/functions/strings/vprintf.js +++ b/functions/strings/vprintf.js @@ -1,4 +1,4 @@ -function vprintf(format, args) { +function vprintf (format, args) { // discuss at: http://phpjs.org/functions/vprintf/ // original by: Ash Searle (http://hexmen.com/blog/) // improved by: Michael White (http://getsprink.com) @@ -7,23 +7,23 @@ function vprintf(format, args) { // example 1: vprintf("%01.2f", 123.1); // returns 1: 6 - var body, elmt; + var body, elmt var ret = '', - d = this.window.document; + d = this.window.document // .shift() does not work to get first item in bodies - var HTMLNS = 'http://www.w3.org/1999/xhtml'; + var HTMLNS = 'http://www.w3.org/1999/xhtml' body = d.getElementsByTagNameNS ? (d.getElementsByTagNameNS(HTMLNS, 'body')[0] ? d.getElementsByTagNameNS(HTMLNS, - 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0]; + 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0] if (!body) { - return false; + return false } - ret = this.sprintf.apply(this, [format].concat(args)); + ret = this.sprintf.apply(this, [format].concat(args)) - elmt = d.createTextNode(ret); - body.appendChild(elmt); + elmt = d.createTextNode(ret) + body.appendChild(elmt) - return ret.length; -} \ No newline at end of file + return ret.length +} diff --git a/functions/strings/vsprintf.js b/functions/strings/vsprintf.js index 281ec92ac7..3fb1803701 100644 --- a/functions/strings/vsprintf.js +++ b/functions/strings/vsprintf.js @@ -1,9 +1,9 @@ -function vsprintf(format, args) { +function vsprintf (format, args) { // discuss at: http://phpjs.org/functions/vsprintf/ // original by: ejsanders // depends on: sprintf // example 1: vsprintf('%04d-%02d-%02d', [1988, 8, 1]); // returns 1: '1988-08-01' - return this.sprintf.apply(this, [format].concat(args)); -} \ No newline at end of file + return this.sprintf.apply(this, [format].concat(args)) +} diff --git a/functions/strings/wordwrap.js b/functions/strings/wordwrap.js index 9008559f0b..af66887dc1 100644 --- a/functions/strings/wordwrap.js +++ b/functions/strings/wordwrap.js @@ -1,4 +1,4 @@ -function wordwrap(str, int_width, str_break, cut) { +function wordwrap (str, int_width, str_break, cut) { // discuss at: http://phpjs.org/functions/wordwrap/ // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // improved by: Nick Callen @@ -14,16 +14,16 @@ function wordwrap(str, int_width, str_break, cut) { // example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); // returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.' - var m = ((arguments.length >= 2) ? arguments[1] : 75); - var b = ((arguments.length >= 3) ? arguments[2] : '\n'); - var c = ((arguments.length >= 4) ? arguments[3] : false); + var m = ((arguments.length >= 2) ? arguments[1] : 75) + var b = ((arguments.length >= 3) ? arguments[2] : '\n') + var c = ((arguments.length >= 4) ? arguments[3] : false) - var i, j, l, s, r; + var i, j, l, s, r - str += ''; + str += '' if (m < 1) { - return str; + return str } for (i = -1, l = (r = str.split(/\r\n|\n|\r/)) @@ -33,9 +33,9 @@ function wordwrap(str, int_width, str_break, cut) { j = c == 2 || (j = s.slice(0, m + 1) .match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice( m) - .match(/^\S*/))[0].length; + .match(/^\S*/))[0].length } } - return r.join('\n'); -} \ No newline at end of file + return r.join('\n') +} diff --git a/functions/url/base64_decode.js b/functions/url/base64_decode.js index 15346acaef..bd3b7230ac 100644 --- a/functions/url/base64_decode.js +++ b/functions/url/base64_decode.js @@ -1,4 +1,4 @@ -function base64_decode(data) { +function base64_decode (data) { // discuss at: http://phpjs.org/functions/base64_decode/ // original by: Tyler Akins (http://rumkin.com) // improved by: Thunder.m @@ -16,41 +16,41 @@ function base64_decode(data) { // example 3: base64_decode('4pyTIMOgIGxhIG1vZGU='); // returns 3: '✓ à la mode' - var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = '', - tmp_arr = []; + tmp_arr = [] if (!data) { - return data; + return data } - data += ''; + data += '' do { // unpack four hexets into three octets using index points in b64 - h1 = b64.indexOf(data.charAt(i++)); - h2 = b64.indexOf(data.charAt(i++)); - h3 = b64.indexOf(data.charAt(i++)); - h4 = b64.indexOf(data.charAt(i++)); + h1 = b64.indexOf(data.charAt(i++)) + h2 = b64.indexOf(data.charAt(i++)) + h3 = b64.indexOf(data.charAt(i++)) + h4 = b64.indexOf(data.charAt(i++)) - bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; + bits = h1 << 18 | h2 << 12 | h3 << 6 | h4 - o1 = bits >> 16 & 0xff; - o2 = bits >> 8 & 0xff; - o3 = bits & 0xff; + o1 = bits >> 16 & 0xff + o2 = bits >> 8 & 0xff + o3 = bits & 0xff if (h3 == 64) { - tmp_arr[ac++] = String.fromCharCode(o1); + tmp_arr[ac++] = String.fromCharCode(o1) } else if (h4 == 64) { - tmp_arr[ac++] = String.fromCharCode(o1, o2); + tmp_arr[ac++] = String.fromCharCode(o1, o2) } else { - tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); + tmp_arr[ac++] = String.fromCharCode(o1, o2, o3) } - } while (i < data.length); + } while (i < data.length) - dec = tmp_arr.join(''); + dec = tmp_arr.join('') - return decodeURIComponent(escape(dec.replace(/\0+$/, ''))); -} \ No newline at end of file + return decodeURIComponent(escape(dec.replace(/\0+$/, ''))) +} diff --git a/functions/url/base64_encode.js b/functions/url/base64_encode.js index 5a71a3c5d4..5775a37c42 100644 --- a/functions/url/base64_encode.js +++ b/functions/url/base64_encode.js @@ -1,4 +1,4 @@ -function base64_encode(data) { +function base64_encode (data) { // discuss at: http://phpjs.org/functions/base64_encode/ // original by: Tyler Akins (http://rumkin.com) // improved by: Bayron Guevara @@ -14,38 +14,38 @@ function base64_encode(data) { // example 3: base64_encode('✓ à la mode'); // returns 3: '4pyTIMOgIGxhIG1vZGU=' - var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = '', - tmp_arr = []; + tmp_arr = [] if (!data) { - return data; + return data } - data = unescape(encodeURIComponent(data)); + data = unescape(encodeURIComponent(data)) do { // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); + o1 = data.charCodeAt(i++) + o2 = data.charCodeAt(i++) + o3 = data.charCodeAt(i++) - bits = o1 << 16 | o2 << 8 | o3; + bits = o1 << 16 | o2 << 8 | o3 - h1 = bits >> 18 & 0x3f; - h2 = bits >> 12 & 0x3f; - h3 = bits >> 6 & 0x3f; - h4 = bits & 0x3f; + h1 = bits >> 18 & 0x3f + h2 = bits >> 12 & 0x3f + h3 = bits >> 6 & 0x3f + h4 = bits & 0x3f // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); + tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4) + } while (i < data.length) - enc = tmp_arr.join(''); + enc = tmp_arr.join('') - var r = data.length % 3; + var r = data.length % 3 - return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); -} \ No newline at end of file + return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3) +} diff --git a/functions/url/get_headers.js b/functions/url/get_headers.js index b09dea4be0..e9742c905b 100644 --- a/functions/url/get_headers.js +++ b/functions/url/get_headers.js @@ -1,4 +1,4 @@ -function get_headers(url, format) { +function get_headers (url, format) { // discuss at: http://phpjs.org/functions/get_headers/ // original by: Paulo Freitas // bugfixed by: Brett Zamir (http://brett-zamir.me) @@ -9,36 +9,36 @@ function get_headers(url, format) { // example 1: get_headers('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm')[0]; // returns 1: 'Date: Wed, 13 May 2009 23:53:11 GMT' - var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); + var req = this.window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest() if (!req) { - throw new Error('XMLHttpRequest not supported'); + throw new Error('XMLHttpRequest not supported') } - var tmp, headers, pair, i, j = 0; - ß; - req.open('HEAD', url, false); - req.send(null); + var tmp, headers, pair, i, j = 0 + ß + req.open('HEAD', url, false) + req.send(null) if (req.readyState < 3) { - return false; + return false } - tmp = req.getAllResponseHeaders(); - tmp = tmp.split('\n'); - tmp = this.array_filter(tmp, function(value) { - return value.substring(1) !== ''; - }); - headers = format ? {} : []; + tmp = req.getAllResponseHeaders() + tmp = tmp.split('\n') + tmp = this.array_filter(tmp, function (value) { + return value.substring(1) !== '' + }) + headers = format ? {} : [] for (var i in tmp) { if (format) { - pair = tmp[i].split(':'); + pair = tmp[i].split(':') headers[pair.splice(0, 1)] = pair.join(':') - .substring(1); + .substring(1) } else { - headers[j++] = tmp[i]; + headers[j++] = tmp[i] } } - return headers; -} \ No newline at end of file + return headers +} diff --git a/functions/url/get_meta_tags.js b/functions/url/get_meta_tags.js index b79a636d5a..15393edb70 100644 --- a/functions/url/get_meta_tags.js +++ b/functions/url/get_meta_tags.js @@ -1,4 +1,4 @@ -function get_meta_tags(file) { +function get_meta_tags (file) { // discuss at: http://phpjs.org/functions/get_meta_tags/ // original by: Brett Zamir (http://brett-zamir.me) // note: This function uses XmlHttpRequest and cannot retrieve resource from different domain. @@ -8,34 +8,34 @@ function get_meta_tags(file) { // example 1: get_meta_tags('http://kevin.vanzonneveld.net/pj_test_supportfile_2.htm'); // returns 1: {description: 'a php manual', author: 'name', keywords: 'php documentation', 'geo_position': '49.33;-86.59'} - var fulltxt = ''; + var fulltxt = '' if (false) { // Use this for testing instead of the line above: fulltxt = '' + '' + '' + '' + - ''; + '' } else { fulltxt = this.file_get_contents(file) - .match(/^[\s\S]*<\/head>/i); // We have to disallow some character, so we choose a Unicode non-character + .match(/^[\s\S]*<\/head>/i) // We have to disallow some character, so we choose a Unicode non-character } - var patt = /]*?>/gim; - var patt1 = /]*?>/gim + var patt1 = / 0) { - cur_depth++; + cur_depth++ } - var base_pad = repeat_char(pad_val * cur_depth, pad_char); - var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char); - var str = ''; + var base_pad = repeat_char(pad_val * cur_depth, pad_char) + var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char) + var str = '' if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') { - str += 'Array\n' + base_pad + '(\n'; + str += 'Array\n' + base_pad + '(\n' for (var key in obj) { if (Object.prototype.toString.call(obj[key]) === '[object Array]') { - str += thick_pad + '[' + key + '] => ' + formatArray(obj[key], cur_depth + 1, pad_val, pad_char); + str += thick_pad + '[' + key + '] => ' + formatArray(obj[key], cur_depth + 1, pad_val, pad_char) } else { - str += thick_pad + '[' + key + '] => ' + obj[key] + '\n'; + str += thick_pad + '[' + key + '] => ' + obj[key] + '\n' } } - str += base_pad + ')\n'; + str += base_pad + ')\n' } else if (obj === null || obj === undefined) { - str = ''; + str = '' } else { // for our "resource" class - str = obj.toString(); + str = obj.toString() } - return str; - }; + return str + } - output = formatArray(array, 0, pad_val, pad_char); + output = formatArray(array, 0, pad_val, pad_char) if (return_val !== true) { if (d.body) { - this.echo(output); + this.echo(output) } else { try { // We're in XUL, so appending as plain text won't work; trigger an error out of XUL - d = XULDocument; - this.echo('
' + output + '
'); + d = XULDocument + this.echo('
' + output + '
') } catch (e) { // Outputting as plain text may work in some plain XML - this.echo(output); + this.echo(output) } } - return true; + return true } - return output; -} \ No newline at end of file + return output +} diff --git a/functions/var/serialize.js b/functions/var/serialize.js index 07c75ac1b3..d6354f111b 100644 --- a/functions/var/serialize.js +++ b/functions/var/serialize.js @@ -1,4 +1,4 @@ -function serialize(mixed_value) { +function serialize (mixed_value) { // discuss at: http://phpjs.org/functions/serialize/ // original by: Arpad Ray (mailto:arpad@php.net) // improved by: Dino @@ -24,67 +24,67 @@ function serialize(mixed_value) { ktype = '', vals = '', count = 0, - _utf8Size = function(str) { + _utf8Size = function (str) { var size = 0, i = 0, l = str.length, - code = ''; + code = '' for (i = 0; i < l; i++) { - code = str.charCodeAt(i); + code = str.charCodeAt(i) if (code < 0x0080) { - size += 1; + size += 1 } else if (code < 0x0800) { - size += 2; + size += 2 } else { - size += 3; + size += 3 } } - return size; + return size }, - _getType = function(inp) { - var match, key, cons, types, type = typeof inp; + _getType = function (inp) { + var match, key, cons, types, type = typeof inp if (type === 'object' && !inp) { - return 'null'; + return 'null' } if (type === 'object') { if (!inp.constructor) { - return 'object'; + return 'object' } - cons = inp.constructor.toString(); - match = cons.match(/(\w+)\(/); + cons = inp.constructor.toString() + match = cons.match(/(\w+)\(/) if (match) { - cons = match[1].toLowerCase(); + cons = match[1].toLowerCase() } - types = ['boolean', 'number', 'string', 'array']; + types = ['boolean', 'number', 'string', 'array'] for (key in types) { if (cons === types[key]) { - type = types[key]; - break; + type = types[key] + break } } } - return type; + return type }, - type = _getType(mixed_value); + type = _getType(mixed_value) switch (type) { - case 'function': - val = ''; - break; - case 'boolean': - val = 'b:' + (mixed_value ? '1' : '0'); - break; - case 'number': - val = (Math.round(mixed_value) === mixed_value ? 'i' : 'd') + ':' + mixed_value; - break; - case 'string': - val = 's:' + _utf8Size(mixed_value) + ':"' + mixed_value + '"'; - break; - case 'array': - case 'object': - val = 'a'; + case 'function': + val = '' + break + case 'boolean': + val = 'b:' + (mixed_value ? '1' : '0') + break + case 'number': + val = (Math.round(mixed_value) === mixed_value ? 'i' : 'd') + ':' + mixed_value + break + case 'string': + val = 's:' + _utf8Size(mixed_value) + ':"' + mixed_value + '"' + break + case 'array': + case 'object': + val = 'a' /* if (type === 'object') { var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/); @@ -96,29 +96,29 @@ function serialize(mixed_value) { } */ - for (key in mixed_value) { - if (mixed_value.hasOwnProperty(key)) { - ktype = _getType(mixed_value[key]); + for (key in mixed_value) { + if (mixed_value.hasOwnProperty(key)) { + ktype = _getType(mixed_value[key]) if (ktype === 'function') { - continue; + continue } - okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key); - vals += this.serialize(okey) + this.serialize(mixed_value[key]); - count++; + okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key) + vals += this.serialize(okey) + this.serialize(mixed_value[key]) + count++ } - } - val += ':' + count + ':{' + vals + '}'; - break; - case 'undefined': + } + val += ':' + count + ':{' + vals + '}' + break + case 'undefined': // Fall-through - default: + default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP - val = 'N'; - break; + val = 'N' + break } if (type !== 'object' && type !== 'array') { - val += ';'; + val += ';' } - return val; + return val } diff --git a/functions/var/settype.js b/functions/var/settype.js index 9645c93f57..91e65777f2 100644 --- a/functions/var/settype.js +++ b/functions/var/settype.js @@ -1,4 +1,4 @@ -function settype(vr, type) { +function settype (vr, type) { // discuss at: http://phpjs.org/functions/settype/ // original by: Waldo Malqui Silva (http://waldo.malqui.info) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -14,109 +14,109 @@ function settype(vr, type) { // example 2: $result = foo // returns 2: '1' - var is_array = function(arr) { + var is_array = function (arr) { return typeof arr === 'object' && typeof arr.length === 'number' && !(arr.propertyIsEnumerable('length')) && - typeof arr.splice === 'function'; - }; - var v, mtch, i, obj; - v = this[vr] ? this[vr] : vr; + typeof arr.splice === 'function' + } + var v, mtch, i, obj + v = this[vr] ? this[vr] : vr try { switch (type) { - case 'boolean': - if (is_array(v) && v.length === 0) { - this[vr] = false; - } else if (v === '0') { - this[vr] = false; + case 'boolean': + if (is_array(v) && v.length === 0) { + this[vr] = false + } else if (v === '0') { + this[vr] = false } else if (typeof v === 'object' && !is_array(v)) { - var lgth = false; + var lgth = false for (i in v) { - lgth = true; + lgth = true } - this[vr] = lgth; + this[vr] = lgth } else { - this[vr] = !!v; + this[vr] = !!v } - break; - case 'integer': - if (typeof v === 'number') { - this[vr] = parseInt(v, 10); - } else if (typeof v === 'string') { - mtch = v.match(/^([+\-]?)(\d+)/); + break + case 'integer': + if (typeof v === 'number') { + this[vr] = parseInt(v, 10) + } else if (typeof v === 'string') { + mtch = v.match(/^([+\-]?)(\d+)/) if (!mtch) { - this[vr] = 0; + this[vr] = 0 } else { - this[vr] = parseInt(v, 10); + this[vr] = parseInt(v, 10) } } else if (v === true) { - this[vr] = 1; + this[vr] = 1 } else if (v === false || v === null) { - this[vr] = 0; + this[vr] = 0 } else if (is_array(v) && v.length === 0) { - this[vr] = 0; + this[vr] = 0 } else if (typeof v === 'object') { - this[vr] = 1; + this[vr] = 1 } - break; - case 'float': - if (typeof v === 'string') { - mtch = v.match(/^([+\-]?)(\d+(\.\d+)?|\.\d+)([eE][+\-]?\d+)?/); - if (!mtch) { - this[vr] = 0; + break + case 'float': + if (typeof v === 'string') { + mtch = v.match(/^([+\-]?)(\d+(\.\d+)?|\.\d+)([eE][+\-]?\d+)?/) + if (!mtch) { + this[vr] = 0 } else { - this[vr] = parseFloat(v, 10); + this[vr] = parseFloat(v, 10) } - } else if (v === true) { - this[vr] = 1; + } else if (v === true) { + this[vr] = 1 } else if (v === false || v === null) { - this[vr] = 0; + this[vr] = 0 } else if (is_array(v) && v.length === 0) { - this[vr] = 0; + this[vr] = 0 } else if (typeof v === 'object') { - this[vr] = 1; + this[vr] = 1 } - break; - case 'string': - if (v === null || v === false) { - this[vr] = ''; - } else if (is_array(v)) { - this[vr] = 'Array'; + break + case 'string': + if (v === null || v === false) { + this[vr] = '' + } else if (is_array(v)) { + this[vr] = 'Array' } else if (typeof v === 'object') { - this[vr] = 'Object'; + this[vr] = 'Object' } else if (v === true) { - this[vr] = '1'; + this[vr] = '1' } else { - this[vr] += ''; + this[vr] += '' } // numbers (and functions?) - break; - case 'array': - if (v === null) { - this[vr] = []; - } else if (typeof v !== 'object') { - this[vr] = [v]; + break + case 'array': + if (v === null) { + this[vr] = [] + } else if (typeof v !== 'object') { + this[vr] = [v] } - break; - case 'object': - if (v === null) { - this[vr] = {}; - } else if (is_array(v)) { + break + case 'object': + if (v === null) { + this[vr] = {} + } else if (is_array(v)) { for (i = 0, obj = {}; i < v.length; i++) { - obj[i] = v; + obj[i] = v } - this[vr] = obj; + this[vr] = obj } else if (typeof v !== 'object') { this[vr] = { - scalar : v - }; + scalar: v + } } - break; - case 'null': - delete this[vr]; - break; + break + case 'null': + delete this[vr] + break } - return true; + return true } catch (e) { - return false; + return false } -} \ No newline at end of file +} diff --git a/functions/var/strval.js b/functions/var/strval.js index d08700a483..5477bc45b8 100644 --- a/functions/var/strval.js +++ b/functions/var/strval.js @@ -1,4 +1,4 @@ -function strval(str) { +function strval (str) { // discuss at: http://phpjs.org/functions/strval/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -7,27 +7,27 @@ function strval(str) { // example 1: strval({red: 1, green: 2, blue: 3, white: 4}); // returns 1: 'Object' - var type = ''; + var type = '' if (str === null) { - return ''; + return '' } - type = this.gettype(str); + type = this.gettype(str) // Comment out the entire switch if you want JS-like // behavior instead of PHP behavior switch (type) { - case 'boolean': - if (str === true) { - return '1'; - } - return ''; - case 'array': - return 'Array'; - case 'object': - return 'Object'; + case 'boolean': + if (str === true) { + return '1' + } + return '' + case 'array': + return 'Array' + case 'object': + return 'Object' } - return str; -} \ No newline at end of file + return str +} diff --git a/functions/var/unserialize.js b/functions/var/unserialize.js index d3d095bce5..881e681762 100644 --- a/functions/var/unserialize.js +++ b/functions/var/unserialize.js @@ -1,4 +1,4 @@ -function unserialize(data) { +function unserialize (data) { // discuss at: http://phpjs.org/functions/unserialize/ // original by: Arpad Ray (mailto:arpad@php.net) // improved by: Pedro Tainha (http://www.pedrotainha.com) @@ -24,154 +24,153 @@ function unserialize(data) { // returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'} var that = this, - utf8Overhead = function(chr) { + utf8Overhead = function (chr) { // http://phpjs.org/functions/unserialize:571#comment_95906 - var code = chr.charCodeAt(0); - if ( code < 0x0080 - || 0x00A0 <= code && code <= 0x00FF - || [338,339,352,353,376,402,8211,8212,8216,8217,8218,8220,8221,8222,8224,8225,8226,8230,8240,8364,8482].indexOf(code)!=-1) - { - return 0; + var code = chr.charCodeAt(0) + if (code < 0x0080 || 0x00A0 <= code && code <= 0x00FF || [338, 339, 352, 353, 376, 402, 8211, 8212, 8216, 8217, + 8218, 8220, 8221, 8222, 8224, 8225, 8226, 8230, 8240, 8364, 8482 + ].indexOf(code) != -1) { + return 0 } if (code < 0x0800) { - return 1; + return 1 } - return 2; - }; - error = function(type, msg, filename, line) { - throw new that.window[type](msg, filename, line); - }; - read_until = function(data, offset, stopchr) { + return 2 + } + error = function (type, msg, filename, line) { + throw new that.window[type](msg, filename, line) + } + read_until = function (data, offset, stopchr) { var i = 2, buf = [], - chr = data.slice(offset, offset + 1); + chr = data.slice(offset, offset + 1) while (chr != stopchr) { if ((i + offset) > data.length) { - error('Error', 'Invalid'); + error('Error', 'Invalid') } - buf.push(chr); - chr = data.slice(offset + (i - 1), offset + i); - i += 1; + buf.push(chr) + chr = data.slice(offset + (i - 1), offset + i) + i += 1 } - return [buf.length, buf.join('')]; - }; - read_chrs = function(data, offset, length) { - var i, chr, buf; + return [buf.length, buf.join('')] + } + read_chrs = function (data, offset, length) { + var i, chr, buf - buf = []; + buf = [] for (i = 0; i < length; i++) { - chr = data.slice(offset + (i - 1), offset + i); - buf.push(chr); - length -= utf8Overhead(chr); + chr = data.slice(offset + (i - 1), offset + i) + buf.push(chr) + length -= utf8Overhead(chr) } - return [buf.length, buf.join('')]; - }; - _unserialize = function(data, offset) { + return [buf.length, buf.join('')] + } + _unserialize = function (data, offset) { var dtype, dataoffset, keyandchrs, keys, contig, length, array, readdata, readData, ccount, stringlength, i, key, kprops, kchrs, vprops, vchrs, value, chrs = 0, - typeconvert = function(x) { - return x; - }; + typeconvert = function (x) { + return x + } if (!offset) { - offset = 0; + offset = 0 } dtype = (data.slice(offset, offset + 1)) - .toLowerCase(); + .toLowerCase() - dataoffset = offset + 2; + dataoffset = offset + 2 switch (dtype) { - case 'i': - typeconvert = function(x) { - return parseInt(x, 10); - }; - readData = read_until(data, dataoffset, ';'); - chrs = readData[0]; - readdata = readData[1]; - dataoffset += chrs + 1; - break; - case 'b': - typeconvert = function(x) { - return parseInt(x, 10) !== 0; - }; - readData = read_until(data, dataoffset, ';'); - chrs = readData[0]; - readdata = readData[1]; - dataoffset += chrs + 1; - break; - case 'd': - typeconvert = function(x) { - return parseFloat(x); - }; - readData = read_until(data, dataoffset, ';'); - chrs = readData[0]; - readdata = readData[1]; - dataoffset += chrs + 1; - break; - case 'n': - readdata = null; - break; - case 's': - ccount = read_until(data, dataoffset, ':'); - chrs = ccount[0]; - stringlength = ccount[1]; - dataoffset += chrs + 2; - - readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10)); - chrs = readData[0]; - readdata = readData[1]; - dataoffset += chrs + 2; - if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) { - error('SyntaxError', 'String length mismatch'); - } - break; - case 'a': - readdata = {}; - - keyandchrs = read_until(data, dataoffset, ':'); - chrs = keyandchrs[0]; - keys = keyandchrs[1]; - dataoffset += chrs + 2; - - length = parseInt(keys, 10); - contig = true; - - for (i = 0; i < length; i++) { - kprops = _unserialize(data, dataoffset); - kchrs = kprops[1]; - key = kprops[2]; - dataoffset += kchrs; - - vprops = _unserialize(data, dataoffset); - vchrs = vprops[1]; - value = vprops[2]; - dataoffset += vchrs; - - if (key !== i) - contig = false; - - readdata[key] = value; - } - - if (contig) { - array = new Array(length); - for (i = 0; i < length; i++) - array[i] = readdata[i]; - readdata = array; - } - - dataoffset += 1; - break; - default: - error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype); - break; + case 'i': + typeconvert = function (x) { + return parseInt(x, 10) + } + readData = read_until(data, dataoffset, ';') + chrs = readData[0] + readdata = readData[1] + dataoffset += chrs + 1 + break + case 'b': + typeconvert = function (x) { + return parseInt(x, 10) !== 0 + } + readData = read_until(data, dataoffset, ';') + chrs = readData[0] + readdata = readData[1] + dataoffset += chrs + 1 + break + case 'd': + typeconvert = function (x) { + return parseFloat(x) + } + readData = read_until(data, dataoffset, ';') + chrs = readData[0] + readdata = readData[1] + dataoffset += chrs + 1 + break + case 'n': + readdata = null + break + case 's': + ccount = read_until(data, dataoffset, ':') + chrs = ccount[0] + stringlength = ccount[1] + dataoffset += chrs + 2 + + readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10)) + chrs = readData[0] + readdata = readData[1] + dataoffset += chrs + 2 + if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) { + error('SyntaxError', 'String length mismatch') + } + break + case 'a': + readdata = {} + + keyandchrs = read_until(data, dataoffset, ':') + chrs = keyandchrs[0] + keys = keyandchrs[1] + dataoffset += chrs + 2 + + length = parseInt(keys, 10) + contig = true + + for (i = 0; i < length; i++) { + kprops = _unserialize(data, dataoffset) + kchrs = kprops[1] + key = kprops[2] + dataoffset += kchrs + + vprops = _unserialize(data, dataoffset) + vchrs = vprops[1] + value = vprops[2] + dataoffset += vchrs + + if (key !== i) + contig = false + + readdata[key] = value + } + + if (contig) { + array = new Array(length) + for (i = 0; i < length; i++) + array[i] = readdata[i] + readdata = array + } + + dataoffset += 1 + break + default: + error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype) + break } - return [dtype, dataoffset - offset, typeconvert(readdata)]; - }; + return [dtype, dataoffset - offset, typeconvert(readdata)] + } - return _unserialize((data + ''), 0)[2]; + return _unserialize((data + ''), 0)[2] } diff --git a/functions/var/var_dump.js b/functions/var/var_dump.js index 00cf08824c..6fda8fb71b 100644 --- a/functions/var/var_dump.js +++ b/functions/var/var_dump.js @@ -1,4 +1,4 @@ -function var_dump() { +function var_dump () { // discuss at: http://phpjs.org/functions/var_dump/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Zahlii @@ -13,145 +13,144 @@ function var_dump() { pad_char = ' ', pad_val = 4, lgth = 0, - i = 0; + i = 0 - var _getFuncName = function(fn) { + var _getFuncName = function (fn) { var name = (/\W*function\s+([\w\$]+)\s*\(/) - .exec(fn); + .exec(fn) if (!name) { - return '(Anonymous)'; + return '(Anonymous)' } - return name[1]; - }; + return name[1] + } - var _repeat_char = function(len, pad_char) { - var str = ''; + var _repeat_char = function (len, pad_char) { + var str = '' for (var i = 0; i < len; i++) { - str += pad_char; + str += pad_char } - return str; - }; - var _getInnerVal = function(val, thick_pad) { - var ret = ''; + return str + } + var _getInnerVal = function (val, thick_pad) { + var ret = '' if (val === null) { - ret = 'NULL'; + ret = 'NULL' } else if (typeof val === 'boolean') { - ret = 'bool(' + val + ')'; + ret = 'bool(' + val + ')' } else if (typeof val === 'string') { - ret = 'string(' + val.length + ') "' + val + '"'; + ret = 'string(' + val.length + ') "' + val + '"' } else if (typeof val === 'number') { if (parseFloat(val) == parseInt(val, 10)) { - ret = 'int(' + val + ')'; + ret = 'int(' + val + ')' } else { - ret = 'float(' + val + ')'; + ret = 'float(' + val + ')' } } // The remaining are not PHP behavior because these values only exist in this exact form in JavaScript else if (typeof val === 'undefined') { - ret = 'undefined'; + ret = 'undefined' } else if (typeof val === 'function') { var funcLines = val.toString() - .split('\n'); - ret = ''; + .split('\n') + ret = '' for (var i = 0, fll = funcLines.length; i < fll; i++) { - ret += (i !== 0 ? '\n' + thick_pad : '') + funcLines[i]; + ret += (i !== 0 ? '\n' + thick_pad : '') + funcLines[i] } } else if (val instanceof Date) { - ret = 'Date(' + val + ')'; + ret = 'Date(' + val + ')' } else if (val instanceof RegExp) { - ret = 'RegExp(' + val + ')'; + ret = 'RegExp(' + val + ')' } else if (val.nodeName) { // Different than PHP's DOMElement switch (val.nodeType) { - case 1: - if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') { + case 1: + if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') { // Undefined namespace could be plain XML, but namespaceURI not widely supported - ret = 'HTMLElement("' + val.nodeName + '")'; - } else { - ret = 'XML Element("' + val.nodeName + '")'; - } - break; - case 2: - ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')'; - break; - case 3: - ret = 'TEXT_NODE(' + val.nodeValue + ')'; - break; - case 4: - ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')'; - break; - case 5: - ret = 'ENTITY_REFERENCE_NODE'; - break; - case 6: - ret = 'ENTITY_NODE'; - break; - case 7: - ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue + ')'; - break; - case 8: - ret = 'COMMENT_NODE(' + val.nodeValue + ')'; - break; - case 9: - ret = 'DOCUMENT_NODE'; - break; - case 10: - ret = 'DOCUMENT_TYPE_NODE'; - break; - case 11: - ret = 'DOCUMENT_FRAGMENT_NODE'; - break; - case 12: - ret = 'NOTATION_NODE'; - break; + ret = 'HTMLElement("' + val.nodeName + '")' + } else { + ret = 'XML Element("' + val.nodeName + '")' + } + break + case 2: + ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')' + break + case 3: + ret = 'TEXT_NODE(' + val.nodeValue + ')' + break + case 4: + ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')' + break + case 5: + ret = 'ENTITY_REFERENCE_NODE' + break + case 6: + ret = 'ENTITY_NODE' + break + case 7: + ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue + ')' + break + case 8: + ret = 'COMMENT_NODE(' + val.nodeValue + ')' + break + case 9: + ret = 'DOCUMENT_NODE' + break + case 10: + ret = 'DOCUMENT_TYPE_NODE' + break + case 11: + ret = 'DOCUMENT_FRAGMENT_NODE' + break + case 12: + ret = 'NOTATION_NODE' + break } } - return ret; - }; + return ret + } - var _formatArray = function(obj, cur_depth, pad_val, pad_char) { - var someProp = ''; + var _formatArray = function (obj, cur_depth, pad_val, pad_char) { + var someProp = '' if (cur_depth > 0) { - cur_depth++; + cur_depth++ } - var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char); - var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char); - var str = ''; - var val = ''; + var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char) + var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char) + var str = '' + var val = '' if (typeof obj === 'object' && obj !== null) { if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') { - return obj.var_dump(); + return obj.var_dump() } - lgth = 0; + lgth = 0 for (someProp in obj) { - lgth++; + lgth++ } - str += 'array(' + lgth + ') {\n'; + str += 'array(' + lgth + ') {\n' for (var key in obj) { - var objVal = obj[key]; + var objVal = obj[key] if (typeof objVal === 'object' && objVal !== null && !(objVal instanceof Date) && !(objVal instanceof RegExp) && - ! - objVal.nodeName) { + !objVal.nodeName) { str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val, - pad_char); + pad_char) } else { - val = _getInnerVal(objVal, thick_pad); - str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n'; + val = _getInnerVal(objVal, thick_pad) + str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n' } } - str += base_pad + '}\n'; + str += base_pad + '}\n' } else { - str = _getInnerVal(obj, thick_pad); + str = _getInnerVal(obj, thick_pad) } - return str; - }; + return str + } - output = _formatArray(arguments[0], 0, pad_val, pad_char); + output = _formatArray(arguments[0], 0, pad_val, pad_char) for (i = 1; i < arguments.length; i++) { - output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char); + output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char) } - this.echo(output); -} \ No newline at end of file + this.echo(output) +} diff --git a/functions/var/var_export.js b/functions/var/var_export.js index f709230aed..8901f9c605 100644 --- a/functions/var/var_export.js +++ b/functions/var/var_export.js @@ -1,4 +1,4 @@ -function var_export(mixed_expression, bool_return) { +function var_export (mixed_expression, bool_return) { // discuss at: http://phpjs.org/functions/var_export/ // original by: Philip Peterson // improved by: johnrembo @@ -28,73 +28,73 @@ function var_export(mixed_expression, bool_return) { idtLevel = arguments[2] || 2, innerIndent = '', outerIndent = '', - getFuncName = function(fn) { + getFuncName = function (fn) { var name = (/\W*function\s+([\w\$]+)\s*\(/) - .exec(fn); + .exec(fn) if (!name) { - return '(Anonymous)'; + return '(Anonymous)' } - return name[1]; - }; - _makeIndent = function(idtLevel) { + return name[1] + } + _makeIndent = function (idtLevel) { return (new Array(idtLevel + 1)) - .join(' '); - }; - __getType = function(inp) { + .join(' ') + } + __getType = function (inp) { var i = 0, - match, types, cons, type = typeof inp; + match, types, cons, type = typeof inp if (type === 'object' && (inp && inp.constructor) && getFuncName(inp.constructor) === 'PHPJS_Resource') { - return 'resource'; + return 'resource' } if (type === 'function') { - return 'function'; + return 'function' } if (type === 'object' && !inp) { // Should this be just null? - return 'null'; + return 'null' } if (type === 'object') { if (!inp.constructor) { - return 'object'; + return 'object' } - cons = inp.constructor.toString(); - match = cons.match(/(\w+)\(/); + cons = inp.constructor.toString() + match = cons.match(/(\w+)\(/) if (match) { - cons = match[1].toLowerCase(); + cons = match[1].toLowerCase() } - types = ['boolean', 'number', 'string', 'array']; + types = ['boolean', 'number', 'string', 'array'] for (i = 0; i < types.length; i++) { if (cons === types[i]) { - type = types[i]; - break; + type = types[i] + break } } } - return type; - }; - type = __getType(mixed_expression); + return type + } + type = __getType(mixed_expression) if (type === null) { - retstr = 'NULL'; + retstr = 'NULL' } else if (type === 'array' || type === 'object') { - outerIndent = _makeIndent(idtLevel - 2); - innerIndent = _makeIndent(idtLevel); + outerIndent = _makeIndent(idtLevel - 2) + innerIndent = _makeIndent(idtLevel) for (i in mixed_expression) { - value = this.var_export(mixed_expression[i], 1, idtLevel + 2); + value = this.var_export(mixed_expression[i], 1, idtLevel + 2) value = typeof value === 'string' ? value.replace(//g, '>'): value; + replace(/>/g, '>') : value x[cnt++] = innerIndent + i + ' => ' + (__getType(mixed_expression[i]) === 'array' ? - '\n' : '') + value; + '\n' : '') + value } - iret = x.join(',\n'); - retstr = outerIndent + 'array (\n' + iret + '\n' + outerIndent + ')'; + iret = x.join(',\n') + retstr = outerIndent + 'array (\n' + iret + '\n' + outerIndent + ')' } else if (type === 'function') { funcParts = mixed_expression.toString() . - match(/function .*?\((.*?)\) \{([\s\S]*)\}/); + match(/function .*?\((.*?)\) \{([\s\S]*)\}/) // For lambda functions, var_export() outputs such as the following: // '\000lambda_1'. Since it will probably not be a common use to @@ -104,21 +104,21 @@ function var_export(mixed_expression, bool_return) { // are using the namespaced version, note that create_function() will // not be available as a global retstr = "create_function ('" + funcParts[1] + "', '" + - funcParts[2].replace(new RegExp("'", 'g'), "\\'") + "')"; + funcParts[2].replace(new RegExp("'", 'g'), "\\'") + "')" } else if (type === 'resource') { // Resources treated as null for var_export - retstr = 'NULL'; + retstr = 'NULL' } else { retstr = typeof mixed_expression !== 'string' ? mixed_expression : "'" + mixed_expression.replace(/(["'])/g, '\\$1') . - replace(/\0/g, '\\0') + "'"; + replace(/\0/g, '\\0') + "'" } if (!bool_return) { - this.echo(retstr); - return null; + this.echo(retstr) + return null } - return retstr; -} \ No newline at end of file + return retstr +} diff --git a/functions/xdiff/xdiff_string_diff.js b/functions/xdiff/xdiff_string_diff.js index 7ee5230fc2..bd52b0840c 100644 --- a/functions/xdiff/xdiff_string_diff.js +++ b/functions/xdiff/xdiff_string_diff.js @@ -1,4 +1,4 @@ -function xdiff_string_diff(old_data, new_data, context_lines, minimal) { +function xdiff_string_diff (old_data, new_data, context_lines, minimal) { // discuss at: http://phpjs.org/functions/xdiff_string_diff // original by: Brett Zamir (http://brett-zamir.me) // based on: Imgen Tata (http://www.myipdf.com/) @@ -33,267 +33,267 @@ function xdiff_string_diff(old_data, new_data, context_lines, minimal) { /** * Trims string */ - trim = function(text) { + trim = function (text) { if (typeof text !== 'string') { - throw new Error('String parameter required'); + throw new Error('String parameter required') } - return text.replace(/(^\s*)|(\s*$)/g, ''); + return text.replace(/(^\s*)|(\s*$)/g, '') }, /** * Verifies type of arguments */ - verify_type = function(type) { + verify_type = function (type) { var args = arguments, args_len = arguments.length, basic_types = ['number', 'boolean', 'string', 'function', 'object', 'undefined'], - basic_type, i, j, type_of_type = typeof type; + basic_type, i, j, type_of_type = typeof type if (type_of_type !== 'string' && type_of_type !== 'function') { - throw new Error('Bad type parameter'); + throw new Error('Bad type parameter') } if (args_len < 2) { - throw new Error('Too few arguments'); + throw new Error('Too few arguments') } if (type_of_type === 'string') { - type = trim(type); + type = trim(type) if (type === '') { - throw new Error('Bad type parameter'); + throw new Error('Bad type parameter') } for (j = 0; j < basic_types.length; j++) { - basic_type = basic_types[j]; + basic_type = basic_types[j] if (basic_type == type) { for (i = 1; i < args_len; i++) { if (typeof args[i] !== type) { - throw new Error('Bad type'); + throw new Error('Bad type') } } - return; + return } } - throw new Error('Bad type parameter'); + throw new Error('Bad type parameter') } // Not basic type. we need to use instanceof operator for (i = 1; i < args_len; i++) { if (!(args[i] instanceof type)) { - throw new Error('Bad type'); + throw new Error('Bad type') } } }, /** * Checks if the specified array contains an element with specified value */ - has_value = function(array, value) { - var i; - verify_type(Array, array); + has_value = function (array, value) { + var i + verify_type(Array, array) for (i = 0; i < array.length; i++) { if (array[i] === value) { - return true; + return true } } - return false; + return false }, /** * Checks the type of arguments * @param {String | Function} type Specifies the desired type * @return {Boolean} Return true if all arguments after the type argument are of specified type. Else false */ - are_type_of = function(type) { + are_type_of = function (type) { var args = arguments, args_len = arguments.length, basic_types = ['number', 'boolean', 'string', 'function', 'object', 'undefined'], - basic_type, i, j, type_of_type = typeof type; + basic_type, i, j, type_of_type = typeof type if (type_of_type !== 'string' && type_of_type !== 'function') { - throw new Error('Bad type parameter'); + throw new Error('Bad type parameter') } if (args_len < 2) { - throw new Error('Too few arguments'); + throw new Error('Too few arguments') } if (type_of_type === 'string') { - type = trim(type); + type = trim(type) if (type === '') { - return false; + return false } for (j = 0; j < basic_types.length; j++) { - basic_type = basic_types[j]; + basic_type = basic_types[j] if (basic_type == type) { for (i = 1; i < args_len; i++) { if (typeof args[i] != type) { - return false; + return false } } - return true; + return true } } - throw new Error('Bad type parameter'); + throw new Error('Bad type parameter') } // Not basic type. we need to use instanceof operator for (i = 1; i < args_len; i++) { if (!(args[i] instanceof type)) { - return false; + return false } } - return true; + return true }, /* * Initialize and return an array with specified size and initial value */ - get_initialized_array = function(array_size, init_value) { + get_initialized_array = function (array_size, init_value) { var array = [], - i; - verify_type('number', array_size); + i + verify_type('number', array_size) for (i = 0; i < array_size; i++) { - array.push(init_value); + array.push(init_value) } - return array; + return array }, /** * Splits text into lines and return as a string array */ - split_into_lines = function(text) { - verify_type('string', text); + split_into_lines = function (text) { + verify_type('string', text) if (text === '') { - return []; + return [] } - return text.split('\n'); + return text.split('\n') }, - is_empty_array = function(obj) { - return are_type_of(Array, obj) && obj.length === 0; + is_empty_array = function (obj) { + return are_type_of(Array, obj) && obj.length === 0 }, /** * Finds longest common sequence between two sequences * @see {@link http://wordaligned.org/articles/longest-common-subsequence} */ - find_longest_common_sequence = function(seq1, seq2, seq1_is_in_lcs, seq2_is_in_lcs) { + find_longest_common_sequence = function (seq1, seq2, seq1_is_in_lcs, seq2_is_in_lcs) { if (!are_type_of(Array, seq1, seq2)) { - throw new Error('Array parameters are required'); + throw new Error('Array parameters are required') } // Deal with edge case if (is_empty_array(seq1) || is_empty_array(seq2)) { - return []; + return [] } // Function to calculate lcs lengths - var lcs_lens = function(xs, ys) { + var lcs_lens = function (xs, ys) { var i, j, prev, - curr = get_initialized_array(ys.length + 1, 0); + curr = get_initialized_array(ys.length + 1, 0) for (i = 0; i < xs.length; i++) { - prev = curr.slice(0); + prev = curr.slice(0) for (j = 0; j < ys.length; j++) { if (xs[i] === ys[j]) { - curr[j + 1] = prev[j] + 1; + curr[j + 1] = prev[j] + 1 } else { - curr[j + 1] = Math.max(curr[j], prev[j + 1]); + curr[j + 1] = Math.max(curr[j], prev[j + 1]) } } } - return curr; + return curr }, // Function to find lcs and fill in the array to indicate the optimal longest common sequence - find_lcs = function(xs, xidx, xs_is_in, ys) { + find_lcs = function (xs, xidx, xs_is_in, ys) { var i, xb, xe, ll_b, ll_e, pivot, max, yb, ye, nx = xs.length, - ny = ys.length; + ny = ys.length if (nx === 0) { - return []; + return [] } if (nx === 1) { if (has_value(ys, xs[0])) { - xs_is_in[xidx] = true; - return [xs[0]]; + xs_is_in[xidx] = true + return [xs[0]] } - return []; + return [] } - i = Math.floor(nx / 2); - xb = xs.slice(0, i); - xe = xs.slice(i); - ll_b = lcs_lens(xb, ys); + i = Math.floor(nx / 2) + xb = xs.slice(0, i) + xe = xs.slice(i) + ll_b = lcs_lens(xb, ys) ll_e = lcs_lens(xe.slice(0) .reverse(), ys.slice(0) - .reverse()); + .reverse()) - pivot = 0; - max = 0; + pivot = 0 + max = 0 for (j = 0; j <= ny; j++) { if (ll_b[j] + ll_e[ny - j] > max) { - pivot = j; - max = ll_b[j] + ll_e[ny - j]; + pivot = j + max = ll_b[j] + ll_e[ny - j] } } - yb = ys.slice(0, pivot); - ye = ys.slice(pivot); + yb = ys.slice(0, pivot) + ye = ys.slice(pivot) return find_lcs(xb, xidx, xs_is_in, yb) - .concat(find_lcs(xe, xidx + i, xs_is_in, ye)); - }; + .concat(find_lcs(xe, xidx + i, xs_is_in, ye)) + } // Fill in seq1_is_in_lcs to find the optimal longest common subsequence of first sequence - find_lcs(seq1, 0, seq1_is_in_lcs, seq2); + find_lcs(seq1, 0, seq1_is_in_lcs, seq2) // Fill in seq2_is_in_lcs to find the optimal longest common subsequence of second sequence and return the result - return find_lcs(seq2, 0, seq2_is_in_lcs, seq1); - }; + return find_lcs(seq2, 0, seq2_is_in_lcs, seq1) + } // First, check the parameters if (are_type_of('string', old_data, new_data) === false) { - return false; + return false } if (old_data == new_data) { - return ''; + return '' } if (typeof context_lines !== 'number' || context_lines > MAX_CONTEXT_LINES || context_lines < MIN_CONTEXT_LINES) { - context_lines = DEFAULT_CONTEXT_LINES; + context_lines = DEFAULT_CONTEXT_LINES } - ori_lines = split_into_lines(old_data); - new_lines = split_into_lines(new_data); + ori_lines = split_into_lines(old_data) + new_lines = split_into_lines(new_data) var ori_len = ori_lines.length, new_len = new_lines.length, ori_is_in_lcs = get_initialized_array(ori_len, false), new_is_in_lcs = get_initialized_array(new_len, false), lcs_len = find_longest_common_sequence(ori_lines, new_lines, ori_is_in_lcs, new_is_in_lcs) .length, - unidiff = ''; + unidiff = '' if (lcs_len === 0) { // No common sequence unidiff = HEADER_PREFIX + ORIGINAL_INDICATOR + (ori_len > 0 ? '1' : '0') + RANGE_SEPARATOR + ori_len + ' ' + - NEW_INDICATOR + (new_len > 0 ? '1' : '0') + RANGE_SEPARATOR + new_len + HEADER_SUFFIX; + NEW_INDICATOR + (new_len > 0 ? '1' : '0') + RANGE_SEPARATOR + new_len + HEADER_SUFFIX for (i = 0; i < ori_len; i++) { - unidiff += NEW_LINE + DELETION_INDICATOR + ori_lines[i]; + unidiff += NEW_LINE + DELETION_INDICATOR + ori_lines[i] } for (j = 0; j < new_len; j++) { - unidiff += NEW_LINE + ADDITION_INDICATOR + new_lines[j]; + unidiff += NEW_LINE + ADDITION_INDICATOR + new_lines[j] } - return unidiff; + return unidiff } var leading_context = [], @@ -302,57 +302,57 @@ function xdiff_string_diff(old_data, new_data, context_lines, minimal) { actual_trailing_context = [], // Regularize leading context by the context_lines parameter - regularize_leading_context = function(context) { + regularize_leading_context = function (context) { if (context.length === 0 || context_lines === 0) { - return []; + return [] } - var context_start_pos = Math.max(context.length - context_lines, 0); + var context_start_pos = Math.max(context.length - context_lines, 0) - return context.slice(context_start_pos); + return context.slice(context_start_pos) }, // Regularize trailing context by the context_lines parameter - regularize_trailing_context = function(context) { + regularize_trailing_context = function (context) { if (context.length === 0 || context_lines === 0) { - return []; + return [] } - return context.slice(0, Math.min(context_lines, context.length)); - }; + return context.slice(0, Math.min(context_lines, context.length)) + } // Skip common lines in the beginning while (i < ori_len && ori_is_in_lcs[i] === true && new_is_in_lcs[i] === true) { - leading_context.push(ori_lines[i]); - i++; + leading_context.push(ori_lines[i]) + i++ } - j = i; + j = i // The index in the longest common sequence - k = i; - ori_hunk_start = i; - new_hunk_start = j; - ori_hunk_end = i; - new_hunk_end = j; + k = i + ori_hunk_start = i + new_hunk_start = j + ori_hunk_end = i + new_hunk_end = j while (i < ori_len || j < new_len) { while (i < ori_len && ori_is_in_lcs[i] === false) { - i++; + i++ } - ori_hunk_end = i; + ori_hunk_end = i while (j < new_len && new_is_in_lcs[j] === false) { - j++; + j++ } - new_hunk_end = j; + new_hunk_end = j // Find the trailing context - trailing_context = []; + trailing_context = [] while (i < ori_len && ori_is_in_lcs[i] === true && j < new_len && new_is_in_lcs[j] === true) { - trailing_context.push(ori_lines[i]); - k++; - i++; - j++; + trailing_context.push(ori_lines[i]) + k++ + i++ + j++ } if (k >= lcs_len || // No more in longest common lines @@ -360,67 +360,67 @@ function xdiff_string_diff(old_data, new_data, context_lines, minimal) { // Context break found if (trailing_context.length < 2 * context_lines) { // It must be last block of common lines but not a context break - trailing_context = []; + trailing_context = [] // Force break out - i = ori_len; - j = new_len; + i = ori_len + j = new_len // Update hunk ends to force output to the end - ori_hunk_end = ori_len; - new_hunk_end = new_len; + ori_hunk_end = ori_len + new_hunk_end = new_len } // Output the diff hunk // Trim the leading and trailing context block - actual_leading_context = regularize_leading_context(leading_context); - actual_trailing_context = regularize_trailing_context(trailing_context); + actual_leading_context = regularize_leading_context(leading_context) + actual_trailing_context = regularize_trailing_context(trailing_context) - ori_hunk_start -= actual_leading_context.length; - new_hunk_start -= actual_leading_context.length; - ori_hunk_end += actual_trailing_context.length; - new_hunk_end += actual_trailing_context.length; + ori_hunk_start -= actual_leading_context.length + new_hunk_start -= actual_leading_context.length + ori_hunk_end += actual_trailing_context.length + new_hunk_end += actual_trailing_context.length - ori_hunk_line_no = ori_hunk_start + 1; - new_hunk_line_no = new_hunk_start + 1; - ori_hunk_size = ori_hunk_end - ori_hunk_start; - new_hunk_size = new_hunk_end - new_hunk_start; + ori_hunk_line_no = ori_hunk_start + 1 + new_hunk_line_no = new_hunk_start + 1 + ori_hunk_size = ori_hunk_end - ori_hunk_start + new_hunk_size = new_hunk_end - new_hunk_start // Build header unidiff += HEADER_PREFIX + ORIGINAL_INDICATOR + ori_hunk_line_no + RANGE_SEPARATOR + ori_hunk_size + ' ' + - NEW_INDICATOR + new_hunk_line_no + RANGE_SEPARATOR + new_hunk_size + HEADER_SUFFIX + NEW_LINE; + NEW_INDICATOR + new_hunk_line_no + RANGE_SEPARATOR + new_hunk_size + HEADER_SUFFIX + NEW_LINE // Build the diff hunk content while (ori_hunk_start < ori_hunk_end || new_hunk_start < new_hunk_end) { if (ori_hunk_start < ori_hunk_end && ori_is_in_lcs[ori_hunk_start] === true && new_is_in_lcs[ new_hunk_start] === true) { // The context line - unidiff += CONTEXT_INDICATOR + ori_lines[ori_hunk_start] + NEW_LINE; - ori_hunk_start++; - new_hunk_start++; + unidiff += CONTEXT_INDICATOR + ori_lines[ori_hunk_start] + NEW_LINE + ori_hunk_start++ + new_hunk_start++ } else if (ori_hunk_start < ori_hunk_end && ori_is_in_lcs[ori_hunk_start] === false) { // The deletion line - unidiff += DELETION_INDICATOR + ori_lines[ori_hunk_start] + NEW_LINE; - ori_hunk_start++; + unidiff += DELETION_INDICATOR + ori_lines[ori_hunk_start] + NEW_LINE + ori_hunk_start++ } else if (new_hunk_start < new_hunk_end && new_is_in_lcs[new_hunk_start] === false) { // The additional line - unidiff += ADDITION_INDICATOR + new_lines[new_hunk_start] + NEW_LINE; - new_hunk_start++; + unidiff += ADDITION_INDICATOR + new_lines[new_hunk_start] + NEW_LINE + new_hunk_start++ } } // Update hunk position and leading context - ori_hunk_start = i; - new_hunk_start = j; - leading_context = trailing_context; + ori_hunk_start = i + new_hunk_start = j + leading_context = trailing_context } } // Trim the trailing new line if it exists if (unidiff.length > 0 && unidiff.charAt(unidiff.length) === NEW_LINE) { - unidiff = unidiff.slice(0, -1); + unidiff = unidiff.slice(0, -1) } - return unidiff; -} \ No newline at end of file + return unidiff +} diff --git a/functions/xdiff/xdiff_string_patch.js b/functions/xdiff/xdiff_string_patch.js index 648f2da571..f38f1d6a59 100644 --- a/functions/xdiff/xdiff_string_patch.js +++ b/functions/xdiff/xdiff_string_patch.js @@ -1,4 +1,4 @@ -function xdiff_string_patch(originalStr, patch, flags, error) { +function xdiff_string_patch (originalStr, patch, flags, error) { // discuss at: http://phpjs.org/functions/xdiff_string_patch/ // original by: Brett Zamir (http://brett-zamir.me) // improved by: Steven Levithan (stevenlevithan.com) @@ -12,16 +12,16 @@ function xdiff_string_patch(originalStr, patch, flags, error) { // (c) 2007-2010 Steven Levithan // MIT License // - var getNativeFlags = function(regex) { + var getNativeFlags = function (regex) { return (regex.global ? 'g' : '') + (regex.ignoreCase ? 'i' : '') + (regex.multiline ? 'm' : '') + (regex.extended ? 'x' : '') + // Proposed for ES4; included in AS3 - (regex.sticky ? 'y' : ''); + (regex.sticky ? 'y' : '') }, - cbSplit = function(string, sep /* separator */) { + cbSplit = function (string, sep /* separator */) { // If separator `s` is not a regex, use the native `split` if (!(sep instanceof RegExp)) { // Had problems to get it to work here using prototype test - return String.prototype.split.apply(string, arguments); + return String.prototype.split.apply(string, arguments) } var str = String(string), output = [], @@ -32,45 +32,45 @@ function xdiff_string_patch(originalStr, patch, flags, error) { // and restore it to its original value when we're done using the regex x = sep._xregexp, // Brett paring down - s = new RegExp(sep.source, getNativeFlags(sep) + 'g'); + s = new RegExp(sep.source, getNativeFlags(sep) + 'g') if (x) { s._xregexp = { - source : x.source, - captureNames : x.captureNames ? x.captureNames.slice(0) : null - }; + source: x.source, + captureNames: x.captureNames ? x.captureNames.slice(0) : null + } } while ((match = s.exec(str))) { // Run the altered `exec` (required for `lastIndex` fix, etc.) if (s.lastIndex > lastLastIndex) { - output.push(str.slice(lastLastIndex, match.index)); + output.push(str.slice(lastLastIndex, match.index)) if (match.length > 1 && match.index < str.length) { - Array.prototype.push.apply(output, match.slice(1)); + Array.prototype.push.apply(output, match.slice(1)) } - lastLength = match[0].length; - lastLastIndex = s.lastIndex; + lastLength = match[0].length + lastLastIndex = s.lastIndex if (output.length >= limit) { - break; + break } } if (s.lastIndex === match.index) { - s.lastIndex++; + s.lastIndex++ } } if (lastLastIndex === str.length) { if (!s.test('') || lastLength) { - output.push(''); + output.push('') } } else { - output.push(str.slice(lastLastIndex)); + output.push(str.slice(lastLastIndex)) } - return output.length > limit ? output.slice(0, limit) : output; + return output.length > limit ? output.slice(0, limit) : output }, i = 0, ll = 0, @@ -88,105 +88,105 @@ function xdiff_string_patch(originalStr, patch, flags, error) { optTemp = 0, OPTS = { // Unsure of actual PHP values, so better to rely on string - 'XDIFF_PATCH_NORMAL' : 1, - 'XDIFF_PATCH_REVERSE' : 2, - 'XDIFF_PATCH_IGNORESPACE' : 4 - }; + 'XDIFF_PATCH_NORMAL': 1, + 'XDIFF_PATCH_REVERSE': 2, + 'XDIFF_PATCH_IGNORESPACE': 4 + } // Input defaulting & sanitation if (typeof originalStr !== 'string' || !patch) { - return false; + return false } if (!flags) { - flags = 'XDIFF_PATCH_NORMAL'; + flags = 'XDIFF_PATCH_NORMAL' } if (typeof flags !== 'number') { // Allow for a single string or an array of string flags - flags = [].concat(flags); + flags = [].concat(flags) for (i = 0; i < flags.length; i++) { // Resolve string input to bitwise e.g. 'XDIFF_PATCH_NORMAL' becomes 1 if (OPTS[flags[i]]) { - optTemp = optTemp | OPTS[flags[i]]; + optTemp = optTemp | OPTS[flags[i]] } } - flags = optTemp; + flags = optTemp } if (flags & OPTS.XDIFF_PATCH_NORMAL) { for (i = 0, ll = lines.length; i < ll; i++) { - ranges = lines[i].match(rangeExp); + ranges = lines[i].match(rangeExp) if (ranges) { - lastLinePos = linePos; - linePos = ranges[1] - 1; + lastLinePos = linePos + linePos = ranges[1] - 1 while (lastLinePos < linePos) { - newStrArr[newStrArr.length] = origLines[lastLinePos++]; + newStrArr[newStrArr.length] = origLines[lastLinePos++] } while (lines[++i] && (rangeExp.exec(lines[i])) === null) { - firstChar = lines[i].charAt(0); + firstChar = lines[i].charAt(0) switch (firstChar) { - case '-': + case '-': // Skip including that line - ++linePos; - break; - case '+': - newStrArr[newStrArr.length] = lines[i].slice(1); - break; - case ' ': - newStrArr[newStrArr.length] = origLines[linePos++]; - break; - default: + ++linePos + break + case '+': + newStrArr[newStrArr.length] = lines[i].slice(1) + break + case ' ': + newStrArr[newStrArr.length] = origLines[linePos++] + break + default: // Reconcile with returning errrors arg? - throw 'Unrecognized initial character in unidiff line'; + throw 'Unrecognized initial character in unidiff line' } } if (lines[i]) { - i--; + i-- } } } while (linePos > 0 && linePos < origLines.length) { - newStrArr[newStrArr.length] = origLines[linePos++]; + newStrArr[newStrArr.length] = origLines[linePos++] } } else if (flags & OPTS.XDIFF_PATCH_REVERSE) { // Only differs from above by a few lines for (i = 0, ll = lines.length; i < ll; i++) { - ranges = lines[i].match(rangeExp); + ranges = lines[i].match(rangeExp) if (ranges) { - lastLinePos = linePos; - linePos = ranges[3] - 1; + lastLinePos = linePos + linePos = ranges[3] - 1 while (lastLinePos < linePos) { - newStrArr[newStrArr.length] = origLines[lastLinePos++]; + newStrArr[newStrArr.length] = origLines[lastLinePos++] } while (lines[++i] && (rangeExp.exec(lines[i])) === null) { - firstChar = lines[i].charAt(0); + firstChar = lines[i].charAt(0) switch (firstChar) { - case '-': - newStrArr[newStrArr.length] = lines[i].slice(1); - break; - case '+': + case '-': + newStrArr[newStrArr.length] = lines[i].slice(1) + break + case '+': // Skip including that line - ++linePos; - break; - case ' ': - newStrArr[newStrArr.length] = origLines[linePos++]; - break; - default: + ++linePos + break + case ' ': + newStrArr[newStrArr.length] = origLines[linePos++] + break + default: // Reconcile with returning errrors arg? - throw 'Unrecognized initial character in unidiff line'; + throw 'Unrecognized initial character in unidiff line' } } if (lines[i]) { - i--; + i-- } } } while (linePos > 0 && linePos < origLines.length) { - newStrArr[newStrArr.length] = origLines[linePos++]; + newStrArr[newStrArr.length] = origLines[linePos++] } } if (typeof error === 'string') { - this.window[error] = errors; + this.window[error] = errors } - return newStrArr.join('\n'); -} \ No newline at end of file + return newStrArr.join('\n') +} diff --git a/functions/xml/utf8_decode.js b/functions/xml/utf8_decode.js index c5701ec70d..e6176caae1 100644 --- a/functions/xml/utf8_decode.js +++ b/functions/xml/utf8_decode.js @@ -1,4 +1,4 @@ -function utf8_decode(str_data) { +function utf8_decode (str_data) { // discuss at: http://phpjs.org/functions/utf8_decode/ // original by: Webtoolkit.info (http://www.webtoolkit.info/) // input by: Aman Gupta @@ -16,42 +16,42 @@ function utf8_decode(str_data) { var tmp_arr = [], i = 0, c1 = 0, - seqlen = 0; + seqlen = 0 - str_data += ''; + str_data += '' while (i < str_data.length) { - c1 = str_data.charCodeAt(i) & 0xFF; - seqlen = 0; + c1 = str_data.charCodeAt(i) & 0xFF + seqlen = 0 // http://en.wikipedia.org/wiki/UTF-8#Codepage_layout if (c1 <= 0xBF) { - c1 = (c1 & 0x7F); - seqlen = 1; + c1 = (c1 & 0x7F) + seqlen = 1 } else if (c1 <= 0xDF) { - c1 = (c1 & 0x1F); - seqlen = 2; + c1 = (c1 & 0x1F) + seqlen = 2 } else if (c1 <= 0xEF) { - c1 = (c1 & 0x0F); - seqlen = 3; + c1 = (c1 & 0x0F) + seqlen = 3 } else { - c1 = (c1 & 0x07); - seqlen = 4; + c1 = (c1 & 0x07) + seqlen = 4 } for (var ai = 1; ai < seqlen; ++ai) { - c1 = ((c1 << 0x06) | (str_data.charCodeAt(ai + i) & 0x3F)); + c1 = ((c1 << 0x06) | (str_data.charCodeAt(ai + i) & 0x3F)) } if (seqlen == 4) { - c1 -= 0x10000; - tmp_arr.push(String.fromCharCode(0xD800 | ((c1 >> 10) & 0x3FF)), String.fromCharCode(0xDC00 | (c1 & 0x3FF))); + c1 -= 0x10000 + tmp_arr.push(String.fromCharCode(0xD800 | ((c1 >> 10) & 0x3FF)), String.fromCharCode(0xDC00 | (c1 & 0x3FF))) } else { - tmp_arr.push(String.fromCharCode(c1)); + tmp_arr.push(String.fromCharCode(c1)) } - i += seqlen; + i += seqlen } - return tmp_arr.join(""); -} \ No newline at end of file + return tmp_arr.join('') +} diff --git a/functions/xml/utf8_encode.js b/functions/xml/utf8_encode.js index 436613d63b..8769bda35a 100644 --- a/functions/xml/utf8_encode.js +++ b/functions/xml/utf8_encode.js @@ -1,4 +1,4 @@ -function utf8_encode(argString) { +function utf8_encode (argString) { // discuss at: http://phpjs.org/functions/utf8_encode/ // original by: Webtoolkit.info (http://www.webtoolkit.info/) // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) @@ -15,56 +15,56 @@ function utf8_encode(argString) { // returns 1: 'Kevin van Zonneveld' if (argString === null || typeof argString === 'undefined') { - return ''; + return '' } // .replace(/\r\n/g, "\n").replace(/\r/g, "\n"); - var string = (argString + ''); + var string = (argString + '') var utftext = '', - start, end, stringl = 0; + start, end, stringl = 0 - start = end = 0; - stringl = string.length; + start = end = 0 + stringl = string.length for (var n = 0; n < stringl; n++) { - var c1 = string.charCodeAt(n); - var enc = null; + var c1 = string.charCodeAt(n) + var enc = null if (c1 < 128) { - end++; + end++ } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode( (c1 >> 6) | 192, (c1 & 63) | 128 - ); + ) } else if ((c1 & 0xF800) != 0xD800) { enc = String.fromCharCode( (c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128 - ); + ) } else { // surrogate pairs if ((c1 & 0xFC00) != 0xD800) { - throw new RangeError('Unmatched trail surrogate at ' + n); + throw new RangeError('Unmatched trail surrogate at ' + n) } - var c2 = string.charCodeAt(++n); + var c2 = string.charCodeAt(++n) if ((c2 & 0xFC00) != 0xDC00) { - throw new RangeError('Unmatched lead surrogate at ' + (n - 1)); + throw new RangeError('Unmatched lead surrogate at ' + (n - 1)) } - c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000; + c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000 enc = String.fromCharCode( (c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128 - ); + ) } if (enc !== null) { if (end > start) { - utftext += string.slice(start, end); + utftext += string.slice(start, end) } - utftext += enc; - start = end = n + 1; + utftext += enc + start = end = n + 1 } } if (end > start) { - utftext += string.slice(start, stringl); + utftext += string.slice(start, stringl) } - return utftext; -} \ No newline at end of file + return utftext +}