Files
spark/src/client/spark_core/utils/GlobalExtensions.cs
T

88 lines
3.5 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 string iremove_suffix(this string str, string suffix) {
if (str.EndsWith(suffix, StringComparison.CurrentCultureIgnoreCase))
str = str.Remove(str.Length - suffix.Length);
return str;
}
public static string if_null_or_empty(this string str, string default_value) =>
string.IsNullOrEmpty(str) ? default_value : str;
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
}
}
}
}
public static void sync_with_models<T, TModel>(this IList<T> target, IEnumerable<TModel> models, Func<TModel, T> add_factory, Func<T, TModel, T> update_factory) {
var model_list = models as IList<TModel> ?? models.ToList();
if (model_list.Count == 0) {
target.Clear();
} else {
int stop = Math.Min(target.Count, model_list.Count);
for (int i = 0; i < stop; i++) {
target[i] = update_factory(target[i], model_list[i]);
}
while (target.Count < model_list.Count) {
target.Add(add_factory(model_list[target.Count]));
}
while (model_list.Count < target.Count) {
target.RemoveAt(model_list.Count);
}
}
}
}
}