Skip to content

Commit 7b1b819

Browse files
authored
Merge pull request #43 from hartbit/memoize
Add a memoize function to simplify caching
2 parents d57fc3c + 6642f7b commit 7b1b819

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

Sources/TSCBasic/misc.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,3 +229,14 @@ extension SystemError: CustomStringConvertible {
229229
}
230230
}
231231
}
232+
233+
/// Memoizes a costly computation to a cache variable.
234+
public func memoize<T>(to cache: inout T?, build: () throws -> T) rethrows -> T {
235+
if let value = cache {
236+
return value
237+
} else {
238+
let value = try build()
239+
cache = value
240+
return value
241+
}
242+
}

0 commit comments

Comments
 (0)