Change Wrapper to a nested type for Lazy

This commit is contained in:
Michael Miller 2021-01-09 14:35:58 -07:00
parent 5cac4aa5a1
commit aa4c257ade
No known key found for this signature in database
GPG key ID: F9A0C5C65B162436
2 changed files with 18 additions and 28 deletions

View file

@ -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

View file

@ -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