Skip to content

Commit a279583

Browse files
authored
Merge pull request #58 from xp-forge/feature/concat
Add `concat()`, returns a concatenation of the sequence and the given enumerable
2 parents 6784eef + f837ad1 commit a279583

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/main/php/util/data/Sequence.class.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,22 @@ public static function generate($supplier) {
9595
return new self($f());
9696
}
9797

98+
/**
99+
* Creates a new stream with an enumeration of elements
100+
*
101+
* @param ?iterable|util.XPIterator|function(): iterable $enumerable
102+
* @return self
103+
* @throws lang.IllegalArgumentException if type of elements argument is incorrect
104+
*/
105+
public function concat($enumerable) {
106+
$enumeration= Enumeration::of($enumerable);
107+
$f= function() use($enumeration) {
108+
yield from $this->elements;
109+
yield from $enumeration;
110+
};
111+
return new self($f());
112+
}
113+
98114
/**
99115
* Returns the first element of this stream, or an empty optional
100116
*

src/test/php/util/data/unittest/SequenceCreationTest.class.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,25 @@ public function passing_sequence_to_of_yields_itself() {
7373
public function multiple_arguments_supported_in_of(... $input) {
7474
$this->assertSequence([1, 2, 3, 4, 5, 6], Sequence::of(...$input));
7575
}
76+
77+
#[Test]
78+
public function concat() {
79+
$this->assertSequence(
80+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
81+
Sequence::of([1, 2, 3])->concat([4, 5, 6])->concat([7, 8, 9])
82+
);
83+
}
84+
85+
#[Test]
86+
public function concat_after_mapping() {
87+
$this->assertSequence(
88+
[2, 4, 6, 'EOF'],
89+
Sequence::of([1, 2, 3])->map(function($e) { return $e * 2; })->concat(['EOF'])
90+
);
91+
}
92+
93+
#[Test, Expect(IllegalArgumentException::class)]
94+
public function cannot_concat_non_enumerable() {
95+
Sequence::$EMPTY->concat('test');
96+
}
7697
}

0 commit comments

Comments
 (0)