Skip to content

Commit

Permalink
Add singleOrNull to Listing
Browse files Browse the repository at this point in the history
  • Loading branch information
holzensp committed Oct 14, 2024
1 parent e039516 commit bd7c4c8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/stdlib/base/ListingNodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@ protected Object eval(VmListing self) {
}
}

public abstract static class singleOrNull extends ExternalPropertyNode {
@Specialization
protected Object eval(VmListing self) {
if (self.getLength() != 1) {
return VmNull.withoutDefault();
}
return VmUtils.readMember(self, 0L);
}
}

public abstract static class distinctBy extends ExternalMethod1Node {
@Child private ApplyVmFunction1Node applyNode = ApplyVmFunction1Node.create();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ facts {
module.catch(() -> base.single) == "Expected a single-element Listing."
new Listing { 42 }.single == 42
}

["singleOrNull"] {
empty.singleOrNull == null
base.singleOrNull == null
new Listing { 42 }.singleOrNull == 42
}
}

examples {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ facts {
true
true
}
["singleOrNull"] {
true
true
true
}
}
examples {
["length"] {
Expand Down
3 changes: 3 additions & 0 deletions stdlib/base.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -1903,6 +1903,9 @@ class Listing<out Element> extends Object {
/// ```
external single: Element

/// Same as [single] but returns [null] if this collection is empty or has more than one element.
external singleOrNull: Element?

/// Removes elements that are duplicates after applying [selector] from this listing, preserving the first occurrence.
///
/// Facts:
Expand Down

0 comments on commit bd7c4c8

Please sign in to comment.