Topaz provides various core functions built-in to make development efficient. All functions support type safety and functional programming paradigms. 🚀
📝 String Functions
Basic String Manipulation
// String length and basic information
let text = "Hello Topaz!"
let length = text.length() // 12
let byteLength = text.byteLength() // UTF-8 byte length
let isEmpty = text.isEmpty() // false
// Case conversion
let lowercase = text.toLowerCase() // "hello topaz!"
let uppercase = text.toUpperCase() // "HELLO TOPAZ!"
let titlecase = text.toTitleCase() // "Hello Topaz!"
print("Original: {text}")
print("Length: {length}")
print("Lowercase: {lowercase}")
String Search and Validation
let content = "Topaz is a modern programming language"
// String searching
let contains = content.contains("modern") // true
let startsWith = content.startsWith("Topaz") // true
let endsWith = content.endsWith("language") // true
// Position finding
let index = content.indexOf("programming") // Some(17)
let lastIndex = content.lastIndexOf("a") // Some(32)
// Regular expression matching
let patternMatch = content.match(r"\w+") // First word match
let allMatches = content.matchAll(r"\w+") // All word matches
print("Contains: {contains}")
print("Index: {index}")
String Transformation and Splitting
let originalString = " Hello, World, Topaz "
// Whitespace removal
let trimmed = originalString.trim() // "Hello, World, Topaz"
let trimStart = originalString.trimStart() // "Hello, World, Topaz "
let trimEnd = originalString.trimEnd() // " Hello, World, Topaz"
// String splitting and joining
let splitResult = "apple,banana,cherry".split(",") // ["apple", "banana", "cherry"]
let joinResult = splitResult.join(" | ") // "apple | banana | cherry"
// String replacement
let replaced = "Hello World".replace("World", "Topaz") // "Hello Topaz"
let replaceAll = "test test test".replaceAll("test", "code") // "code code code"
print("Trimmed: '{trimmed}'")
print("Split result: {splitResult}")
print("Replaced: {replaced}")
String Formatting
// String templates
let name = "Developer"
let age = 25
let formatted = "Hello, I'm {name} and I'm {age} years old."
print(formatted)
// Advanced formatting
let number = 3.14159
let fixedNumber = number.toFixed(2) // "3.14"
let exponential = number.toExponential(2) // "3.14e+0"
// String padding
let paddingString = "42"
let leftPadded = paddingString.padStart(5, "0") // "00042"
let rightPadded = paddingString.padEnd(5, "0") // "42000"
print("Fixed number: {fixedNumber}")
print("Left padded: {leftPadded}")
🔢 Number Functions
Basic Math Functions
// Basic mathematical operations
let absolute = Math.abs(-42) // 42
let maximum = Math.max(10, 20, 30) // 30
let minimum = Math.min(10, 20, 30) // 10
let squareRoot = Math.sqrt(16) // 4.0
// Rounding functions
let decimal = 3.7
let ceiling = Math.ceil(decimal) // 4
let floor = Math.floor(decimal) // 3
let rounded = Math.round(decimal) // 4
let truncated = Math.trunc(decimal) // 3
print("Absolute: {absolute}")
print("Square root: {squareRoot}")
print("Rounded: {rounded}")
Advanced Math Functions
// Exponential and logarithmic functions
let naturalExp = Math.exp(1) // e^1 ≈ 2.718
let power = Math.pow(2, 3) // 2^3 = 8
let naturalLog = Math.log(Math.E) // 1
let log10 = Math.log10(100) // 2
let log2 = Math.log2(8) // 3
// Trigonometric functions
let radians = Math.PI / 4 // 45 degrees
let sine = Math.sin(radians) // √2/2 ≈ 0.707
let cosine = Math.cos(radians) // √2/2 ≈ 0.707
let tangent = Math.tan(radians) // 1
// Inverse trigonometric functions
let arcsine = Math.asin(0.5) // π/6
let arccosine = Math.acos(0.5) // π/3
let arctangent = Math.atan(1) // π/4
print("Natural exp: {naturalExp}")
print("Sine: {sine}")
print("Arcsine: {arcsine}")
Number Utility Functions
// Number validation
let number1 = 42
let number2 = 3.14
let infinity = 1.0 / 0.0
let notANumber = 0.0 / 0.0
let isInteger = Number.isInteger(number1) // true
let isFinite = Number.isFinite(number2) // true
let isInfinite = Number.isInfinite(infinity) // true
let isNaN = Number.isNaN(notANumber) // true
// Number conversion
let parseInt = Number.parseInt("42") // Ok(42)
let parseFloat = Number.parseFloat("3.14") // Ok(3.14)
let parseRadix = Number.parseInt("1010", 2) // Ok(10) - binary
print("Is integer: {isInteger}")
print("Parse radix: {parseRadix}")
Range and Constraint Functions
// Value range limiting
function clamp(value: float, min: float, max: float) -> float {
return Math.max(min, Math.min(value, max))
}
let clampedValue = clamp(15, 10, 20) // 15
let clampedValue2 = clamp(5, 10, 20) // 10
let clampedValue3 = clamp(25, 10, 20) // 20
// Linear interpolation
function lerp(start: float, end: float, ratio: float) -> float {
return start + (end - start) * ratio
}
let interpolated = lerp(0, 100, 0.5) // 50.0
// Value normalization
function normalize(value: float, min: float, max: float) -> float {
return (value - min) / (max - min)
}
let normalized = normalize(150, 100, 200) // 0.5
print("Clamped value: {clampedValue}")
print("Interpolated: {interpolated}")
print("Normalized: {normalized}")
📚 Array Functions
Basic Array Manipulation
let numbers = [1, 2, 3, 4, 5]
// Array information
let arrayLength = numbers.length() // 5
let isEmpty = numbers.isEmpty() // false
// Element access
let first = numbers.first() // Some(1)
let last = numbers.last() // Some(5)
let atIndex = numbers.get(2) // Some(3)
// Element addition/removal
let mut mutableArray = [1, 2, 3]
mutableArray.push(4) // [1, 2, 3, 4]
let popped = mutableArray.pop() // Some(4), array is [1, 2, 3]
mutableArray.unshift(0) // [0, 1, 2, 3]
let shifted = mutableArray.shift() // Some(0), array is [1, 2, 3]
print("Array length: {arrayLength}")
print("First element: {first}")
print("Mutable array: {mutableArray}")
Functional Array Methods
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// map - transformation
let squares = numbers.map(x => x * x) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
let strings = numbers.map(x => x.toString()) // ["1", "2", "3", ...]
// filter - filtering
let evens = numbers.filter(x => x % 2 == 0) // [2, 4, 6, 8, 10]
let large = numbers.filter(x => x > 5) // [6, 7, 8, 9, 10]
// reduce - accumulation
let sum = numbers.reduce((acc, curr) => acc + curr, 0) // 55
let product = numbers.reduce((acc, curr) => acc * curr, 1) // 3628800
// find - searching
let found = numbers.find(x => x > 5) // Some(6)
let foundIndex = numbers.findIndex(x => x > 5) // Some(5)
print("Squares: {squares}")
print("Evens: {evens}")
print("Sum: {sum}")
print("Found: {found}")
Array Validation and Checking
let testArray = [2, 4, 6, 8, 10]
// every - check all elements
let allEven = testArray.every(x => x % 2 == 0) // true
let allLarge = testArray.every(x => x > 5) // false
// some - check some elements
let someLarge = testArray.some(x => x > 5) // true
let someOdd = testArray.some(x => x % 2 == 1) // false
// includes - inclusion check
let includes6 = testArray.includes(6) // true
let includes7 = testArray.includes(7) // false
// indexOf - find index
let indexOf6 = testArray.indexOf(6) // Some(2)
let indexOf7 = testArray.indexOf(7) // None
print("All even: {allEven}")
print("Some large: {someLarge}")
print("Includes 6: {includes6}")
Array Sorting and Transformation
let randomArray = [3, 1, 4, 1, 5, 9, 2, 6]
// Sorting
let ascending = randomArray.sort() // [1, 1, 2, 3, 4, 5, 6, 9]
let descending = randomArray.sortBy((a, b) => b - a) // [9, 6, 5, 4, 3, 2, 1, 1]
// Remove duplicates
let uniqueArray = randomArray.unique() // [3, 1, 4, 5, 9, 2, 6]
// Reverse array
let reversed = randomArray.reverse() // [6, 2, 9, 5, 1, 4, 1, 3]
// Array concatenation
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
let concatenated = array1.concat(array2) // [1, 2, 3, 4, 5, 6]
// Array slicing
let sliced = [1, 2, 3, 4, 5, 6].slice(2, 5) // [3, 4, 5]
print("Sorted array: {ascending}")
print("Unique array: {uniqueArray}")
print("Concatenated: {concatenated}")
🏗️ Object Functions
Object Inspection and Manipulation
let userObject = {
name: "DevUser",
age: 28,
job: "Developer",
skills: ["Topaz", "Rust", "TypeScript"]
}
// Get object keys/values
let keys = Object.keys(userObject) // ["name", "age", "job", "skills"]
let values = Object.values(userObject) // ["DevUser", 28, "Developer", [...]]
let entries = Object.entries(userObject) // [["name", "DevUser"], ...]
// Property existence check
let hasName = Object.hasOwnProperty(userObject, "name") // true
let hasAddress = Object.hasOwnProperty(userObject, "address") // false
// Object merging
let additionalInfo = { address: "New York", email: "dev@example.com" }
let merged = Object.assign(userObject, additionalInfo)
print("Keys: {keys}")
print("Has name: {hasName}")
Object Transformation and Copying
let originalObject = {
data: {
number: 42,
text: "hello",
array: [1, 2, 3]
},
config: {
enabled: true,
version: "1.0"
}
}
// Shallow copy
let shallowCopy = Object.assign({}, originalObject)
// Deep copy
let deepCopy = Object.deepClone(originalObject)
// Object freezing and sealing
let frozenObject = Object.freeze(originalObject) // Immutable object
let sealedObject = Object.seal(originalObject) // No add/delete properties
// Define property
let newObject = {}
Object.defineProperty(newObject, "readOnlyProperty", {
value: "unchangeable",
writable: false,
enumerable: true
})
print("Deep copy: {deepCopy}")
print("Is frozen: {Object.isFrozen(frozenObject)}")
🎯 Utility Functions
JSON Processing
let dataObject = {
name: "Topaz",
version: "1.0.0",
features: ["safety", "performance", "convenience"]
}
// JSON serialization/deserialization
let jsonString = JSON.stringify(dataObject)
print("JSON: {jsonString}")
match JSON.parse(jsonString) {
case Ok(parsedObject) => print("Parse success: {parsedObject}")
case Err(error) => print("Parse failed: {error}")
}
// Pretty JSON output
let prettyJson = JSON.stringify(dataObject, null, 2)
print("Pretty JSON:\n{prettyJson}")
Type Checking Functions
// Advanced runtime type check with pattern matching
function getType(value: any) -> string {
match value {
case null => "null"
case _: Array<any> => "array"
case _: Date => "date"
case _: int => "int"
case _: float => "float"
case _: string => "string"
case _: bool => "boolean"
case _ => "object"
}
}
let variousValues = [
42,
"string",
[1, 2, 3],
{ key: "value" },
null,
true,
Date.now()
]
for value in variousValues {
print("Value: {value}, Type: {getType(value)}")
}
Concurrency Utilities
// Parallel execution with concurrent block (conceptual)
function task(label: string, ms: int) -> string {
// simulate work (implementation-specific)
// sleep(ms)
return "{label} complete"
}
let results = concurrent(timeout: 3s) {
fast: task("Task 1", 1000)
mid: task("Task 2", 1500)
slow: task("Task 3", 2000)
} else {
fallback: "partial"
}
print("Concurrent results: {results}")
Functional Utilities
// Currying
function curry<A, B, C>(fn: (A, B) -> C) -> (A) -> (B) -> C {
return (a: A) => (b: B) => fn(a, b)
}
let add = (a: int, b: int) => a + b
let curriedAdd = curry(add)
let add5 = curriedAdd(5)
print("5 + 3 = {add5(3)}")
// Pipeline
function pipe<A, B, C>(fn1: (A) -> B, fn2: (B) -> C) -> (A) -> C {
return (input: A) => fn2(fn1(input))
}
let double = (x: int) => x * 2
let toString = (x: int) => x.toString()
let pipeline = pipe(double, toString)
print("Pipeline result: {pipeline(21)}") // "42"
// Memoization
function memoize<T, R>(fn: (T) -> R) -> (T) -> R {
let mut cache: Map<T, R> = Map.new()
return (input: T) => {
if cache.has(input) {
return cache.get(input).unwrap()
}
let result = fn(input)
cache.set(input, result)
return result
}
}
// Fibonacci example
let fibonacci = memoize((n: int) => {
if n <= 1 { return n }
return fibonacci(n - 1) + fibonacci(n - 2)
})
print("Fibonacci 10: {fibonacci(10)}")
🔧 System Functions
Environment and Time
// Environment information
let currentTime = Date.now() // Current timestamp
let currentDate = Date.today() // Today's date
let isoString = Date.now().toISOString() // ISO 8601 format
// Time calculations
let tomorrow = Date.now().addDays(1)
let lastWeek = Date.now().subtractWeeks(1)
let nextMonth = Date.now().addMonths(1)
print("Current time: {currentTime}")
print("ISO string: {isoString}")
// Environment variables (runtime dependent)
let envVar = System.getEnv("PATH")
let currentDir = System.getCurrentDir()
print("Current directory: {currentDir}")
Random Functions
// Basic random
let randomNumber = Math.random() // 0.0 ~ 1.0
let randomInt = Math.randomInt(1, 100) // 1 ~ 100
let randomBool = Math.randomBool() // true or false
// Random selection from array
let colors = ["red", "blue", "green", "yellow"]
let randomColor = colors.randomChoice() // Random color
// Array shuffle
let deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let shuffled = deck.shuffle()
print("Random number: {randomNumber}")
print("Random int: {randomInt}")
print("Random color: {randomColor}")
print("Shuffled deck: {shuffled}")
Topaz core functions make development more efficient and safe. All functions guarantee type safety and support functional programming style! 🎯