From 449131a516f38e4816905c7db433e92287e20e08 Mon Sep 17 00:00:00 2001 From: Marc Jansen Date: Fri, 9 Oct 2015 23:04:00 +0200 Subject: [PATCH 1/2] Use MDN polyfill for Math.cosh This commit replaces the current implementation of ol.math.cosh with the reference implementation of the Mozilla developer network. This method only has one call to the Math.exp-function compared to two in the original implementation. See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/cosh --- src/ol/math.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ol/math.js b/src/ol/math.js index c0244bda01..22e5c0fca2 100644 --- a/src/ol/math.js +++ b/src/ol/math.js @@ -21,7 +21,8 @@ ol.math.clamp = function(value, min, max) { * @return {number} Hyperbolic cosine of x. */ ol.math.cosh = function(x) { - return (Math.exp(x) + Math.exp(-x)) / 2; + var y = Math.exp(x); + return (y + 1 / y) / 2; }; From cd99d44704946519a82d22c89c08aac08e49263b Mon Sep 17 00:00:00 2001 From: Marc Jansen Date: Fri, 9 Oct 2015 23:27:02 +0200 Subject: [PATCH 2/2] Use Math.cosh of ES6/2015 if available --- src/ol/math.js | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/ol/math.js b/src/ol/math.js index 22e5c0fca2..dfd6e47673 100644 --- a/src/ol/math.js +++ b/src/ol/math.js @@ -17,13 +17,30 @@ ol.math.clamp = function(value, min, max) { /** + * Return the hyperbolic cosine of a given number. The method will use the + * native `Math.cosh` function if it is available, otherwise the hyperbolic + * cosine will be calculated via the reference implementation of the Mozilla + * developer network. + * * @param {number} x X. * @return {number} Hyperbolic cosine of x. */ -ol.math.cosh = function(x) { - var y = Math.exp(x); - return (y + 1 / y) / 2; -}; +ol.math.cosh = (function() { + // Wrapped in a iife, to save the overhead of checking for the native + // implementation on every invocation. + var cosh; + if ('cosh' in Math) { + // The environment supports the native Math.cosh function, use it… + cosh = Math.cosh; + } else { + // … else, use the reference implementation of MDN: + cosh = function(x) { + var y = Math.exp(x); + return (y + 1 / y) / 2; + }; + } + return cosh; +}()); /**