changeset 88:3200ed24d29e

Re #2: Refactor API * Break out common code from Array Difference method * Make use of existing "index of" method
author IBBoard <dev@ibboard.co.uk>
date Sat, 21 Aug 2010 16:02:05 +0000
parents 90b9a3fe3c18
children cd96f6078edb
files Arrays.cs
diffstat 1 files changed, 24 insertions(+), 41 deletions(-) [+]
line wrap: on
line diff
--- a/Arrays.cs	Sat Aug 21 10:04:52 2010 +0000
+++ b/Arrays.cs	Sat Aug 21 16:02:05 2010 +0000
@@ -27,63 +27,46 @@
 
 		public static object[] Difference(object[] items1, object[] items2)
 		{
-			ArrayList arr = new ArrayList();
+			object[] diffObjs;
 
 
 			//Difference with as few loops as possible, so see which is shortest			
-			if (items1.Length > items2.Length)
+			if (items1.Length >= items2.Length)
 			{
 				//add everything from the first list
-				arr.AddRange(items1);
-
-				foreach (object obj in items2)
-				{
-					//Then for each item in the second list, if it is in the list remove it
-					if (arr.Contains(obj))
-					{
-						arr.Remove(obj);
-					}
-					else
-					{
-						//and if it isn't in the list add it
-						arr.Add(obj);
-					}
-				}
+				diffObjs = DoDifference(items1, items2);
 			}
 			else
 			{
-				//add everything from the second list
-				arr.AddRange(items2);
+				diffObjs = DoDifference(items2, items1);
+			}
+
+			return diffObjs;
+		}
 
-				foreach (object obj in items1)
+		private static object[] DoDifference(object[] longArray, object[] shortArray)
+		{
+			ArrayList arr = new ArrayList();
+			arr.AddRange(longArray);
+
+			foreach (object obj in shortArray)
+			{
+				if (arr.Contains(obj))
 				{
-					//Then for each item in the first list, if it is in the list remove it
-					if (arr.Contains(obj))
-					{
-						arr.Remove(obj);
-					}
-					else
-					{
-						//and if it isn't in the list add it
-						arr.Add(obj);
-					}
+					arr.Remove(obj);
+				}
+				else
+				{
+					arr.Add(obj);
 				}
 			}
-
+			
 			return arr.ToArray();
 		}
-
+		
 		public static int IndexOf(object[] items, object item)
 		{
-			for (int i = 0; i<items.Length; i++)
-			{
-				if (items[i].Equals(item))
-				{
-					return i;
-				}
-			}
-
-			return -1;
+			return Array.IndexOf(items, item);
 		}
 
 		public static bool Contains(object[] items, object item)