Skip to content

Commit

Permalink
probably naive array.sort method
Browse files Browse the repository at this point in the history
  • Loading branch information
prakashk committed Apr 24, 2013
1 parent a3dfb52 commit e391912
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/scala/org/moe/runtime/builtins/ArrayClass.scala
Expand Up @@ -367,6 +367,20 @@ object ArrayClass {
)
)

arrayClass.addMethod(
new MoeMethod(
"sort",
new MoeSignature(List(new MoeOptionalParameter("&sorter"))),
env,
(e) => // self(e).sort(r, e.getAs[MoeCode]("&sorter"))
e.get("&sorter") match {
case Some(none: MoeUndefObject) => self(e).sort(r, None)
case Some(sorter: MoeCode) => self(e).sort(r, Some(sorter))
case _ => self(e).sort(r, None)
}
)
)

/**
* List of Methods to support:
* - delete ($index | @indicies)
Expand Down
Expand Up @@ -187,6 +187,14 @@ class MoeArrayObject(
r.NativeObjects.getHash(categorized)
}

def sort (r: MoeRuntime, sorter: Option[MoeCode]): MoeArrayObject = {
val s = sorter match {
case Some(code) => (a: MoeObject, b: MoeObject) => code.execute(new MoeArguments(List(a, b))).unboxToInt.get < 0
case None => (a: MoeObject, b: MoeObject) => a.unboxToString.get < b.unboxToString.get
}
r.NativeObjects.getArray(array sortWith s)
}

// equality
def equal_to (r: MoeRuntime, that: MoeArrayObject): MoeBoolObject =
r.NativeObjects.getBool(
Expand Down
11 changes: 11 additions & 0 deletions src/test/scala/org/moe/parser/ArrayMethodTestSuite.scala
Expand Up @@ -198,4 +198,15 @@ class ArrayMethodTestSuite extends FunSuite with BeforeAndAfter with ParserTestU
triples.length should be (1)
triples(0).unboxToInt.get should equal (3)
}

test("... basic test with array.sort -- no sorter") {
val result = interpretCode("""[2, 7, 10, 3, 4, 1].sort.join(",")""")
result.unboxToString.get should equal("1,10,2,3,4,7")
}

test("... basic test with array.sort -- numeric sorter") {
val result = interpretCode("""[2, 7, 10, 3, 4, 1].sort(-> ($a, $b) { $a <=> $b }).join(",")""")
result.unboxToString.get should equal("1,2,3,4,7,10")
}

}

0 comments on commit e391912

Please sign in to comment.