hgweb: properly iterate over arrays and objects in mercurial.js
authorAnton Shestakov <av6@dwimlabs.net>
Wed, 22 Nov 2017 21:15:44 +0800
changeset 35158 241da2de0e9f
parent 35157 ccf86aa5797c
child 35159 018aac6d7cb0
hgweb: properly iterate over arrays and objects in mercurial.js In JavaScript, using for-in loops to access every property of an object can have unexpected results when inheritance is involved. For example, if some piece of code adds a property (it may be a method too) to Object.prototype, then all for-in loops that iterate over keys of any object (also anything that inherits Object) will get that property on one of the iterations. To filter out such unexpected properties for-in loops have to use Object.hasOwnProperty() method. (This corresponds to "forin" option of jshint). In the two first cases "data" and "edges" are arrays, to it's simpler to just switch to using a regular for-with-a-counter loop.
mercurial/templates/static/mercurial.js
--- a/mercurial/templates/static/mercurial.js	Wed Nov 22 20:52:59 2017 +0800
+++ b/mercurial/templates/static/mercurial.js	Wed Nov 22 21:15:44 2017 +0800
@@ -95,7 +95,7 @@
 		var backgrounds = '';
 		var nodedata = '';
 
-		for (var i in data) {
+		for (var i = 0; i < data.length; i++) {
 
 			var parity = i % 2;
 			this.cell[1] += this.bg_height;
@@ -107,7 +107,7 @@
 			var fold = false;
 
 			var prevWidth = this.ctx.lineWidth;
-			for (var j in edges) {
+			for (var j = 0; j < edges.length; j++) {
 
 				line = edges[j];
 				start = line[0];
@@ -227,6 +227,7 @@
 		}
 
 		for (var unit in scales){
+			if (!scales.hasOwnProperty(unit)) { continue; }
 			var s = scales[unit];
 			var n = Math.floor(delta / s);
 			if ((n >= 2) || (s === 1)){