Use PHP functions in JavaScript

JavaScript abs

Return the absolute value of the number

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
function abs (mixed_number)  {
    // Return the absolute value of the number  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/abs    // +   original by: Waldo Malqui Silva
    // +   improved by: Karol Kowalski
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // *     example 1: abs(4.2);    // *     returns 1: 4.2
    // *     example 2: abs(-4.2);
    // *     returns 2: 4.2
    // *     example 3: abs(-5);
    // *     returns 3: 5    // *     example 4: abs('_argos');
    // *     returns 4: 0
    return Math.abs(mixed_number) || 0;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
abs(4.2);

Should return

1
4.2

» Example 2

Running

1
abs(-4.2);

Should return

1
4.2

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have abs goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
4 Sep '09 Permalink

q  @ Jay: "Later" has arrived. We're now on GitHub!
http://github.com/kvz/phpjs

Some more info about the change here:
http://kevin.vanzonneveld.net/techblog/article/svn_to_git/

Gravatar
Kevin van Zonneveld
22 Mar '09 Permalink

q  @ Jay: I'm working on 1 github project and a.t.m. I do not find the speed satisfying. I imagine all that SSH traffic causes quite some load but git pull times of > 60 seconds are just not acceptable. Maybe later though! Thanks

Gravatar
Jay
6 Mar '09 Permalink

q  You should really consider putting this project up on GitHub.com, it would be a perfect fit. That way people could modify and improve the code, and then send you a pull request for you to merge their changes. It's a very nice way to develop open source projects.

Gravatar
Kevin van Zonneveld
15 Jan '09 Permalink

q  @ Paul: It was actually an issue in the exit function. Should be fixed now, thanks for letting us know!

Gravatar
Paul
15 Jan '09 Permalink

q  I downloaded php.namespaced.*.js at 2009-01-14 15:28 HST. There appears to be a space missing which is causing javascript errors. Search string "functionPropagation". I was able to resolve the error in php.namespaced.js and php.namespaced.min.js, but not php.namespaced.packed.js due to the packing operation.

BTW: This package is incredible!

Gravatar
Kevin van Zonneveld
12 Jan '09 Permalink

q  @ Nile: Hey Nile thanks for your contribution. Unfortunately there are a couple of issues with it:
- depends on an outside function: applyEncode
- does not support associative arrays (in terms of traversing)
- does not support index arrays, numbers, etc (in terms of encoding)

Please have a look here:
http://www.json.org/json2.js

The code is public domain, so maybe it's possible to modify it and use it in PHP.JS. We could look into that!

Gravatar
Nile
9 Jan '09 Permalink

q  json_encode
[CODE="Javascript"]
var arr = new Array('Hello');
var applyEncode = function(varIn){
return '{'+varIn+'}';
}
var json_encode = function(value){
var data = '';
for(i=0,endCount='';i<value.length;++i){
var endCount = (i!=value.length-1) ? ", " : "";
data += '"'+key(value[i])+'" : "'+value[key(value)]+'"'+endCount;
}
return applyEncode(data);
}
document.write(json_encode(arr));
[/CODE]

Gravatar
Reena
8 Sep '08 Permalink

q  Good

Gravatar
Kevin van Zonneveld
13 Apr '08 Permalink

q  @ Jonas Raoni: Thanks I'll update the function.
@ Philip: I'll update your name!

Gravatar
Philip
12 Apr '08 Permalink

q  Hey, just fyi... Philip and Philip Peterson are both me ;-)

Gravatar
Jonas Raoni
12 Apr '08 Permalink

q  A shorter version of this would be:

return Math.abs (n) || 0;

Gravatar
Kevin van Zonneveld
2 Apr '08 Permalink

q  Philip: Good idea, I'll add it, thanks!

Gravatar
Philip
31 Mar '08 Permalink

q  Dunno where this belongs, but how about this code for echo()?

[CODE="Javascript"]
function echo()
{
for(i=0;i<echo.arguments.length;i++)
{
if(document.body && document.body.innerHTML) {
document.body.innerHTML=document.body.innerHTML+echo.arguments[i];
} else {
document.write(echo.arguments[i]);
}
}
}
[/CODE]

Gravatar
Kevin van Zonneveld
31 Jan '08 Permalink

q  @ _argos: Nice work! Added!

Gravatar
_argos
31 Jan '08 Permalink

q  Hi Kevin I'm here again look this ports.

[CODE="Javascript"]
if ( defined ( 'CONSTANTE' ) ) {

console.log ( CONSTANTE );

}

function defined ( constant_name ) {

return ( ( window [ constant_name ] !== undefined ) ? true : false );

}



// -----

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

console.log ( range ( 0, 12 ) );



// [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

console.log ( range( 0, 100, 10 ) );



// ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

console.log ( range( 'a', 'i' ) );



// ['c', 'b', 'a'];

console.log ( range ('c', 'a' ) );



function range ( low, high, step ) {

var matrix = [];

var inival, endval, plus;

var walker = step || 1;

var chars = false;



if ( !isNaN ( low ) && !isNaN ( high ) ) {

inival = low;

endval = high;

} else if ( isNaN ( low ) && isNaN ( high ) ) {

chars = true;

inival = low.charCodeAt ( 0 );

endval = high.charCodeAt ( 0 );

} else {

inival = ( isNaN ( low ) ? 0 : low );

endval = ( isNaN ( high ) ? 0 : high );

}



plus = ( ( inival > endval ) ? false : true );



if ( plus ) {

while ( inival <= endval ) {

matrix.push ( ( ( chars ) ? String.fromCharCode ( inival ) : inival ) );

inival += walker;

}

} else {

while ( inival >= endval ) {

matrix.push ( ( ( chars ) ? String.fromCharCode ( inival ) : inival ) );

inival -= walker;

}

}



return matrix;

}



// -----

console.log ( strcmp ( 'waldo', 'Waldo' ) );

console.log ( strcmp ( 'Waldo', 'waldo' ) );

console.log ( strcmp ( 'waldo', 'waldo' ) );



function strcmp ( str1, str2 ) {

var size1 = str1.charCodeAt ( 0 );

var size2 = str2.charCodeAt ( 0 );



return ( ( size1 == size2 ) ? 0 : ( ( size1 > size2 ) ? 1 : -1 ) );

}
[/CODE]

Gravatar
_argos
30 Jan '08 Permalink

q  @Karol Kowalski : Hi, thanks for take the time to check my port, I make the same tests like you, because I think that native functions always are more slower, so ever I use self hacks :p again thanxs for your time.

PS: Sorry for my badly English, but i have 4 years without use it :p

Gravatar
Kevin van Zonneveld
30 Jan '08 Permalink

q  @ Karol Kowalski: Awesome work Karol! I've updated the function. Thanks for putting in the extra effort. Greatly appreciated!

Gravatar
Karol Kowalski
30 Jan '08 Permalink

q  I run a test and it appeared that my function with Math.abs was around 40% more time consuming than yours. I tried to optimize it and ended up with 20% gain, and the code is still smaller and more readable. I tested it in Firefox, IE7, Safari and Opera with similar results. To see what's causing the overhead I run a function that would just return Math.abs, withoud checking for validity, still it was 10% slower than your function. It seems that Math.abs API is always slower than what can be accomplished with JS hack, a bit sad.

Still, for code readability I would sugget using the code of abs_math2.

Here's the test code:
[CODE="Javascript"]
if (!window['console']) {

console={}
console.log=alert
}

var start;

function abs_math2 ( mixed_number ) {
return ( ( isNaN ( mixed_number ) ) ? 0 : Math.abs ( mixed_number ) );
}

function abs_math( mixed_number ) {
var abs=Math.abs( mixed_number );
return ( !isNaN ( abs ) ) ? abs : 0
}

function abs_cond( mixed_number ) {
return ( ( !isNaN ( mixed_number ) ) ? ( ( mixed_number < 0 ) ? ( mixed_number * -1 ) : mixed_number ) : 0 );
}


start=new Date();

for (var i=100000;i;i--) {

abs_cond(4.2);
abs_cond(-4.2);
abs_cond(-5);
abs_cond('_argos');
abs_cond(-Infinity);

}

console.log((new Date())-start)


start=new Date();

for (var i=100000;i;i--) {

abs_math(4.2);
abs_math(-4.2);
abs_math(-5);
abs_math('_argos');
abs_math(-Infinity);

}

console.log((new Date())-start)


start=new Date();

for (var i=100000;i;i--) {

abs_math2(4.2);
abs_math2(-4.2);
abs_math2(-5);
abs_math2('_argos');
abs_math2(-Infinity);

}

console.log((new Date())-start)


//my results
//Firefox 2.0.11
//1000
//1422
//1219


[/CODE]

Gravatar
Kevin van Zonneveld
30 Jan '08 Permalink

q  @ Karol Kowalski: Using native Javascript for this is probably best so I've updated the function. But I'm not totally certain that this is faster. Doesn't the Math libary have to be loaded or something? Can somebod shed a light on this?

For reference, this was the original by _argos:
[CODE="Javascript"]
function abs( mixed_number ) {
// + original by: _argos
return ( ( !isNaN ( mixed_number ) ) ? ( ( mixed_number < 0 ) ? ( mixed_number * -1 ) : mixed_number ) : 0 );
}
[/CODE]

Gravatar
Karol Kowalski
30 Jan '08 Permalink

q  Why not use native JS Math.abs for this. I believe this should be faster than conditional expressions.

[CODE="Javascript"]
function abs( mixed_number ) {
// http://kevin.vanzonneveld.net
// + original by: _argos
// * example 1: abs(4.2);
// * returns 1: 4.2
// * example 2: abs(-4.2);
// * returns 2: 4.2
// * example 3: abs(-5);
// * returns 3: 5
// * example 4: abs('_argos');
// * returns 4: 0

var abs=Math.abs( mixed_number )
return ( !isNaN ( abs) ) ? abs : 0
}
[/CODE]


Contribute a New function

More functions

In this category

» abs
acos
acosh
asin
asinh
atan
atan2
atanh
base_convert
bindec
ceil
cos
cosh
decbin
dechex
decoct
deg2rad
exp
expm1
floor
fmod
getrandmax
hexdec
hypot
is_finite
is_infinite
is_nan
lcg_value
log
log10
log1p
max
min
mt_getrandmax
mt_rand
octdec
pi
pow
rad2deg
rand
round
sin
sinh
sqrt
tan
tanh

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !