meekframework/collection

v0.3.0 2018-05-28 09:14 UTC

This package is not auto-updated.

Last update: 2024-09-23 16:20:45 UTC


README

提供处理数据结构的实现和契约。

添加到任何集合实现中的第一个元素的类型将成为该集合实例的唯一支持类型。

使用标量类型的示例

$stack = new Meek\Collection\UnboundedStack();

$stack->push('1');  // All future push() operations will only accept the string data type.

$stack->push(2);    // Throws an InvalidArgumentException -> must be a string

使用对象的示例

class MyClass extends stdClass {}

$stack = new Meek\Collection\UnboundedStack();

$stack->push(new stdClass());   // All future push() operations will only accept instances of `stdClass`.
$stack->push(new MyClass());    // Works fine as `MyClass` is sub-classed from `stdClass`


$stack->push(new class {});    // Throws an InvalidArgumentException -> must be an instance of "stdClass"

用法

使用 UnboundedStack 反转字符串

$wordToReverse = 'dog';
$stack = new Meek\Collection\UnboundedStack(...str_split($wordToReverse));
$reversedWord = '';

while ($stack->size() > 0) {
    $reversedWord .= $stack->pop();
}

print $reversedWord;    // prints 'god'

使用 BoundedStack 跟踪历史记录

$numberOfActionsToKeepTrackOf = 3;
$stack = new Meek\Collection\BoundedStack($numberOfActionsToKeepTrackOf);

$perform = function ($action) use ($stack) {
    $stack->push($action);
    echo sprintf('perform: %s', $action);
};

$undo = function () use ($stack) {
    $action = $stack->pop();
    echo sprintf('undo: %s', $action);
};

$perform('select all');     // prints 'perform: select all'
$perform('copy');           // prints 'perform: copy'
$perform('paste');          // prints 'perform: paste'
$undo();                    // prints 'undo: paste'
$perform('paste');          // prints 'perform: paste'

try {
    $perform('select all');
} catch (OverflowException $e) {
    // clear history and keep going or notify user that history is full
}