Documentation
Utility Functions
General purpose helpers for common tasks.
General purpose utility functions for common tasks.
identity()
Returns the value unchanged
Implementation
Simply returns the input value
Example
same = UniCoreFW.identity("hello")
Expected output: "hello"
Source Code
def identity(value):
return value
times()
Calls a function n times, passing the iteration index
Implementation
Uses list comprehension to collect results
Example
results = UniCoreFW.times(3, lambda i: i * 2)
Expected output: [0, 2, 4]
Source Code
def times(n, func):
return [func(i) for i in range(n)]
unique_id()
Generates a unique identifier with optional prefix
Implementation
Uses a counter to ensure uniqueness
Example
id1 = UniCoreFW.unique_id("user_")
Expected output: "user_1"
Source Code
def unique_id(prefix=""):
UniCoreFW._id_counter += 1
return f"{prefix}{UniCoreFW._id_counter}"
escape()
Escapes HTML characters in a string
Implementation
Uses character mapping for safe HTML
Example
escaped = UniCoreFW.escape("<script>alert('XSS')</script>")
Expected output: <script>alert('XSS')</script>
Source Code
def escape(string):
escape_map = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`",
}
return "".join(escape_map.get(c, c) for c in string)
start_case()
Convert a string into Start Case: - Splits on spaces, punctuation, and camelCase - Capitalizes each word (preserves ALLCAPS words) - Drops apostrophes
Implementation
Args: string: The input string
Returns:
The Start Cased string
Example
start_case("helloWorld_test")
Expected output: "Hello World Test"
Source Code
def start_case(string: str) -> str:
if string is None:
return ""
s = str(string).strip()
if not s:
return ""
# camelCase splits
s = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", s)
s = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", s)
# drop apostrophes
s = s.replace("'", "")
# non-alphanumerics → spaces
s = re.sub(r"[^A-Za-z0-9]+", " ", s)
words = [w for w in s.split(" ") if w]
def _cap(w):
return w.upper() if w.isupper() else w.lower().capitalize()
return " ".join(_cap(w) for w in words)
split()
Split a string into parts.
Implementation
-
split(s) → s.split() (on whitespace)
- split(s, "") or (s, None) → list(s) (every char)
- split(s, sep) → s.split(sep)
Args: args[0]: the string args[1] (optional): the separator
Returns: A list of substrings
Example
split("foo bar baz")
Expected output: ["foo", "bar", "baz"]
Source Code
def split(*args) -> List[str]:
if not args or args[0] is None:
return []
s = str(args[0])
if len(args) == 1:
# default: whitespace
return [w for w in s.split() if w]
sep = args[1]
if sep is None or sep == "":
return list(s) if s else []
return s.split(sep)
number_format()
Format a number with grouped thousands and fixed decimals.
Implementation
Args: value: The number to format precision: Number of decimal places decimal_sep: Character for the decimal point thousands_sep: Character for the thousands grouping
Returns:
The formatted number string, or "" if invalid
Example
number_format(1234567.89)
Expected output: "1,234,567.89"
Source Code
def number_format(
value: Any,
precision: int = 0,
decimal_sep: str = ".",
thousands_sep: str = ","
) -> str:
if not isinstance(value, (int, float)) or not math.isfinite(value):
return ""
# Round to the given precision
fmt = f"{{:,.{precision}f}}"
result = fmt.format(value)
# Python always uses ',' for thousands and '.' for decimal
if thousands_sep != ",":
result = result.replace(",", "TMP")
if decimal_sep != ".":
result = result.replace(".", decimal_sep)
if thousands_sep != ",":
result = result.replace("TMP", thousands_sep)
return result
unescape()
Unescapes HTML entities in a string
Implementation
Reverses escape mappings
Example
unescaped = UniCoreFW.unescape("<div>")
Expected output: <div>
Source Code
def unescape(string):
unescape_map = {
"&": "&",
"<": "<",
">": ">",
""": '"',
"'": "'",
"`": "`",
}
for key, value in unescape_map.items():
string = string.replace(key, value)
return string
series_phrase_serial()
Join a sequence into a human-readable series with an Oxford comma
for 3+ items, even if the user supplied a custom last_sep without
the comma.
Implementation
Args: items: Iterable of values (None→empty list) sep: Separator between items (e.g. ", " or ";") last_sep: Separator before last item (e.g. ", and " or " or ")
Returns:
A string like "a, b, c, and d" or with custom separators.
Example
series_phrase_serial(["foo","bar","baz","qux"],", "," or ")
Expected output: "foo, bar, baz, or qux"
Source Code
def series_phrase_serial(
items: Any,
sep: Any = ", ",
last_sep: Any = ", and "
) -> str:
seq = [str(x) for x in (items or []) if x is not None and str(x) != ""]
n = len(seq)
if n == 0:
return ""
if n == 1:
return seq[0]
if n == 2:
# for two items always use plain " and "
return seq[0] + " and " + seq[1]
# n >= 3: enforce Oxford comma
sep_str = "" if sep is None else str(sep)
last_str = "" if last_sep is None else str(last_sep)
# if user‐supplied last_sep doesn’t already start with the sep’s punctuation,
# prefix it so we get the comma (or semicolon, etc.) back.
lead = sep_str.rstrip()
if last_str.strip() and not last_str.lstrip().startswith(lead):
last_str = lead + last_str
return sep_str.join(seq[:-1]) + last_str + seq[-1]
now()
Returns the current timestamp in milliseconds
Implementation
Uses time.time() with conversion to milliseconds
Example
timestamp = UniCoreFW.now()
Expected output: 1616458643123 (example millisecond timestamp)
Source Code
def now():
return int(time.time() * 1000)
enhanced_debounce()
Enhanced debounce with max_wait support for better control.
Implementation
Args: func: The function to debounce wait: The delay in milliseconds max_wait: Maximum time to wait before forcing execution
Returns:
A debounced function with max_wait capability
Example
def api_call():
return "Called!"
debounced = enhanced_debounce(api_call, 100, max_wait=500)
# Function will execute after 100ms of inactivity or 500ms max
Expected output: ``
Source Code
def enhanced_debounce(func: Callable, wait: int, max_wait: Optional[int] = None) -> Callable:
_validate_callable(func)
wait_seconds = wait / 1000.0
max_wait_seconds = max_wait / 1000.0 if max_wait else None
timer = None
max_timer = None
lock = threading.Lock()
first_call_time = [None]
result = [None]
def debounced(*args, **kwargs):
nonlocal timer, max_timer
current_time = now()
def execute():
nonlocal timer, max_timer
with lock:
if timer:
timer.cancel()
if max_timer:
max_timer.cancel()
timer = max_timer = None
first_call_time[0] = None
result[0] = func(*args, **kwargs)
return result[0]
with lock:
# Cancel existing timer
if timer:
timer.cancel()
# Set first call time if not set
if first_call_time[0] is None:
first_call_time[0] = current_time # type: ignore
result[0] = func(*args, **kwargs) # Store initial result
# Set max wait timer if specified
if max_wait_seconds:
max_timer = threading.Timer(max_wait_seconds, execute)
max_timer.start()
# Set regular debounce timer
timer = threading.Timer(wait_seconds, execute)
timer.start()
return result[0]
return _copy_function_metadata(debounced, func)
enhanced_partial_right()
Enhanced partial_right application with _argcount tracking.
Implementation
Args: func: The function to partially apply from right bound_args: Arguments to bind to the right *bound_kwargs: Keyword arguments to bind
Returns:
A partially applied function with _argcount metadata
Example
def divide(a, b, c):
return a / b / c
divide_by_two = enhanced_partial_right(divide, 2)
divide_by_two(8, 2) # 8 / 2 / 2
Expected output: 2.0
Source Code
def enhanced_partial_right(func: Callable, *bound_args, **bound_kwargs) -> Callable:
_validate_callable(func)
def wrapper(*args, **kwargs):
return func(*args, *bound_args, **{**kwargs, **bound_kwargs})
# Calculate remaining argument count
original_arity = func.__code__.co_argcount
wrapper._argcount = max(0, original_arity - len(bound_args)) # type: ignore
return _copy_function_metadata(wrapper, func)
enhanced_partial()
Enhanced partial application with _argcount tracking.
Implementation
Args: func: The function to partially apply bound_args: Arguments to bind *bound_kwargs: Keyword arguments to bind
Returns:
A partially applied function with _argcount metadata
Example
def multiply(a, b, c):
return a * b * c
times_two = enhanced_partial(multiply, 2)
times_two(3, 4)
Expected output: 24
Source Code
def enhanced_partial(func: Callable, *bound_args, **bound_kwargs) -> Callable:
_validate_callable(func)
def wrapper(*args, **kwargs):
return func(*(bound_args + args), **{**bound_kwargs, **kwargs})
# Calculate remaining argument count
original_arity = func.__code__.co_argcount
wrapper._argcount = max(0, original_arity - len(bound_args)) # type: ignore
return _copy_function_metadata(wrapper, func)
enhanced_curry_right()
Enhanced curry_right with explicit arity support and _argcount tracking.
Implementation
Args: func: The function to curry from right to left arity: Explicit arity (if None, inferred from function)
Returns:
A curried function that collects arguments from right to left
Example
def subtract(a, b, c):
return a - b - c
curried_sub = enhanced_curry_right(subtract)
result = curried_sub(1)(2)(10) # 10 - 2 - 1
result
Expected output: 7
Source Code
def enhanced_curry_right(func: Callable, arity: Optional[int] = None) -> Callable:
_validate_callable(func)
if arity is None:
arity = func.__code__.co_argcount
def curried(*args):
if len(args) >= arity:
# Collect the right number of args and pass them in normal order
collected_args = args[-arity:] if len(args) > arity else args
return func(*collected_args)
def next_curry(*more_args):
# Prepend new args to existing args (right-to-left collection)
return curried(*(more_args + args))
# Track remaining arguments needed
next_curry._argcount = arity - len(args) # type: ignore
return _copy_function_metadata(next_curry, func)
curried._argcount = arity # type: ignore
return _copy_function_metadata(curried, func)
memoize()
Caches the results of function calls
Implementation
Uses functools.lru_cache decorator
Example
@UniCoreFW.memoize
def fibonacci(n):
if n <= 1: return n
return fibonacci(n-1) + fibonacci(n-2)
Expected output: Function with cached results
Source Code
def memoize(func):
return lru_cache(maxsize=None)(func)
template()
Renders a template with variables from a context
Implementation
Security-enhanced template engine with context validation
Example
result = UniCoreFW.template("Hello, <%= name %>!", {"name": "John"})
Expected output: Hello, John!
Source Code
def template(template_str: str, context: Dict[str, Any]) -> str:
# Validate inputs for security
template_str = sanitize_string(template_str, max_length=10000)
if not isinstance(context, dict):
raise TypeError("Context must be a dictionary")
# Validate context values
for key, value in context.items():
if not isinstance(key, str):
raise TypeError(f"Context key '{key}' must be a string")
if callable(value):
from .security import validate_callable
validate_callable(value, f"context['{key}']")
# Check for dangerous patterns
dangerous_patterns = (
r"<%=.*?.__(class|bases|subclasses|globals|dict|code|builtins|module)__.*?%>"
)
if re.search(dangerous_patterns, template_str):
raise SecurityError("Potentially dangerous template pattern detected")
# Define the token pattern
token_pattern = r"(<%=?[^%]*?%>)"
# Tokenize the template
def tokenize(template_text: str) -> List[str]:
"""Split template into tokens."""
tokens = re.split(token_pattern, template_text)
return tokens
# Evaluate expressions in the template
def evaluate_expression(expr: str, ctx: Dict[str, Any]) -> Any:
"""
Evaluate a template expression.
Args:
expr: The expression to evaluate
ctx: The context dictionary
Returns:
The result of the expression
Raises:
ValueError: If the expression is invalid
NameError: If a variable is not defined
AttributeError: If an attribute is not found
"""
# Allow simple variable access and method calls with a strict pattern
pattern = r"^([a-zA-Z_][a-zA-Z0-9_]*)(\.[a-zA-Z_][a-zA-Z0-9_]*(\(\))?)*$"
if not re.match(pattern, expr):
raise ValueError(f"Invalid expression: '{expr}'")
parts = expr.split(".")
value = ctx.get(parts[0], None)
if value is None:
raise NameError(f"Name '{parts[0]}' is not defined.")
for part in parts[1:]:
if part.endswith("()"):
method_name = part[:-2]
value = call_safe_method(value, method_name)
else:
if hasattr(value, part):
value = getattr(value, part, None)
else:
raise AttributeError(f"Attribute '{part}' not found.")
return value
# Evaluate conditions in the template
def evaluate_condition(condition: str, ctx: Dict[str, Any]) -> bool:
"""
Evaluate a template condition.
Args:
condition: The condition to evaluate
ctx: The context dictionary
Returns:
True if the condition is truthy, False otherwise
Raises:
ValueError: If the condition is invalid
"""
# Allow simple variable truthiness checks
pattern = r"^([a-zA-Z_][a-zA-Z0-9_]*)$"
if not re.match(pattern, condition):
raise ValueError(f"Invalid condition: '{condition}'")
value = ctx.get(condition, None)
return bool(value)
# Call safe methods on objects
def call_safe_method(obj: Any, method_name: str) -> Any:
"""
Call a safe method on an object.
Args:
obj: The object to call the method on
method_name: The name of the method to call
Returns:
The result of the method call
Raises:
ValueError: If the method is not allowed
"""
# Only allow safe methods on strings
safe_methods = {"upper", "lower", "title", "capitalize"}
if isinstance(obj, str) and method_name in safe_methods:
method = getattr(obj, method_name, None)
if method is not None:
return method()
else:
raise ValueError(
f"Method '{method_name}' is not allowed on object of type '{type(obj).__name__}'."
)
# Process the template
tokens = tokenize(template_str)
output = ""
skip_stack = [] # Track conditional blocks
idx = 0
while idx < len(tokens):
token = tokens[idx]
# Handle variable interpolation
if token.startswith("<%=") and token.endswith("%>"):
if not any(skip_stack): # Only process if not in a skipped block
expr = token[3:-2].strip()
value = evaluate_expression(expr, context)
output += str(value)
# Handle control statements
elif token.startswith("<%") and token.endswith("%>"):
tag_content = token[2:-2].strip()
# if statement
if tag_content.startswith("if "):
condition = tag_content[3:].rstrip(":").strip()
result = evaluate_condition(condition, context)
skip_stack.append(not result)
# endif statement
elif tag_content == "endif":
if skip_stack:
skip_stack.pop()
else:
raise ValueError("Unmatched 'endif' found.")
# unknown tag
else:
raise ValueError(f"Unknown tag '{tag_content}'.")
# Regular text
else:
if not any(skip_stack): # Only add if not in a skipped block
output += token
idx += 1
# Check for unclosed conditional blocks
if skip_stack:
raise ValueError("Unclosed 'if' statement detected.")
return output
max()
Gets the maximum value in an array
Implementation
Uses Python's max function with optional key function
Example
max_val = UniCoreFW.max([1, 5, 3, 2, 4])
Expected output: 5
Source Code
def max(array, key_func=None):
if not array:
return None
if key_func:
return max(array, key=key_func)
return max(array)
min()
Gets the minimum value in an array
Implementation
Uses Python's min function with optional key function
Example
min_val = UniCoreFW.min([1, 5, 3, 2, 4])
Expected output: 1
Source Code
def min(array, key_func=None):
if not array:
return None
if key_func:
return min(array, key=key_func)
return min(array)
noop()
A function that does nothing (no operation)
Implementation
Empty function body
Example
UniCoreFW.noop()
Expected output: None
Source Code
def noop():
pass
constant()
Returns a function that always returns the specified value
Implementation
Creates a lambda that ignores arguments
Example
always_true = UniCoreFW.constant(True)
result = always_true(1, 2, 3)
Expected output: True
Source Code
def constant(value):
return lambda: value
random()
Returns a random integer between min_val and max_val
Implementation
Uses Python's random.randint
Example
random_num = UniCoreFW.random(1, 10)
Expected output: A random integer between 1 and 10
Source Code
def random(min_val, max_val):
from random import randint
return randint(min_val, max_val)
iteratee()
Returns a function based on the type of value
Implementation
Creates appropriate functions for different types
Example
pred = UniCoreFW.iteratee({"active": True})
result = pred({"active": True, "name": "John"})
Expected output: True
Source Code
def iteratee(value):
if callable(value):
return value
elif isinstance(value, dict):
return lambda obj: all(obj.get(k) == v for k, v in value.items())
else:
return lambda obj: obj == value
enhanced_curry()
Enhanced curry function with explicit arity support and _argcount tracking.
Implementation
Args: func: The function to curry arity: Explicit arity (if None, inferred from function)
Returns:
A curried function that collects arguments until arity is reached
Example
def add_three(a, b, c):
return a + b + c
curried_add = enhanced_curry(add_three)
result = curried_add(1)(2)(3)
result
Expected output: 6
Source Code
def enhanced_curry(func: Callable, arity: Optional[int] = None) -> Callable:
_validate_callable(func)
if arity is None:
arity = func.__code__.co_argcount
def curried(*args):
if len(args) >= arity:
return func(*args[:arity])
def next_curry(*more_args):
return curried(*(args + more_args))
# Track remaining arguments needed
next_curry._argcount = arity - len(args) # type: ignore
return _copy_function_metadata(next_curry, func)
curried._argcount = arity # type: ignore
return _copy_function_metadata(curried, func)
juxtapose()
Create a function that applies multiple functions to the same arguments.
Implementation
Args: *functions: Functions to apply in parallel
Returns:
A function that returns a list of results from all functions
Example
first_char = lambda s: s[0]
last_char = lambda s: s[-1]
both_ends = juxtapose(first_char, last_char)
both_ends("hello")
Expected output: ['h', 'o']
Source Code
def juxtapose(*functions: Callable) -> Callable:
for func in functions:
_validate_callable(func)
def parallel(*args, **kwargs):
return [func(*args, **kwargs) for func in functions]
# Set _argcount for compatibility with tests
parallel._argcount = max((f.__code__.co_argcount for f in functions), default=0) # type: ignore
parallel.__name__ = f"juxtapose({', '.join(f.__name__ for f in functions)})"
return parallel
iterated()
Create a function that applies func n times to a value.
Implementation
Args: func: The function to iterate
Returns:
A function that takes (value, n) and applies func n times
Example
double = lambda x: x * 2
repeated_double = iterated(double)
repeated_double(2, 3) # 2 -> 4 -> 8 -> 16
Expected output: 16
Source Code
def iterated(func: Callable) -> Callable:
_validate_callable(func)
def iterator(value, n=1):
result = value
for _ in range(max(0, n)):
result = func(result)
return result
return _copy_function_metadata(iterator, func)
flow_right()
Create a function that is the composition of functions, executed right to left.
Implementation
Args: *functions: Functions to compose
Returns:
A function that applies all functions in reverse sequence
Example
double = lambda x: x * 2
add_one = lambda x: x + 1
transform = flow_right(double, add_one)
transform(5) # add_one(5) then double(6) = 12
Expected output: 12
Source Code
def flow_right(*functions: Callable) -> Callable:
for func in functions:
_validate_callable(func)
if not functions:
return lambda x: x
def composed(*args, **kwargs):
result = functions[-1](*args, **kwargs)
for func in reversed(functions[:-1]):
result = func(result)
return result
# Set _argcount for compatibility with tests
composed._argcount = functions[-1].__code__.co_argcount if functions else 0 # type: ignore
composed.__name__ = f"flow_right({', '.join(f.__name__ for f in functions)})"
return composed
flow()
Create a function that is the composition of functions, executed left to right.
Implementation
Args: *functions: Functions to compose
Returns:
A function that applies all functions in sequence
Example
add_exclamation = lambda s: s + "!"
make_greeting = lambda name: f"Hello {name}"
greet = flow(make_greeting, add_exclamation)
greet("World")
Expected output: 'Hello World!'
Source Code
def flow(*functions: Callable) -> Callable:
for func in functions:
_validate_callable(func)
if not functions:
return lambda x: x
def composed(*args, **kwargs):
result = functions[0](*args, **kwargs)
for func in functions[1:]:
result = func(result)
return result
# Set _argcount for compatibility with tests
composed._argcount = functions[0].__code__.co_argcount if functions else 0 # type: ignore
composed.__name__ = f"flow({', '.join(f.__name__ for f in functions)})"
return composed
ary()
Create a function that accepts up to n arguments, ignoring additional ones.
Implementation
Args: func: The function to cap arguments for n: The arity cap (if None, uses function's natural arity)
Returns:
A function that accepts at most n arguments
Example
def add_four(a, b, c, d):
return a + b + c + d
capped = ary(add_four, 2)
capped(1, 2, 3, 4) # Only uses first 2 args
Expected output: 3
Source Code
def ary(func: Callable, n: Optional[int] = None) -> Callable:
_validate_callable(func)
if n is None:
n = func.__code__.co_argcount
def wrapper(*args, **kwargs):
return func(*args[:n], **kwargs)
return _copy_function_metadata(wrapper, func)
flip()
Create a function that invokes func with arguments reversed.
Implementation
Implementation details are not available.
Example
Expected output: ``
Source Code
def flip(func: Callable) -> Callable:
_validate_callable(func)
def wrapper(*args, **kwargs):
return func(*reversed(args), **kwargs)
return _copy_function_metadata(wrapper, func)
chain()
Enables method chaining on collections
Implementation
Creates a wrapper class with chainable methods
Example
chained = UniCoreFW.chain([1, 2, 3, 4])
result = chained.filter(lambda x: x % 2 == 0).map(lambda x: x * 2).value()
Expected output: [4, 8]
Source Code
def chain(obj):
class Chained:
def __init__(self, obj):
self._wrapped = obj
def value(self):
return self._wrapped
def __getattr__(self, attr):
func = getattr(UniCoreFW, attr, None)
if callable(func):
def chainable(*args, **kwargs):
result = func(self._wrapped, *args, **kwargs)
if result is None:
return self
return Chained(result)
return chainable
raise AttributeError(f"{attr} is not a valid attribute")
return Chained(obj)
tap()
Invokes a function with a value and returns the value
Implementation
Calls the function and returns the original value
Example
tapped = UniCoreFW.tap([1, 2, 3], lambda x: print(f"Array: {x}"))
Expected output: [1, 2, 3] (with side effect of printing 'Array: [1, 2, 3]')
Source Code
def tap(value, func):
func(value)
return value
property()
Creates a function that retrieves a property from objects
Implementation
Returns a function that accesses properties
Example
get_name = UniCoreFW.property("name")
name = get_name({"name": "John", "age": 30})
Expected output: "John"
Source Code
def property(prop_name):
return (
lambda obj: obj.get(prop_name)
if isinstance(obj, dict)
else getattr(obj, prop_name, None)
)
property_of()
Creates a function that retrieves properties from a specific object
Implementation
Returns a function that accesses properties of the given object
Example
user = {"name": "John", "age": 30}
get_prop = UniCoreFW.property_of(user)
name = get_prop("name")
Expected output: "John"
Source Code
def property_of(obj):
return (
lambda prop_name: obj.get(prop_name)
if isinstance(obj, dict)
else getattr(obj, prop_name, None)
)
matcher()
Creates a function that matches objects against criteria
Implementation
Returns a function that checks property equality
Example
is_active_user = UniCoreFW.matcher({"active": True})
result = is_active_user({"name": "John", "active": True})
Expected output: True
Source Code
def matcher(attrs):
def match(obj):
return all(obj.get(k) == v for k, v in attrs.items())
return match
deep_copy()
Creates a deep copy of an object without using imports
Implementation
Recursively copies objects, lists, and tuples
Example
copied = UniCoreFW.deep_copy({"a": 1, "b": [1, 2, {"c": 3}]})
Expected output: {"a": 1, "b": [1, 2, {"c": 3}]} (deep copy)
Source Code
def deep_copy(obj):
if isinstance(obj, dict):
return {k: UniCoreFW.deep_copy(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [UniCoreFW.deep_copy(elem) for elem in obj]
elif isinstance(obj, tuple):
return tuple(UniCoreFW.deep_copy(elem) for elem in obj)
elif isinstance(obj, str):
# Strings are immutable, return as is
return obj
else:
# For immutable objects like int, float, return as is
return obj
nest()
Groups a list of dictionaries into a nested dictionary based on the specified keys.
Implementation
Args: collection: A list of dictionaries to be nested. keys: A list of keys to nest the dictionaries by. The order of keys determines the hierarchy of the nesting.
Returns:
A nested dictionary where each level corresponds to a key in the keys
list, and the final level contains lists of dictionaries from the
collection that share the same key values.
Example
collection = [
{'type': 'fruit', 'name': 'apple', 'color': 'red'},
{'type': 'fruit', 'name': 'banana', 'color': 'yellow'},
{'type': 'vegetable', 'name': 'carrot', 'color': 'orange'}
]
keys = ['type', 'color']
nest(collection, keys)
Expected output: {
'fruit': {
'red': [{'type': 'fruit', 'name': 'apple', 'color': 'red'}],
'yellow': [{'type': 'fruit', 'name': 'banana', 'color': 'yellow'}],
},
'vegetable': {
'orange': [{'type': 'vegetable', 'name': 'carrot', 'color': 'orange'}]
}
}
Source Code
def nest(collection: List[Dict[Any, Any]], keys: List[str]) -> Dict[Any, Any]:
out: Dict[Any, Any] = {}
for x in collection:
curr = out
for i, k in enumerate(keys):
val = x.get(k)
if i == len(keys) - 1:
curr.setdefault(val, []).append(x)
else:
curr = curr.setdefault(val, {})
return out
key_by()
Creates an object composed of keys generated from the results of running each element of the given collection through the given iteratee.
Implementation
Args: collection: The collection to process. Should be a list of dictionaries. iteratee: The function to run each element of the collection through. Can be a string (in which case the value of the given key is used) or a callable.
Returns:
An object with the results of running the iteratee on each element of the collection as keys,
and the element of the collection as the values.
Example
key_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], 'a')
Expected output: {1: {'a': 1, 'b': 2}, 3: {'a': 3, 'b': 4}}
Source Code
def key_by(
collection: List[Dict[Any, Any]], iteratee: Union[str, Callable]
) -> Dict[Any, Dict[Any, Any]]:
if isinstance(iteratee, str):
def fn(x):
return x.get(iteratee)
else:
fn = iteratee
out: Dict[Any, Any] = {}
for x in collection:
out[fn(x)] = x
return out
invoke_map()
Invokes the given iteratee function on each element of the given collection and returns an array of the results. The iteratee is invoked with the elements of the collection as the first argument and any additional arguments provided to invoke_map as additional arguments.
Implementation
Args: collection: The collection to process. Should be a list. method: The function to invoke on each element. Can be a string (in which case getattr is used to get the method from the element) or a callable. args: Additional arguments to pass to the iteratee. *kwargs: Additional keyword arguments to pass to the iteratee.
Returns:
A list of the results of invoking the iteratee on each element of the
collection.
Example
invoke_map([1, 2, 3], lambda x: x * 2)
Expected output: [2, 4, 6]
Source Code
def invoke_map(
collection: List[Any], method: Union[str, Callable], *args, **kwargs
) -> List[Any]:
result: List[Any] = []
for x in collection:
if isinstance(method, str):
fn = getattr(x, method)
result.append(fn(*args, **kwargs))
else:
result.append(method(x, *args, **kwargs))
return result
includes()
Checks if a given value is present in a collection.
Implementation
Args: collection: The collection to search in. Can be a dictionary or a list. value: The value to search for.
Returns:
Whether the value is present in the collection.
Example
includes([1, 2, 3], 2)
Expected output: True
Source Code
def includes(collection: Union[Dict[Any, Any], List[Any]], value: Any) -> bool:
if isinstance(collection, dict):
return value in collection.values()
return value in collection
for_each_right()
Iterates over elements of a collection from right to left and invokes a function for each element. The function is invoked with one argument: the current element.
Implementation
Args: collection: The collection to iterate over. Can be a dictionary or a list. func: The function to invoke for each element. It should accept a single argument.
Returns:
The original collection.
Example
for_each_right([1, 2, 3], lambda x: print(x))
Expected output: 3
2
1
Source Code
def for_each_right(
collection: Union[Dict[Any, Any], List[Any]], func: Callable[[Any], None]
) -> Union[Dict[Any, Any], List[Any]]:
items = (
list(collection.values()) if isinstance(collection, dict) else list(collection)
)
for v in reversed(items):
func(v) # noqa: E701
return collection
for_each()
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Each invocation of iteratee is called for its side-effects upon the collection. Collection may be either an object or an array. Iteration is stopped if predicate returns Falsey value. The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection).
Implementation
Args: collection: The collection to iterate over. func: The function invoked per iteration.
Returns:
The collection.
Example
for_each([1, 2, 3], lambda x: print(x))
Expected output: 1
2
3
Source Code
def for_each(
collection: Union[Dict[Any, Any], List[Any]], func: Callable[[Any], None]
) -> Union[Dict[Any, Any], List[Any]]:
if isinstance(collection, dict):
for v in collection.values():
func(v) # noqa: E701
else:
for v in collection:
func(v) # noqa: E701
return collection
flat_map_depth()
Recursively flat maps a given collection up to the given depth. This is similar
to :func:flat_map, but will continue to flatten the mapped results until they
are no longer iterable up to the given depth.
Implementation
Args: collection: Collection to iterate over. func: Iteratee applied per iteration. depth: Maximum recursion depth.
Returns:
Fully flattened mapped list up to the given depth.
Example
nested = lambda x: [[x, x], [x, x]]
flat_map_depth([1, 2], nested, 2)
Expected output: [1, 1, 1, 1, 2, 2, 2, 2]
Source Code
def flat_map_depth(
collection: List[Any], func: Callable[[Any], List[Any]], depth: int
) -> List[Any]:
result = flat_map(collection, func)
def _flatten(arr: Any, d: int) -> List[Any]:
"""
Recursively flattens a list or tuple up to the given depth.
Args:
arr: The list or tuple to flatten.
d: The maximum recursion depth.
Returns:
A flattened list of elements.
Examples:
>>> _flatten([1, 2], 2)
[1, 1, 1, 1, 2, 2, 2, 2]
"""
if d <= 0 or not isinstance(arr, (list, tuple)):
return [arr]
out: List[Any] = []
for y in arr:
if isinstance(y, (list, tuple)):
out.extend(_flatten(y, d - 1))
else:
out.append(y)
return out
return _flatten(result, depth)
flat_map_deep()
Recursively flat maps a given collection. This is similar to :func:flat_map, but
will continue to flatten the mapped results until they are no longer iterable.
Implementation
Args: collection: Collection to iterate over. func: Iteratee applied per iteration.
Returns:
Fully flattened mapped list.
Example
nested = lambda x: [[x, x], [x, x]]
flat_map_deep([1, 2], nested)
Expected output: [1, 1, 1, 1, 2, 2, 2, 2]
Source Code
def flat_map_deep(collection: List[Any], func: Callable[[Any], List[Any]]) -> List[Any]:
def _deep(arr):
out: List[Any] = []
for y in arr:
if isinstance(y, (list, tuple)):
out.extend(_deep(y))
else:
out.append(y)
return out
return _deep(flat_map(collection, func))
flat_map()
Creates a flattened list of values by running each element in collection through func and
flattening the mapped results.
Implementation
Args: collection: Collection to iterate over. func: Iteratee applied per iteration.
Returns:
Flattened mapped list.
Example
duplicate = lambda n: [[n, n]]
flat_map([1, 2], duplicate)
Expected output: [[1, 1], [2, 2]]
Source Code
def flat_map(collection: List[Any], func: Callable[[Any], List[Any]]) -> List[Any]:
result: List[Any] = []
for x in collection:
res = func(x)
if isinstance(res, (list, tuple)):
result.extend(res)
return result
find_last()
Finds the last element in a collection that satisfies the predicate.
Implementation
Args: collection: The dictionary or list to search. predicate: An optional function that returns True for elements to include. If not provided, the truthiness of the element itself is used.
Returns:
The last element that satisfies the predicate, or None if not found.
Example
find_last({'a': 1, 'b': 2, 'c': 3}, lambda x: x > 1)
Expected output: 3
Source Code
def find_last(
collection: Union[Dict[Any, Any], List[Any]],
predicate: Optional[Callable[[Any], bool]] = None,
) -> Any:
pred = predicate or (lambda x: bool(x))
items = list(collection.values()) if isinstance(collection, dict) else collection
for v in reversed(items):
if pred(v):
return v
return None
at()
Retrieves the value at the given path of the object.
Implementation
The path value can be a string or an array of strings or integers. If a path value is an array, it will be used to traverse an array-liked object.
Args:
obj: The object to retrieve values from.
*paths: The path(s) to retrieve values from.
Returns:
A list of values at the given paths.
Example
at({'a': {'b': 2}}, 'a.b')
Expected output: [2]
Source Code
def at(obj: Dict[Any, Any], *paths: str) -> List[Any]:
results: List[Any] = []
for path in paths:
current = obj
# split on dots and brackets
parts = re.findall(r"[^.\[\]]+", path)
for p in parts:
if isinstance(current, dict):
current = current.get(p)
elif isinstance(current, (list, tuple)):
try:
idx = int(p)
current = current[idx]
except Exception:
current = None
else:
current = None
if current is None:
break
results.append(current)
return results
compress()
Compresses a string using simple run-length encoding
Implementation
Encodes repeated characters with count and character
Example
compressed = UniCoreFW.compress("aaabbc")
Expected output: "3a2b1c"
Source Code
def compress(word):
if not word:
return ""
comp = [] # Use a list for faster concatenation
length = len(word)
i = 0
while i < length:
count = 1
# Count up to 9 consecutive characters
while i + count < length and word[i] == word[i + count] and count < 9:
count += 1
# Append the count and character to comp
comp.append(f"{count}{word[i]}")
# Move to the next distinct character
i += count
return "".join(comp)
decompress()
Decompresses a string encoded with run-length encoding
Implementation
Decodes count-character pairs
Example
decompressed = UniCoreFW.decompress("3a2b1c")
Expected output: "aaabbc"
Source Code
def decompress(comp):
result = []
i = 0
while i < len(comp):
# Extract the number (count of characters)
count = 0
while i < len(comp) and comp[i].isdigit():
count = count * 10 + int(comp[i]) # Handle multi-digit counts
i += 1
# Extract the character
if i < len(comp):
char = comp[i]
result.append(char * count) # Append repeated character
i += 1
return "".join(result)
find_median_sorted_arrays()
Finds the median of two sorted arrays efficiently
Implementation
Uses binary search with O(log(min(m, n))) complexity
Example
median = UniCoreFW.find_median_sorted_arrays([1, 3, 5], [2, 4, 6])
Expected output: 3.5
Source Code
def find_median_sorted_arrays(nums1, nums2):
# Validate inputs
validate_type(nums1, (list, tuple), "nums1")
validate_type(nums2, (list, tuple), "nums2")
# Validate all elements are numbers
for i, num in enumerate(nums1):
validate_type(num, (int, float), f"nums1[{i}]")
for i, num in enumerate(nums2):
validate_type(num, (int, float), f"nums2[{i}]")
# Check for reasonable size to prevent DoS
max_size = 10000 # Configurable maximum
if len(nums1) + len(nums2) > max_size:
raise SecurityError("Input arrays exceed maximum allowed size")
# Ensure nums1 is the smaller array for binary search efficiency
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
total_length = m + n
half_length = (total_length + 1) // 2 # For handling both odd/even cases
left, right = 0, m
while left <= right:
partition1 = (left + right) // 2
partition2 = half_length - partition1
maxLeft1 = float("-inf") if partition1 == 0 else nums1[partition1 - 1]
minRight1 = float("inf") if partition1 == m else nums1[partition1]
maxLeft2 = float("-inf") if partition2 == 0 else nums2[partition2 - 1]
minRight2 = float("inf") if partition2 == n else nums2[partition2]
# Check if we've partitioned correctly
if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:
# If odd, return the max of the left halves
if total_length % 2 == 1:
return max(maxLeft1, maxLeft2)
# If even, return the average of the two middle values
return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2.0
elif maxLeft1 > minRight2:
# Move towards left in nums1
right = partition1 - 1
else:
# Move towards right in nums1
left = partition1 + 1
splice()
Modify the contents of array by inserting elements starting at index start and removing
delete_count number of elements after.
Implementation
Args:
array: List to splice.
start: Start to splice at.
delete_count: Number of items to remove starting at start. If None then all
items after start are removed. Defaults to None.
items: Elements to insert starting at start. Each item is inserted in the order
given.
Returns:
The removed elements of `array` or the spliced string.
Warning:
`array` is modified in place if ``list``.
Example
array = [1, 2, 3, 4]
splice(array, 1)
Expected output: [2, 3, 4]
Source Code
def splice(
array: Union[List[T], str],
start: int,
delete_count: Optional[int] = None,
*items: Any,
) -> Union[List[T], str]:
# List handling
if isinstance(array, list):
length = len(array)
s = start if start >= 0 else max(length + start, 0)
d = delete_count if delete_count is not None else length - s
removed = array[s : s + d]
array[s : s + d] = list(items)
return removed
# String handling
text: str = array # type: ignore
length = len(text)
s = start if start >= 0 else max(length + start, 0)
d = delete_count if delete_count is not None else length - s
return text[:s] + "".join(items) + text[s + d :]
sorted_last_index_of()
This method is like sorted_last_index except that it returns the index of the
closest element to the supplied value in a sorted array. If value is not
found, the index of the next closest element lower in value is returned.
Implementation
Args: array: Array to inspect. value: Value to evaluate.
Returns:
The index of the closest value to `value`. If `value` is not found, the
index of the next closest element lower in value.
Example
sorted_last_index_of([1, 2, 3, 4], 4.2)
Expected output: 3
Source Code
def sorted_last_index_of(array: List[T], value: T) -> int:
idx = array[::-1].index(value) if value in array else -1
return len(array) - idx - 1 if idx >= 0 else -1
sorted_last_index()
Determines the highest index at which value should be inserted into array
in order to maintain its sorted order.
Implementation
Args: array: A list of elements that are already sorted. value: The value to be inserted.
Returns:
The index at which `value` should be inserted to keep the array sorted.
Example
sorted_last_index([1, 2, 2, 3, 4], 2)
Expected output: 3
Source Code
def sorted_last_index(array: List[T], value: T) -> int:
return bisect.bisect_right(array, value) # type: ignore
sorted_index_of()
Return the index of the first occurrence of value in array if array is sorted.
Implementation
Args: array: A list of elements that are already sorted. value: The value to search for.
Returns:
The index of the first occurrence of `value` in `array` if it exists, otherwise -1.
Example
sorted_index_of([1, 2, 2, 3, 4], 2)
Expected output: 1
Source Code
def sorted_index_of(array: List[T], value: T) -> int:
try:
return array.index(value)
except ValueError:
return -1
sorted_index()
Determines the lowest index at which value should be inserted into array
in order to maintain its sorted order.
Implementation
Args: array: A list of elements that are already sorted. value: The value to be inserted.
Returns:
The index at which `value` should be inserted to keep the array sorted.
Example
sorted_index([1, 2, 2, 3, 4], 2)
Expected output: 1
Source Code
def sorted_index(array: List[T], value: T) -> int:
return bisect.bisect_left(array, value) # type: ignore
shift()
Remove the first element of the array and return it.
Implementation
Args: array: The list to shift.
Returns:
The first element of the array if it is not empty, otherwise None.
Example
array = [1, 2, 3]
item = shift(array)
item
Expected output: 1
Source Code
def shift(array: List[T]) -> Optional[T]:
if array:
return array.pop(0)
return None
push()
Appends values to the end of an array.
Implementation
This is a mutable operation on the array.
Example
push([1, 2], 3, 4)
Expected output: [1, 2, 3, 4]
Source Code
def push(array: List[T], *values: T) -> List[T]:
array.extend(values)
return array
pull_all_with()
Removes all elements from array that have the same value as the result of calling the comparator between the elements of array and values. The comparator is invoked with two arguments: (arr_val, oth_val).
Implementation
Args: array: The array to modify. values: The values to remove. comparator: The comparator to compare the elements of the arrays.
Returns:
A new list with the specified values removed.
Example
pull_all_with([1, 2, 3], [2, 3], lambda a, b: a == b)
Expected output: [1]
Source Code
def pull_all_with(
array: List[T], values: List[T], comparator: Optional[Callable[[T, T], bool]] = None
) -> List[T]:
if comparator is None:
return [x for x in array if x not in values]
return [x for x in array if not any(comparator(x, v) for v in values)]
pull_all_by()
Removes all elements from array that have the same value as the result of calling the iteratee on each element of values. The iteratee is invoked with one argument: (value).
Implementation
Args: array: The array to modify. values: The values to remove. iteratee: The iteratee to transform values.
Returns:
A new list with the specified values removed.
Example
pull_all_by([1, 2, 3], [2, 3], lambda x: x % 2)
Expected output: [1]
Source Code
def pull_all_by(
array: List[T], values: List[T], iteratee: Optional[Callable[[T], Any]] = None
) -> List[T]:
if iteratee is None:
return [x for x in array if x not in values]
keys = {iteratee(v) for v in values}
return [x for x in array if iteratee(x) not in keys]
pull_all()
Removes all provided values from the given array.
Implementation
Args: array: The array to modify. values: The values to remove.
Returns:
A new list with the specified values removed.
Example
pull_all([1, 2, 2, 3, 3, 4], [2, 3])
Expected output: [1, 4]
Source Code
def pull_all(array: List[T], values: List[T]) -> List[T]:
return [x for x in array if x not in values]
pull()
Removes all provided values from the given array.
Implementation
Args: array: List to pull from. values: Values to remove.
Returns:
Modified `array`.
Warning:
`array` is modified in place.
Example
pull([1, 2, 2, 3, 3, 4], 2, 3)
Expected output: [1, 4]
Source Code
def pull(array: List[T], *values: T) -> List[T]:
return [x for x in array if x not in values]
nth()
Gets the element at index n of array.
Implementation
Args: array: List passed in by the user. index: Index of element to return.
Returns:
Returns the element at :attr:`index`.
Example
nth([1, 2, 3, 4], 0)
Expected output: 1
Source Code
def nth(array: List[T], index: int) -> Optional[T]:
length = len(array)
if index < 0:
idx = length + index
if 0 <= idx < length:
return array[idx]
else:
if 0 <= index < length:
return array[index]
return None
mapcat()
Map over an array, concatenating the results.
Implementation
Args: array: The array to map over. func: A function that takes an element and its index, and returns an iterable of values to be concatenated into the result.
Returns:
A new array with the concatenated results.
Example
mapcat([1, 2, 3], lambda x, _: [x, x])
Expected output: [1, 1, 2, 2, 3, 3]
Source Code
def mapcat(array: List[T], func: Callable[[T, int], List[U]]) -> List[U]:
result: List[U] = []
for idx, x in enumerate(array):
res = func(x, idx) # type: ignore
result.extend(res or [])
return result
intersperse()
Insert a separating element between the elements of array.
Implementation
Args: array: List to intersperse. sep: Element to insert.
Returns:
Interspersed list.
Example
intersperse([1, [2], [3], 4], "x")
Expected output: [1, 'x', [2], 'x', [3], 'x', 4]
Source Code
def intersperse(array: List[T], sep: T) -> List[T]:
result: List[T] = []
for idx, item in enumerate(array):
if idx:
result.append(sep)
result.append(item)
return result
intersection_with()
Like intersection but accepts a comparator which is invoked to compare the elements of all arrays.
The order and references of result values are determined by the first array. The comparator is invoked with two arguments: (arr_val, oth_val).
Implementation
Args:
array: The array to find the intersection of.
*args: Lists to check for intersection with array.
Returns:
Intersection of provided lists.
Example
array = ["apple", "banana", "pear"]
others = (["avocado", "pumpkin"], ["peach"])
comparator = lambda a, b: a[0] == b[0]
intersection_with(array, *others, comparator=comparator)
Expected output: ['pear']
Source Code
def intersection_with(array: List[T], *args) -> List[T]:
# last arg may be comparator
comparator = None
arrays: List[List[T]] = []
if args and (callable(args[-1]) or args[-1] is None):
comparator = args[-1]
arrays = list(args[:-1]) # type: ignore
else:
arrays = list(args) # type: ignore
if not arrays:
return array.copy()
cmp = comparator if callable(comparator) else (lambda a, b: a == b)
result: List[T] = []
for x in array:
if any(cmp(x, y) for y in result):
continue
if all(any(cmp(x, y) for y in arr) for arr in arrays):
result.append(x)
return result
interleave()
Merge multiple lists into a single list by inserting the next element of each list by sequential round-robin into the new list.
Implementation
Args: arrays: Lists to interleave.
Returns:
Interleaved list.
Example
interleave([1, 2, 3], [4, 5, 6], [7, 8, 9])
Expected output: [1, 4, 7, 2, 5, 8, 3, 6, 9]
Source Code
def interleave(*arrays: List[T]) -> List[T]:
result: List[T] = []
max_len = max((len(arr) for arr in arrays), default=0)
for i in builtins.range(max_len):
for arr in arrays:
if i < len(arr):
result.append(arr[i])
return result
index_of()
Gets the index at which the first occurrence of value is found.
Implementation
Args: array: List to search. value: Value to search for. from_index: Index to search from.
Returns:
Index of found item or -1 if not found.
Example
index_of([1, 2, 3, 4], 2)
Expected output: 1
Source Code
def index_of(array: List[T], value: T, from_index: int = 0) -> int:
length = len(array)
start = from_index if from_index >= 0 else max(length + from_index, 0)
for i in builtins.range(start, length):
if array[i] == value:
return i
return -1
head()
Returns the first element of the array, if it exists.
Implementation
Args: array: List from which to retrieve the first element.
Returns:
The first element of the list if it is not empty, otherwise None.
Example
head([1, 2, 3])
Expected output: 1
Source Code
def head(array: List[T]) -> Optional[T]:
return array[0] if array else None
from_pairs()
Converts a list of [key, value] pairs into an object.
Implementation
Args: pairs: List of key-value pairs.
Returns:
Object with the given key-value pairs.
Example
from_pairs([["a", 1], ["b", 2]]) == {"a": 1, "b": 2}
Expected output: True
Source Code
def from_pairs(pairs: List[Tuple[K, V]]) -> Dict[K, V]:
return {k: v for k, v in pairs}
flatten_depth()
Recursively flattens array up to the specified depth.
Implementation
Args: array: List to flatten. depth: How deep to flatten the array.
Returns:
Flattened list.
Example
flatten_depth([[1], [2, [3]], [[4]]], 2)
Expected output: [1, 2, 3, [4]]
Source Code
def flatten_depth(array: Any, depth: int = 1) -> List[Any]:
return flatten(array, depth)
flatten_deep()
Recursively flattens array.
Implementation
Args: array: List to flatten.
Returns:
Flattened list.
Example
flatten_deep([[1], [2, [3]], [[4]]])
Expected output: [1, 2, 3, 4]
Source Code
def flatten_deep(array: Any) -> List[Any]:
return flatten(array, float("inf")) # type: ignore
find_last_index()
Gets the index at which the last occurrence of value is found.
Implementation
Args: array: List to search. filter_by: Value to search for.
Returns:
Index of the matched value, otherwise -1.
Example
find_last_index([1, 2, 3, 4, 5], 3)
Expected output: 2
Source Code
def find_last_index(
array: List[T], filter_by: Union[Callable[[T], bool], Dict[str, Any], Any]
) -> int:
if callable(filter_by):
predicate = filter_by # type: ignore
elif isinstance(filter_by, dict):
def predicate(x): # type: ignore
return all(x.get(k) == v for k, v in filter_by.items()) # type: ignore
else:
def predicate(x):
return x == filter_by # type: ignore
for idx in builtins.range(len(array) - 1, -1, -1):
try:
if predicate(array[idx]):
return idx
except Exception:
continue
return -1
find_index()
Gets the index at which the first occurrence of value is found.
Implementation
Args: array: List to search. filter_by: Value to search for.
Returns:
Index of the matched value, otherwise -1.
Example
find_index([1, 2, 3, 4, 5], 3)
Expected output: 2
Source Code
def find_index(
array: List[T], filter_by: Union[Callable[[T], bool], Dict[str, Any], Any]
) -> int:
if callable(filter_by):
predicate = filter_by # type: ignore
elif isinstance(filter_by, dict):
def predicate(x): # type: ignore
return all(x.get(k) == v for k, v in filter_by.items()) # type: ignore
else:
def predicate(x):
return x == filter_by # type: ignore
for idx, item in enumerate(array):
try:
if predicate(item):
return idx
except Exception:
continue
return -1
fill()
Fills elements of array with value from start up to, but not including, end.
Implementation
Args:
array: List to fill.
value: Value to fill with.
start: Index to start filling. Defaults to 0.
end: Index to end filling. Defaults to len(array).
Returns:
Filled array.
Example
fill([1, 2, 3, 4, 5], 0)
Expected output: [0, 0, 0, 0, 0]
Source Code
def fill(
array: List[T], value: T, start: int = 0, end: Optional[int] = None
) -> List[T]:
length = len(array)
if length == 0:
return array
s = start if start >= 0 else max(length + start, 0)
e = end if end is not None else length
e = e if e >= 0 else max(length + e, 0)
s = min(max(s, 0), length)
e = min(max(e, 0), length)
for i in builtins.range(s, e):
array[i] = value
return array
duplicates()
Creates an array of unique elements from the first occurrence of each value in array.
Implementation
Args: array: List to process. iteratee: Function invoked per iteration.
Returns:
List of duplicates.
Example
duplicates([0, 1, 3, 2, 3, 1])
Expected output: [3, 1]
Source Code
def duplicates(array: List[T], iteratee: Callable[[T], Any] = lambda x: x) -> List[T]:
seen: set = set()
dup_set: set = set()
result: List[T] = []
for item in array:
key = iteratee(item)
if key in seen and key not in dup_set:
dup_set.add(key)
result.append(item)
seen.add(key)
return result
drop_right_while()
Creates a slice of array excluding elements dropped from the end. Elements are dropped until
predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
Implementation
Args: array: List to process. predicate: Function invoked per iteration.
Returns:
Dropped list.
Example
drop_right_while([1, 2, 3, 4], lambda x: x >= 3)
Expected output: [1, 2]
Source Code
def drop_right_while(array: List[T], predicate: Callable[[T], bool]) -> List[T]:
for idx in range(len(array) - 1, -1, -1):
if not predicate(array[idx]):
return array[: idx + 1]
return []
drop_while()
Creates a slice of array excluding elements dropped from the beginning. Elements are dropped
until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
Implementation
Args: array: List to process. predicate: Function invoked per iteration.
Returns:
Dropped list.
Example
drop_while([1, 2, 3, 4], lambda x: x < 3)
Expected output: [3, 4]
Source Code
def drop_while(array: List[T], predicate: Callable[[T], bool]) -> List[T]:
for idx, x in enumerate(array):
if not predicate(x):
return array[idx:]
return []
drop_right()
Creates a slice of array with n elements dropped from the end.
Implementation
Args:
array: List to process.
n: Number of elements to drop. Defaults to 1.
Returns:
Dropped list.
Example
drop_right([1, 2, 3, 4], 2)
Expected output: [1, 2]
Source Code
def drop_right(array: List[T], n: int = 1) -> List[T]:
return array[:-n] if n else list(array)
drop()
Creates a slice of array with n elements dropped from the beginning.
Implementation
Args:
array: List to process.
n: Number of elements to drop. Defaults to 1.
Returns:
Dropped list.
Example
drop([1, 2, 3, 4], 2)
Expected output: [3, 4]
Source Code
def drop(array: List[T], n: int = 1) -> List[T]:
return array[n:]
difference_with()
Creates an array of values not included in the other given arrays
using comparator for equality comparisons.
Implementation
Args: array (List[T]): The array to inspect. values (List[T]): The values to exclude. comparator (Optional[Callable[[T, T], bool]]): The comparator to transform values.
Returns:
List[T]: Returns the new array of values not included in the other given arrays.
Example
difference_with([2.1, 1.2, 2.3], [2.3, 3.4], lambda a, b: round(a, 1) == round(b, 1))
Expected output: [1.2]
Source Code
def difference_with(array: List[T], *args) -> List[T]:
if not args:
return list(array)
comparator = args[-1] if callable(args[-1]) else None # type: ignore
values = args[0] if comparator else args[0]
if comparator is None:
def comparator(a, b):
return a == b # type: ignore
result: List[T] = []
for item in array:
if not any(comparator(item, v) for v in values):
result.append(item)
return result
difference_by()
Creates an array of values not included in the other given arrays using SameValueZero for equality comparisons.
Implementation
Args: array (List[T]): The array to inspect. values (List[T]): The values to exclude. iteratee (Optional[Callable[[T], Any]]): The iteratee to transform values.
Returns:
List[T]: Returns the new array of values not included in the other given arrays.
Example
difference_by([2.1, 1.2, 2.3], [2.3, 3.4], key=lambda x: round(x))
Expected output: [1.2]
Source Code
def difference_by(array: List[T], *args) -> List[T]:
if not args:
return list(array)
# last arg may be iteratee
iteratee = args[-1]
if callable(iteratee) or isinstance(iteratee, str):
values = [] if len(args) == 1 else args[0]
else:
iteratee = None
values = args[0]
if iteratee is None:
def key(x): # type: ignore
return x
elif isinstance(iteratee, str):
def key(x):
return (
x.get(iteratee) if isinstance(x, dict) else getattr(x, iteratee, None)
)
else:
key = iteratee # type: ignore
other_keys = {key(v) for v in (values or [])}
return [item for item in array if key(item) not in other_keys]
min_value()
Return the minimum value in the array, based on an optional key function. Returns None if the array is empty.
Implementation
Args: array: The array to search. key_func: Optional function to determine the comparison key.
Returns:
The minimum value or None if the array is empty.
Example
min_value([3, 1, 2])
Expected output: 1
Source Code
def min_value(
array: List[T], key_func: Optional[Callable[[T], Any]] = None
) -> Optional[T]:
if not array:
return None
if key_func:
return builtins.min(array, key=key_func)
return builtins.min(array) # type: ignore