-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Surbhi Kanthed
committed
Jun 10, 2024
1 parent
86ab4eb
commit 2f7b18c
Showing
2 changed files
with
74 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import re | ||
import operator | ||
|
||
OPS = { | ||
'>=': operator.ge, | ||
'<=': operator.le, | ||
'>': operator.gt, | ||
'<': operator.lt, | ||
'=': operator.eq, | ||
} | ||
|
||
|
||
def parse_property_filter(filter_str): | ||
"""Parse a property filter string into a key, operator, and value.""" | ||
match = re.match(r'([^><=]+)([><=]+)(.+)', filter_str) | ||
if not match: | ||
raise ValueError(f"Invalid property filter format: {filter_str}") | ||
key, op_str, value_str = match.groups() | ||
return key, OPS[op_str], value_str | ||
|
||
|
||
def convert_value(value_str): | ||
"""Convert a value string to an appropriate type for comparison.""" | ||
try: | ||
return int(value_str) | ||
except ValueError: | ||
try: | ||
return float(value_str) | ||
except ValueError: | ||
return value_str | ||
|
||
|
||
def filter_nodes_by_properties(nodes, properties): | ||
"""Filter a list of nodes based on property filters.""" | ||
if not properties: | ||
return nodes | ||
property_filters = [] | ||
for prop in properties: | ||
key, op, value_str = parse_property_filter(prop) | ||
value = convert_value(value_str) | ||
property_filters.append((key, op, value)) | ||
|
||
filtered_nodes = [] | ||
for node in nodes: | ||
match = True | ||
for key, op, value in property_filters: | ||
if key not in node.properties: | ||
match = False | ||
break | ||
node_value = convert_value(node.properties.get(key, '')) | ||
if not op(node_value, value): | ||
match = False | ||
break | ||
if match: | ||
filtered_nodes.append(node) | ||
return filtered_nodes |
This file contains 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