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,21 +1,33 @@
|
||||||
require "./wrapper"
|
|
||||||
|
|
||||||
module Spectator
|
module Spectator
|
||||||
# Lazily stores a value.
|
# Lazily stores a value.
|
||||||
struct Lazy(T)
|
struct Lazy(T)
|
||||||
@wrapper : Wrapper(T)?
|
@value : Value(T)?
|
||||||
|
|
||||||
# Retrieves the value, if it was previously fetched.
|
# Retrieves the value, if it was previously fetched.
|
||||||
# On the first invocation of this method, it will yield.
|
# On the first invocation of this method, it will yield.
|
||||||
# The block should return the value to store.
|
# The block should return the value to store.
|
||||||
# Subsequent calls will return the same value and not yield.
|
# Subsequent calls will return the same value and not yield.
|
||||||
def get(&block : -> T)
|
def get(&block : -> T)
|
||||||
if (wrapper = @wrapper)
|
if (value = @value)
|
||||||
wrapper.value
|
value.get
|
||||||
else
|
else
|
||||||
yield.tap do |value|
|
yield.tap do |value|
|
||||||
@wrapper = Wrapper.new(value)
|
@value = Value.new(value)
|
||||||
end
|
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
|
||||||
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