or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array.mdcrypto.mddate.mdfs.mdfunction.mdindex.mdjson.mdnumber.mdobject.mdoptimize.mdstring.mdtimeout.mdweb.md

optimize.mddocs/

0

# Optimization Utilities

1

2

Performance optimization utilities including try-catch wrappers, safe property access, and efficient argument handling designed to improve application performance and reduce errors.

3

4

## Capabilities

5

6

### Try-Catch Wrapper

7

8

Optimized try-catch wrapper that returns structured results instead of throwing exceptions.

9

10

```typescript { .api }

11

/**

12

* Optimize try-catch operations with structured return

13

* @param fn - Function to execute safely

14

* @returns Object with error and value properties

15

*/

16

function tryCatch<T = any>(fn: () => T): {error: Error | undefined, value: T | undefined};

17

```

18

19

**Usage Examples:**

20

21

```typescript

22

import { tryCatch } from "utility";

23

24

// Safe JSON parsing

25

const jsonResult = tryCatch(() => JSON.parse('{"valid": "json"}'));

26

if (jsonResult.error) {

27

console.error('JSON parse failed:', jsonResult.error.message);

28

} else {

29

console.log('Parsed data:', jsonResult.value);

30

}

31

32

// Safe function execution

33

const mathResult = tryCatch(() => {

34

const result = someComplexCalculation();

35

return result * 2;

36

});

37

38

// Safe property access

39

const propResult = tryCatch(() => obj.deeply.nested.property);

40

if (propResult.value !== undefined) {

41

console.log('Property exists:', propResult.value);

42

}

43

44

// Safe API call

45

const apiResult = tryCatch(() => syncApiCall());

46

if (apiResult.error) {

47

handleApiError(apiResult.error);

48

} else {

49

processApiResponse(apiResult.value);

50

}

51

```

52

53

### Unstable Methods Object

54

55

Object containing experimental methods that may change in future versions. Required for TypeScript compatibility when using certain method names as keywords.

56

57

```typescript { .api }

58

/**

59

* Object containing unstable/experimental methods for TypeScript compatibility

60

* WARNING: Methods in this object may change or be removed in future versions

61

*/

62

const UNSTABLE_METHOD: {

63

try: typeof tryCatch;

64

};

65

```

66

67

**Usage Examples:**

68

69

```typescript

70

import { UNSTABLE_METHOD } from "utility";

71

72

// Required in TypeScript when 'try' conflicts with keyword

73

const result = UNSTABLE_METHOD.try(() => riskyOperation());

74

75

// Identical functionality to direct tryCatch import

76

import { tryCatch } from "utility";

77

const sameResult = tryCatch(() => riskyOperation());

78

79

// Dynamic method access (advanced usage)

80

const methodName = 'try' as keyof typeof UNSTABLE_METHOD;

81

const safeResult = UNSTABLE_METHOD[methodName](() => someFunction());

82

83

// Use case: When building wrapper libraries

84

class SafeExecutor {

85

static execute<T>(fn: () => T) {

86

// Use UNSTABLE_METHOD when 'try' method name is needed

87

return UNSTABLE_METHOD.try(fn);

88

}

89

}

90

```

91

92

**Important Notes:**

93

- Use direct `tryCatch` import when possible for better stability

94

- `UNSTABLE_METHOD.try` is functionally identical to `tryCatch`

95

- This object exists primarily for TypeScript keyword compatibility

96

- Methods in `UNSTABLE_METHOD` may be deprecated in future versions

97

98

### Safe Property Access

99

100

Safely access nested object properties without throwing errors.

101

102

```typescript { .api }

103

/**

104

* Safely access nested object properties (avoid if (a && a.b && a.b.c))

105

* @param obj - Root object

106

* @param keys - Property path as separate arguments

107

* @returns Property value or undefined if path doesn't exist

108

*/

109

function dig(obj?: any, ...keys: string[]): any;

110

```

111

112

**Usage Examples:**

113

114

```typescript

115

import { dig } from "utility";

116

117

// Safe nested property access

118

const user = {

119

profile: {

120

address: {

121

street: '123 Main St',

122

city: 'Portland'

123

}

124

}

125

};

126

127

const street = dig(user, 'profile', 'address', 'street');

128

// Result: '123 Main St'

129

130

const nonexistent = dig(user, 'profile', 'phone', 'number');

131

// Result: undefined (no error thrown)

132

133

// Handle null/undefined objects

134

const nullResult = dig(null, 'any', 'path');

135

// Result: undefined

136

137

const undefinedResult = dig(undefined, 'any', 'path');

138

// Result: undefined

139

140

// Empty keys returns the object

141

const sameObject = dig(user);

142

// Result: user object

143

144

// API response handling

145

const apiResponse = {

146

data: {

147

users: [

148

{ id: 1, name: 'Alice' },

149

{ id: 2, name: 'Bob' }

150

]

151

}

152

};

153

154

const firstUserName = dig(apiResponse, 'data', 'users', '0', 'name');

155

// Result: 'Alice'

156

157

const missingData = dig(apiResponse, 'data', 'posts', '0', 'title');

158

// Result: undefined (safe access to non-existent path)

159

```

160

161

### Arguments to Array Conversion

162

163

Optimized conversion of arguments-like objects to arrays.

164

165

```typescript { .api }

166

/**

167

* Optimize arguments to array conversion

168

* @param args - Array-like arguments object

169

* @returns Proper array with same elements

170

*/

171

function argumentsToArray(args: any[]): any[];

172

```

173

174

**Usage Examples:**

175

176

```typescript

177

import { argumentsToArray } from "utility";

178

179

// Convert function arguments

180

function variableArgs() {

181

const argsArray = argumentsToArray(arguments as any);

182

return argsArray.map(arg => arg.toString());

183

}

184

185

// Usage in modern functions (though rest parameters are preferred)

186

function legacyFunction() {

187

const args = argumentsToArray(arguments as any);

188

args.forEach((arg, index) => {

189

console.log(`Argument ${index}:`, arg);

190

});

191

}

192

193

// Array-like object conversion

194

function processArrayLike(arrayLike: any) {

195

const realArray = argumentsToArray(arrayLike);

196

return realArray.filter(item => item != null);

197

}

198

199

// Performance-critical argument handling

200

function highPerformanceFunction() {

201

// Faster than Array.from(arguments) or [...arguments] in some engines

202

const args = argumentsToArray(arguments as any);

203

return args.reduce((sum, num) => sum + num, 0);

204

}

205

206

// NodeList conversion (DOM)

207

function convertNodeList(nodeList: NodeListOf<Element>) {

208

const elements = argumentsToArray(Array.from(nodeList));

209

return elements.map(el => el.tagName);

210

}

211

```