purescript-foreign-object icon indicating copy to clipboard operation
purescript-foreign-object copied to clipboard

Provide a builder

Open paluh opened this issue 4 years ago • 0 comments

Could you please tell me if you think that trivial builder like the below could be a good addition to the lib?

import Prelude

import Foreign.Object (Object)
import Record.Unsafe (unsafeSet) as Record.Unsafe
import Unsafe.Coerce (unsafeCoerce)

newtype Builder a = Builder (Object a → Object a)

instance semigroupBuilder ∷ Semigroup (Builder a) where
  append (Builder b1) (Builder b2) = Builder (b1 <<< b2)

instance monoidBuilder ∷ Monoid (Builder a) where
  mempty = Builder identity

insert ∷ ∀ a. String → a → Builder a
insert k v = unsafeCoerce (Record.Unsafe.unsafeSet k v)

build ∷ ∀ a. Builder a → Object a
build (Builder b) = b (unsafeCoerce {})

Of course this kind of builder is not stack safe (as @garyb pointed out under nearly identical issue here: https://github.com/purescript/purescript-arrays/pull/162 :-)).

paluh avatar May 05 '20 09:05 paluh