» Javascript equivalent for PHP's abs

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: abs.

PHP abs

Description

abs - Absolute value

number abs ( mixed number)

Returns the absolute value of number.

Parameters

  • number

    The numeric value to process

Return Values

The absoulte value of number . If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Javascript abs

Source

This is the main source of the Javascript version of PHP's abs

function abs( mixed_number )  {
    // http://kevin.vanzonneveld.net
    // +   original by: _argos
    // +   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;
}

Examples

Currently there are 4 examples

Example 1

This is how you could call abs()
abs(4.2);
And that would return
4.2

Example 2

This is how you could call abs()
abs(-4.2);
And that would return
4.2

Example 3

This is how you could call abs()
abs(-5);
And that would return
5

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript
category: Programming - Javascript - PHP equivalents
read: 10,606 times

Add comment

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#12. Kevin on 13 April 2008

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

#11. Philip on 12 April 2008

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

#10. Jonas Raoni on 12 April 2008

Jonas RaoniA shorter version of this would be:

return Math.abs (n) || 0;

#9. Kevin on 02 April 2008

KevinPhilip: Good idea, I'll add it, thanks!

#8. Philip on 31 March 2008

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

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]);
}
  }
}

#7. Kevin on 31 January 2008

Kevin@ _argos: Nice work! Added!

#6. _argos on 31 January 2008

_argosHi Kevin I'm here again look this ports.

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 ) );
 
}

#5. _argos on 30 January 2008

_argos@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

#4. Kevin on 30 January 2008

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

#3. Karol Kowalski on 30 January 2008

Karol KowalskiI 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:

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

#2. Kevin on 30 January 2008

Kevin@ 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:

function abs( mixed_number )  {
    // +   original by: _argos
    return ( ( !isNaN ( mixed_number ) ) ? ( ( mixed_number < 0 ) ? ( mixed_number * -1 ) : mixed_number ) : 0 );
}

#1. Karol Kowalski on 30 January 2008

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

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
}