Created
February 4, 2013 05:32
-
-
Save ritalin/4705176 to your computer and use it in GitHub Desktop.
alternative idea for toDictionary implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Ginq; | |
require_once "PHPUnit/Framework/IncompleteTestError.php"; | |
require_once dirname(dirname(__FILE__)) . "/src/Ginq.php"; | |
class GinqTest2 extends \PHPUnit_Framework_TestCase { | |
public static function main() | |
{ | |
require_once "PHPUnit/TextUI/TestRunner.php"; | |
$suite = new \PHPUnit_Framework_TestSuite("GinqTest2"); | |
$result = \PHPUnit_TextUI_TestRunner::run($suite); | |
} | |
/** | |
* testGetIterator(). | |
*/ | |
public function testToDictionary() { | |
$source = array( | |
array(1, "aaa"), array(2, "aaa"), array(3, "bbb"), array(4, "aaa") | |
); | |
$expected = array( | |
"aaa" => array(1, 2, 4), | |
"bbb" => array(3) | |
); | |
$groups = \Ginq::from($source) | |
->groupBy( | |
function ($v) { return $v[1]; }, | |
function ($v) { return $v[0]; } | |
) | |
; | |
$actual = $this | |
->toDictionary( | |
$groups, | |
function ($group, $k) { return $k; }, | |
function ($group, $k) { return $group->toArray(); } | |
) | |
; | |
var_dump($actual);exit; | |
} | |
public function toDictionary(\Ginq $ginq, $keySelector, $valueSelector = null) { | |
if (is_null($valueSelector)) { | |
$valueSelector = function ($v, $k) { return $v; }; | |
} | |
return $ginq->fold( | |
array(), | |
function ($acc, $v, $k) use($keySelector, $valueSelector) { | |
// 必要ならここで、二重キーのチェック | |
$acc[$keySelector($v, $k)] = $valueSelector($v, $k); | |
return $acc; | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment