Browse Source

utils: Optimized arrayMax/arrayMin functions

subsystem: utils

It's generally faster to iterate arrays in forward direction by allowing
the Javascript runtimes to perform better optimizations.

Unit tests were also included.
alejandro 8 years ago
parent
commit
a6773e63c0
3 changed files with 41 additions and 13 deletions
  1. 18 10
      src/utils.js
  2. 1 0
      test/Three.Unit.js
  3. 22 3
      test/unit/src/utils.js

+ 18 - 10
src/utils.js

@@ -1,14 +1,17 @@
-// http://stackoverflow.com/questions/1669190/javascript-min-max-array-values/13440842#13440842
-
 function arrayMin( array ) {
+	if ( array.length === 0 ) {
+
+		return Infinity;
+
+	}
 
-	var length = array.length, min = Infinity;
+	var min = array[ 0 ];
 
-	while ( length -- ) {
+	for ( var i = 1; i < array.length; ++ i ) {
 
-		if ( array[ length ] < min ) {
+		if ( array[ i ] < min ) {
 
-			min = array[ length ];
+			min = array[ i ];
 
 		}
 
@@ -19,14 +22,19 @@ function arrayMin( array ) {
 }
 
 function arrayMax( array ) {
+	if ( array.length === 0 ) {
+
+		return - Infinity;
+
+	}
 
-	var length = array.length, max = - Infinity;
+	var max = array[ 0 ];
 
-	while ( length -- ) {
+	for ( var i = 1; i < array.length; ++ i ) {
 
-		if ( array[ length ] > max ) {
+		if ( array[ i ] > max ) {
 
-			max = array[ length ];
+			max = array[ i ];
 
 		}
 

+ 1 - 0
test/Three.Unit.js

@@ -3,6 +3,7 @@
 import '../src/polyfills.js';
 export * from '../src/constants.js';
 export * from '../src/Three.Legacy.js';
+export * from '../src/utils.js';
 
 //src/animation
 export { AnimationAction } from '../src/animation/AnimationAction.js';

+ 22 - 3
test/unit/src/utils.js

@@ -1,6 +1,25 @@
 /**
- * @author TristanVALCKE / https://github.com/TristanVALCKE
+ * @author alemures / https://github.com/alemures
  */
 
-//Todo
-console.warn("Todo: Unit tests of Utils")
+QUnit.module( 'utils' );
+
+QUnit.test( 'arrayMax' , function( assert ) {
+
+	assert.equal( THREE.arrayMax( [] ), - Infinity );
+	assert.equal( THREE.arrayMax( [ 5 ] ), 5 );
+	assert.equal( THREE.arrayMax( [ 1, 5, 10 ] ), 10 );
+	assert.equal( THREE.arrayMax( [ 5, 1, 10 ] ), 10 );
+	assert.equal( THREE.arrayMax( [ 10, 5, 1 ] ), 10 );
+
+});
+
+QUnit.test( 'arrayMin' , function( assert ) {
+
+	assert.equal( THREE.arrayMin( [] ), Infinity );
+	assert.equal( THREE.arrayMin( [ 5 ] ), 5 );
+	assert.equal( THREE.arrayMin( [ 1, 5, 10 ] ), 1 );
+	assert.equal( THREE.arrayMin( [ 5, 1, 10 ] ), 1 );
+	assert.equal( THREE.arrayMin( [ 10, 5, 1 ] ), 1 );
+
+});