Skip to content

Instantly share code, notes, and snippets.

View JohnMGant's full-sized avatar

Michael Gant JohnMGant

View GitHub Profile
@JohnMGant
JohnMGant / AddArrayForEachLoop.js
Last active August 7, 2020 17:34
Adding an array of integers in JavaScript using for..of
function Add(values) {
let sum = 0
for (var value of values) {
sum += value
}
return sum
}
@JohnMGant
JohnMGant / AddArrayForEachLoop2.js
Created August 7, 2020 17:38
Add an array of integers in JavaScript using array.forEach
function Add(values) {
let sum = 0
values.forEach(val => sum += val)
return sum
}
@JohnMGant
JohnMGant / AddArrayReduce.js
Created August 7, 2020 17:44
Add an array of integers using Reduce
function Add(values) {
return values.reduce((sum, val) => sum += val)
}
internal class LinqAggregateAdder : IIntegerAdder
{
public int Add(int[] values) => values.Aggregate((sum, val) => sum += val);
}
@JohnMGant
JohnMGant / LinqSumAdder.cs
Created August 7, 2020 18:13
Adds an array of integers in C# using Sum
internal class LinqSumAdder : IIntegerAdder
{
public int Add(int[] values) => values.Sum();
}
@JohnMGant
JohnMGant / RecursiveAdder.fs
Created October 2, 2020 18:41
Adding an array of integers in F#
let addInts ints =
let rec loop list acc =
match list with
| head :: tail -> loop tail (acc + head)
| [] -> acc
loop ints 0
@JohnMGant
JohnMGant / ArrayHeadTailAdder.cs
Created October 2, 2020 18:48
Add an array of integers in C# using recursion and arrays
internal class ArrayHeadTailAdder : IIntegerAdder
{
//This will fail with large arrays
public int Add(int[] values)
{
var (head, tail) = GetHeadAndTail(values);
return AddImplentation(head, tail);
}
internal class LinqHeadTailAdder : IIntegerAdder
{
private const int maxSupportedLength = 10000;
public int Add(int[] values)
{
if (values.Length > maxSupportedLength)
{
throw new NotSupportedException($"Max supported length is {maxSupportedLength}");
internal unsafe class PointerHeadTailAdder : IIntegerAdder
{
public int Add(int[] values)
{
fixed (int* head = values)
{
return AddImplementation(head, values.Length);
}
}
internal static class ExtensionMethods
{
public static bool TryDequeue<T>(this Queue<T> queue, out T result)
{
result = default;
if (queue == null || !queue.Any())
{
return false;
}
result = queue.Dequeue();