Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad
Functions
Control Flow
Basic Language Features
Fundamentals

PHP Functions - Passing Variables by Reference

Normally, in PHP, variables are passed into functions by value only. In most cases, this is considered convenient for the (PHP) developer because the developer can actively modify the value passed into the function without having to worry that it might alter the value of the original variable being passed in:

// The Function
function foo($number) {
  $number = $number ** 2; // Here, I actively modify the value passed in before returning the result.
  return $number;
}

// The Original Variable
$my_var = 6;

// The New Variable (created by passing the original variable into function 'foo')
$my_new_var = foo($my_var);

// Now let's see what has happened to both variables
echo "$my_var\n"; // 6 (The value of the original variable remains the same after being passed into the function)
echo "$my_new_var\n"; // 36 (as expected)

In other languages such as Javascript, actively modifying the parameter passed in would alter the value of the original variable.

However, this behaviour may not always be desirable. Suppose we wanted to actively modify the variable passed in (for whatever reason). Then we could specify in the function definition that the variable is to be passed by reference. By doing so, if the parameter inside the function is assigned a new value, it will modify the original variable.

E.g.

// The Functions
function increment(&$number) {
  // In PHP, the ampersand is used before the parameter name to specify that the variable is to be passed in by reference, not by value
  $number++;
}
function decrement(&$number) {
  $number--;
}

// The Variable
$a = 10;
increment($a);
echo "$a\n"; // 11
increment($a);
echo "$a\n"; // 12
decrement($a);
decrement($a);
decrement($a);
echo "$a\n"; // 9
// The Functions
function increment(&$number) {
  // In PHP, the ampersand is used before the parameter name to specify that the variable is to be passed in by reference, not by value
  $number++;
}
function decrement(&$number) {
  $number--;
}
function twice(&$number) {
  $number = $number * 2;
}
function halve(&$number) {
  $number = $number / 2;
}

// The Variable
$a = 10;
increment($a);
echo "$a\n"; // 11
increment($a);
echo "$a\n"; // 12
decrement($a);
decrement($a);
decrement($a);
echo "$a\n"; // 9
twice($a);
twice($a);
echo "$a\n"; // 36
halve($a);
echo "$a\n"; // 18
Testing

Code from the official page

class MyTestCase extends GroovyTestCase {

    void testAssertions() {
        assertTrue(1 == 1)
        assertEquals("test", "test")

        def x = "42"
        assertNotNull "x must not be null", x
        assertNull null

        assertSame x, x
    }

}
Fundamentals

pow => powerOf => x^y

A simple function I use all the time because I cannot be bothered to remember how to use Math.Pow(). Also, who uses double anyway? Pshh, real men use BigInteger.

using System.Numerics;

public class basic 
{
    public static BigInteger pow(long down, long up)
    {
        BigInteger power = 1;
        for (long i = 0; i < up; i++)
          power *= down;
        return power;
    }
}

JSTester - A custom Javascript TDD Framework

My attempt at creating a custom TDD framework in Javascript that runs on any browser.

This project can also be found on GitHub.

var Test = {
  // Key Properties
  passes: 0,
  fails: 0,
  errors: 0,
  output: "",
  // Test Output Method
  write: function (output) {
    document.getElementsByTagName("body")[0].innerHTML += output;
  },
  // Random Output Method
  randomNumber: function () {
    return ~~(101 * Math.random());
  },
  randomToken: function (length) {
    length = length || 10;
    var token = "";
    for (var i = 0; i < length; i++) {
      token += "abcdefghijklmnopqrstuvwxyz0123456789".split("")[~~(36 * Math.random())];
    }
    return token;
  },
  // Spec Methods
  describe: function (msg, fn) {
    var uniqId = this.randomToken();
    msg = msg || "The code to be tested";
    this.passes = this.fails = this.errors = 0;
    this.output = "<div id='console_" + uniqId + "' style='color:white;background-color:black;padding:10px;font-family:monospace'>";
    this.output += "<strong>" + msg + "</strong>";
    this.output += "<div id='describe_" + uniqId + "' style='margin-left:20px'>";
    var start = new Date().getTime();
    try {
      fn();
    } catch (e) {
      this.errors++;
      this.output += "<span style='color:red'>" + e + "</span>";
    }
    var dur = new Date().getTime() - start;
    this.output += "</div>";
    this.output += "<hr />";
    this.output += "<span style='color:lime'>" + this.passes + " Passes</span><br />";
    this.output += "<span style='color:red'>" + this.fails + " Fails</span><br />";
    this.output += "<span style='color:red'>" + this.errors + " Errors</span><br />";
    this.output += "Process took " + dur + "ms to complete<br />"
    this.output += "</div>";
    this.write(this.output + "<br />");
    document.getElementById("console_" + uniqId).style.border = "5px solid " + (this.passes > 0 && this.fails === 0 && this.errors === 0 ? "lime" : "red");
  },
  it: function (msg, fn) {
    msg = msg || "should pass the tests below";
    this.output += "<strong>" + msg + "</strong>";
    this.output += "<div style='margin-left:20px'>";
    try {
      fn();
    } catch (e) {
      this.errors++;
      this.output += "<span style='color:red'>" + e + "</span>";
    }
    this.output += "</div>";
  },
  // Basic Test Method
  expect: function (passed, msg, success) {
    msg = msg || "Value was not what was expected";
    success = success || "Test Passed";
    if (passed) {
      this.passes++;
      this.output += "<span style='color:lime'>" + success + "</span><br />";
    } else {
      this.fails++;
      this.output += "<span style='color:red'>" + msg + "</span><br />";
    }
  },
  // Assertion Methods
  assertEquals: function (actual, expected, msg, success) {
    msg = (msg || "Actual value did not match Expected") + " - Expected: " + expected + ", but instead got: " + actual;
    success = (success || "Test Passed") + " - Value === " + expected;
    this.expect(actual === expected, msg, success);
  },
  assertNotEquals: function (actual, unexpected, msg, success) {
    msg = (msg || "Unexpected value was returned") + " - Value was expected to not equal: " + unexpected;
    success = (success || "Test Passed") + " - Value !== " + unexpected;
    this.expect(actual !== unexpected, msg, success);
  },
  assertSimilar: function (actual, expected, msg, success) {
    msg = (msg || "Actual value did not match Expected") + " - Expected: " + JSON.stringify(expected) + ", but instead got: " + JSON.stringify(actual);
    success = (success || "Test Passed") + " - Value === " + JSON.stringify(expected);
    this.expect(JSON.stringify(actual) === JSON.stringify(expected), msg, success);
  },
  assertNotSimilar: function (actual, unexpected, msg, success) {
    msg = (msg || "Unexpected value was returned") + " - Value was expected to not equal: " + JSON.stringify(unexpected);
    success = (success || "Test Passed") + " - Value !== " + JSON.stringify(unexpected);
    this.expect(JSON.stringify(actual) !== JSON.stringify(unexpected), msg, success);
  },
  expectError: function (msg, fn, success) {
    var errorThrown = !1;
    msg = msg || "Expected error was not thrown";
    success = success || "Test Passed";
    try {
      fn();
    } catch (e) {
      errorThrown = true;
      this.output += e + "<br />";
    } finally {
      this.expect(errorThrown, msg, success);
    }
  },
  expectNoError: function (msg, fn, success) {
    var errorThrown = !1;
    msg = msg || "Unexpected error thrown";
    success = success || "Test Passed";
    try {
      fn();
    } catch (e) {
      errorThrown = true;
      msg += " - " + e;
    } finally {
      this.expect(!errorThrown, msg, success);
    }
  }
};

RubyTester - A custom Ruby TDD Framework

My attempt at creating a custom Ruby testing framework that executes in the command line. Can also be found on GitHub.

NOTE: Original class name was Test but it clashed with the name of the testing framework used here at Codewars so had to rename it.

