API extension

Former Member
Former Member
I would like to see a sort method for dictionary and arrays,
and a cpuUsage attribute for System.Stats.
  • Dictionaries can't be sorted. They are a hash container, so by definition the entries cannot be sorted. Additionally, since MonkeyC is duck typed, comparing objects of various types is not something that is easily done. i.e., you can put a Number, a String and a Dictionary into an array... how do you sort that array?

    If you want to sort an array where you know the type of the objects in the array, and can compare them, you can do it pretty easily.

    // sorts the input array in place. this will be expensive for long arrays.
    function bubble_sort(array) {
    for (var i = 0; i < array.size(); ++i) {
    for (var j = i; j < array.size(); ++j) {
    if (array[j] < array) {
    var tmp = array;
    array= array[j];
    array[j] = tmp;
    }
    }
    }
    }
    [/code]
  • Note that the above {{bubble_sort}} will sort an array of comparable objects. i.e., the following code will work...

    var f = [ 3, 4.0d, 1l, 2, 7, 9, 0.0, -1, -5, 0, 6 ];

    Sys.println(f);
    bubble_sort(f);
    Sys.println(f);


    will produce...

    [3, Obj: 2084472, Obj: 2076328, 2, 7, 9, 0.000000, -1, -5, 0, 6]
    [-5, -1, 0.000000, 0, Obj: 2076328, 2, 3, Obj: 2084472, 6, 7, 9]


    Unfortunately, since MonkeyC doesn't allow you to compare strings, you can't really sort an array that contains strings at all. If you wanted to compare objects of non-primitive types (say two Position objects, or Dictionaries), you could modify bubble_sort to take a method to use to compare objects.
  • Former Member
    Former Member over 10 years ago
    You can compare strings.

    var a = "same";
    var b = "same";

    if(a.equals(b)){
    Sys.println("Strings match");
    }
    else {
    Sys.println("Strings don't match");
    }
  • You can compare strings for equality, but that doesn't do diddly if you want to sort.