63 lines
2.3 KiB
C#
63 lines
2.3 KiB
C#
using bts;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace mbts {
|
|
public static class GlobalExtensions {
|
|
public static string Repeat(this string s, uint count) {
|
|
if (count == 0) return "";
|
|
if (count == 1) return s;
|
|
if (count == 2) return s + s;
|
|
StringBuilder sb = new StringBuilder();
|
|
for (int x = 0; x < count; ++x) {
|
|
sb.Append(s);
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
public static bool iequals(this string str, string comparand) =>
|
|
string.Equals(str, comparand, StringComparison.CurrentCultureIgnoreCase);
|
|
|
|
public static T choose<T>(this Random r, IEnumerable<T> range) {
|
|
var index = r.Next(0, range.Count());
|
|
return range.Skip(index).First();
|
|
}
|
|
|
|
|
|
//this overloaded declaration, (as opposed to one function with comp = null) allows observable_collection.sync_with to be passed into functions as a parameterless Action
|
|
public static void sync_with<T>(this IList<T> dest, IEnumerable<T> src) { dest.sync_with(src, EqualityComparer<T>.Default); }
|
|
public static void sync_with<T>(this IList<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
|
|
Log.notnull(dest);
|
|
if (src == null) {
|
|
dest.Clear();
|
|
return;
|
|
}
|
|
var srcList = src as IList<T> ?? src.ToList();
|
|
var changes = bts.utils.Diff.diff(dest, srcList, comp).ToList();
|
|
// Apply the diff
|
|
for(int i = 0; i < changes.Count; ++i) {
|
|
var c = changes[i];
|
|
// removes
|
|
for (var x = 0; x < c.deletedLeft; ++x) {
|
|
dest.RemoveAt(c.StartLeft);
|
|
}
|
|
// inserts
|
|
for (var x = 0; x < c.insertedRight; ++x) {
|
|
dest.Insert(c.StartLeft + x, srcList[c.StartRight + x]);
|
|
}
|
|
// Adjust start index of remaining changes
|
|
for (int ii = i + 1; ii < changes.Count; ++ii) {
|
|
var cc = changes[ii];
|
|
var delta = c.insertedRight - c.deletedLeft;
|
|
if (cc.StartLeft >= c.StartLeft) {
|
|
cc.StartLeft += delta;
|
|
changes[ii] = cc;//remember: struct
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
} |