mirror of
https://gitea.invidious.io/iv-org/shard-spectator.git
synced 2024-08-15 00:53:35 +00:00
Change Wrapper to a nested type for Lazy
This commit is contained in:
parent
5cac4aa5a1
commit
aa4c257ade
2 changed files with 18 additions and 28 deletions
|
@ -1,22 +1,34 @@
|
|||
require "./wrapper"
|
||||
|
||||
module Spectator
|
||||
# Lazily stores a value.
|
||||
struct Lazy(T)
|
||||
@wrapper : Wrapper(T)?
|
||||
@value : Value(T)?
|
||||
|
||||
# Retrieves the value, if it was previously fetched.
|
||||
# On the first invocation of this method, it will yield.
|
||||
# The block should return the value to store.
|
||||
# Subsequent calls will return the same value and not yield.
|
||||
def get(&block : -> T)
|
||||
if (wrapper = @wrapper)
|
||||
wrapper.value
|
||||
if (value = @value)
|
||||
value.get
|
||||
else
|
||||
yield.tap do |value|
|
||||
@wrapper = Wrapper.new(value)
|
||||
@value = Value.new(value)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Wrapper for a value.
|
||||
# This is intended to be used as a union with nil.
|
||||
# It allows storing (caching) a nillable value.
|
||||
private struct Value(T)
|
||||
# Creates the wrapper.
|
||||
def initialize(@value : T)
|
||||
end
|
||||
|
||||
# Retrieves the value.
|
||||
def get : T
|
||||
@value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
module Spectator
|
||||
# Wrapper for a value.
|
||||
# This is intended to be used as a union with nil.
|
||||
# It allows storing (caching) a nillable value.
|
||||
# ```
|
||||
# if (wrapper = @wrapper)
|
||||
# wrapper.value
|
||||
# else
|
||||
# value = 42
|
||||
# @wrapper = Wrapper.new(value)
|
||||
# value
|
||||
# end
|
||||
# ```
|
||||
struct Wrapper(T)
|
||||
# Original value.
|
||||
getter value : T
|
||||
|
||||
# Creates the wrapper.
|
||||
def initialize(@value : T)
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue