Created
October 7, 2011 00:41
-
-
Save k-holy/1269136 to your computer and use it in GitHub Desktop.
array_map() と ArrayIterator で FizzBuzz
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 Holy\Example; | |
require_once realpath(__DIR__ . '/lime.php'); | |
class Util | |
{ | |
public static function H($data, $callback=null) | |
{ | |
if (isset($data) && strcmp($data, '') != 0) { | |
if (isset($callback)) { | |
$data = call_user_func($callback, $data); | |
} | |
$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8'); | |
} | |
return $data; | |
} | |
} | |
class FizzBuzz | |
{ | |
public static function execute($var) | |
{ | |
return ($var % 3 * $var % 5) ? sprintf('%d', $var) | |
: ($var % 3 ? '' : 'Fizz') . ($var % 5 ? '' : 'Buzz'); | |
} | |
} | |
$source = highlight_file(__FILE__, true); | |
$title = 'array_map() と ArrayIterator で FizzBuzz'; | |
use Holy\Example\Util as U; | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title><?=U::H($title)?></title> | |
<style type="text/css"> | |
body {font-family:monospace;} | |
</style> | |
</head> | |
<body> | |
<h1><?=U::H($title)?></h1> | |
<pre> | |
<?php | |
// Test case | |
$t = new \lime_test(); | |
$t->is('1', FizzBuzz::execute(1)); | |
$t->is('Fizz', FizzBuzz::execute(3)); | |
$t->is('Fizz', FizzBuzz::execute(6)); | |
$t->is('Buzz', FizzBuzz::execute(5)); | |
$t->is('Buzz', FizzBuzz::execute(10)); | |
$t->is('FizzBuzz', FizzBuzz::execute(15)); | |
$t->is('FizzBuzz', FizzBuzz::execute(30)); | |
?> | |
</pre> | |
<ol> | |
<?php | |
// array_map() | |
echo implode("\n", array_map(function($var) { | |
return sprintf('<li>%s</li>', call_user_func(array('\Holy\Example\FizzBuzz', 'execute'), $var)); | |
}, range(1, 100))); | |
?> | |
</ol> | |
<hr /> | |
<?php | |
// ArrayIterator | |
class FizzBuzzIterator extends \ArrayIterator | |
{ | |
public function __construct($start, $end) | |
{ | |
parent::__construct(range($start, $end)); | |
} | |
public function current() | |
{ | |
return FizzBuzz::execute(parent::current()); | |
} | |
} | |
$iterator = new FizzBuzzIterator(1, 100); | |
?> | |
<ol> | |
<?php foreach ($iterator as $i) : ?> | |
<li><?=$i?></li> | |
<?php endforeach ?> | |
</ol> | |
<?=$source?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lime初めて使ってみたけど、こういうサンプルコードにぴったりな気がする。
html終了タグの後に"# Looks like everything went fine. "とか出るのはご愛嬌