class RubyTester
  def initialize
    @passes = 0
    @fails = 0
    @errors = 0
  end
  def describe msg, &block
    80.times do
      print "#"
      sleep 0.025
    end
    puts "\e[1mRubyTester\e[22m"
    sleep 1
    puts "\e[1mv1.0.0\e[22m"
    sleep 1
    puts "\e[1mAuthored by DonaldKellett\e[22m (https://github.com/DonaldKellett)"
    sleep 1
    @passes = 0
    @fails = 0
    @errors = 0
    print "Tests will execute in 3"
    sleep 1
    print " 2"
    sleep 1
    puts " 1"
    sleep 1
    puts "-" * 80
    puts "\e[1mDescribe: #{msg}\e[22m"
    start = Time.now
    begin
      yield
    rescue Exception => e
      @errors += 1
      puts "\e[31mError: #{e}\e[0m"
    end
    dur = ((Time.now - start) * 1000).round
    puts "-" * 80
    sleep 1
    puts "\e[32m#{@passes} Passed\e[0m"
    sleep 1
    puts "\e[31m#{@fails} Failed\e[0m"
    sleep 1
    puts "\e[31m#{@errors} Errors\e[0m"
    sleep 1
    puts "Process took #{dur}ms to complete"
    sleep 1
    puts "\e[1mThank you for using RubyTester :D\e[22m"
    puts "#" * 80
  end
  def it msg, &block
    puts "\e[1mIt: #{msg}\e[22m"
    begin
      yield
    rescue Exception => e
      @errors += 1
      puts "\e[31mError: #{e}\e[0m"
    end
  end
  def expect passed, msg = "Value was not what was expected", success = "Test Passed"
    if passed
      @passes += 1
      puts "\e[32m#{success}\e[0m"
    else
      @fails += 1
      puts "\e[31m#{msg}\e[0m"
    end
  end
  def assert_equals actual, expected, msg = "Actual value did not match expected", success = "Test Passed"
    self.expect actual == expected, msg + " - Expected: " + expected.to_s + ", but instead got: " + actual.to_s, success + " - Value == " + expected.to_s
  end
  def assert_not_equals actual, unexpected, msg = "Unexpected value returned", success = "Test Passed"
    self.expect actual != unexpected, msg + " - Value was expected to not equal: " + unexpected.to_s, success + " - Value != " + unexpected.to_s
  end
  def expect_error msg, &block
    error_thrown = false
    begin
      yield
    rescue Exception => e
      error_thrown = true
      puts "Expected error thrown: #{e}"
    end
    self.expect error_thrown, msg
  end
  def expect_no_error msg, &block
    error_thrown = false
    error_msg = "Error"
    begin
      yield
    rescue Exception => e
      error_thrown = true
      error_msg = e
    end
    self.expect !error_thrown, "#{msg} - #{e}"
  end
  def random_number
    rand 101
  end
  def random_token length = 10
    token_chars = "abcdefghijklmnopqrstuvwxyz0123456789".split ""
    token = ""
    length.times do
      token += token_chars[(36 * rand).floor]
    end
    token
  end
end
let beerSongVerse n =
    match n with
    | 0 -> "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"
    | 1 -> "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n"
    | 2 -> "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n"
    | _ -> System.String.Format("{0} bottles of beer on the wall, {0} bottles of beer.\nTake one down and pass it around, {1} bottles of beer on the wall.\n", n, n - 1)

let beerSong n m =
    [m .. n] |> List.rev |> List.map(fun x -> beerSongVerse x) |> String.concat("\n")
    
beerSong 99 0
let rec hello n =
    match n with
    | 0 -> ()
    | _ -> System.Console.WriteLine("hello"); hello (n - 1)
let add a b = a + b
let square x = x * x
let result = add 1 2 |> add 3 |> add 4 |> square

printfn result
const fn = (f) => (...args) => args.reduce((f, arg) => f(arg), f);

// ==================================

const sum = fn(a => b => c => (a + b + c));

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2)(3)); // 6
console.log(sum(1)(2)(3)); // 6

const doubleInc = sum(1)(1);
console.log(doubleInc(4)); // 6

Taking a look at testing capabilities...

Printing arguments: work in progress...

#include <cstddef>

template <class C>
bool hasSize(C&& xs, std::size_t n) {
  return xs.size() == n;
}