time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

main.js (1610B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MAIN //
     22 
     23 /**
     24 * Computes an absolute value of a signed 32-bit integer in two's complement format.
     25 *
     26 * ## Method
     27 *
     28 * -   Assume two's complement format.
     29 * -   Create a mask by applying a sign propagating right-shift. For negative integers, this results in all `1`'s. For nonnegative integers, this results in all `0`'s.
     30 * -   XOR the mask with `x`. For negative integers, this is the equivalent of a NOT. For nonnegative integers, this is a no-op.
     31 * -   Subtract the mask to recover the absolute value. For negative integers, this adds `1`, which is `-x` when using two's complement. For nonnegative integers, this subtracts `0`.
     32 *
     33 * @param {integer32} x - integer
     34 * @returns {integer32} absolute value
     35 *
     36 * @example
     37 * var v = labs( -10|0 );
     38 * // returns 10
     39 */
     40 function labs( x ) {
     41 	var mask;
     42 	var y;
     43 
     44 	y = x|0; // asm type annotation
     45 	mask = ( y >> 31 )|0; // asm type annotation
     46 	return ((y ^ mask) - mask)|0; // asm type annotation
     47 }
     48 
     49 
     50 // EXPORTS //
     51 
     52 module.exports = labs;