Skip to content

Instantly share code, notes, and snippets.

View JohnMGant's full-sized avatar

Michael Gant JohnMGant

View GitHub Profile
@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)
}
@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 / 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 / AddArrayForLoop.js
Last active August 7, 2020 17:35
Adding an array of numbers in JavaScript using for loop
function Add(values) {
let sum = 0
const length = values.length
for (var i = 0; i < length; i++) {
sum += values[i]
}
return sum
}
static void Main() {
foreach (var line in TellJokeAboutMice())
{
Console.WriteLine(line);
}
}
private static IEnumerable<string> TellJokeAboutMice()
{
yield return "MR MICE.";
internal class EnumeratorAdder : IIntegerAdder
{
public int Add(int[] values)
{
IEnumerator<int> enumerator = values.AsEnumerable().GetEnumerator();
int sum = 0;
while (enumerator.MoveNext())
{
sum += enumerator.Current;
}
internal class ForEachLoopAdder : IIntegerAdder
{
public int Add(int[] values)
{
int sum = 0;
foreach (var value in values)
{
sum += value;
}
return sum;
@JohnMGant
JohnMGant / ArrayPointerAdder.cs
Last active June 26, 2020 20:02
Adds an array of integers using a point (don't do this!)
internal unsafe class ArrayPointerAdder : IIntegerAdder
{
public int Add(int[] values)
{
int sum = 0;
int count = values.Length;
fixed (int *p = values)
{
for (int i = 0; i < count; i++)
{
@JohnMGant
JohnMGant / GotoAdder.cs
Last active December 16, 2020 22:38
Adds an array of integers using goto (don't do this!)
internal class GotoAdder : IIntegerAdder
{
public int Add(int[] values)
{
int sum = 0;
int count = values.Length;
int index = 0;
BEGIN:
if (index == count) goto RETURN;
int value = values[index++];
@JohnMGant
JohnMGant / ForLoopAdder.cs
Last active June 26, 2020 20:04
Adds an array of integers using a for loop
internal class ForLoopAdder : IIntegerAdder
{
public int Add(int[] values)
{
int sum = 0;
int count = values.Length;
for (int i = 0; i < count; i++)
{
int value = values[i];
sum += value;