-
-
Notifications
You must be signed in to change notification settings - Fork 153
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
1 parent
3707e61
commit 9e4c171
Showing
2 changed files
with
36 additions
and
0 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
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,35 @@ | ||
import { Fn0 } from "@thi.ng/api"; | ||
|
||
/** | ||
* Takes a function returning either a no-arg function (thunk) or its | ||
* already realized (non-function) result. Re-executes thunk for as long | ||
* as it returns another function/thunk. Once a non-function result has | ||
* been produced, `trampoline` returns that value itself. If the final | ||
* result should be function, it needs to wrapped (e.g. as a 1-elem | ||
* array). | ||
* | ||
* This function should be used for non-stack consuming recursion. I.e. | ||
* a trampoline is a form of continuation passing style and only ever | ||
* consumes max. 2 extra stack frames, independent from recursion depth. | ||
* | ||
* ``` | ||
* const countdown = (acc, x) => | ||
* x >= 0 ? | ||
* () => (acc.push(x), countdown(acc, x-1)) : | ||
* acc; | ||
* | ||
* trampoline(countdown([], 4)) | ||
* // [ 4, 3, 2, 1, 0 ] | ||
* | ||
* trampoline(countdown([], -1)) | ||
* // [] | ||
* ``` | ||
* | ||
* @param f | ||
*/ | ||
export const trampoline = <T>(f: T | Fn0<T | Fn0<T>>) => { | ||
while (typeof f === "function") { | ||
f = (<any>f)(); | ||
} | ||
return <T>f; | ||
}; |