Sha256: 079a96f338d8bfabb0ac2ffab628efab192c1d3812e7d6e5087ffa3a7a8f8a09

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

module Kind
  module Checkable
    def class?(value)
      Kind::Is.__call__(__kind, value)
    end

    def instance(value, options = Empty::HASH)
      default = options[:or]

      return Kind::Of.(__kind, value) if ::Kind::Maybe::Value.none?(default)

      value != Kind::Undefined && instance?(value) ? value : Kind::Of.(__kind, default)
    end

    def [](value, options = options = Empty::HASH)
      instance(value, options)
    end

    def to_proc
      @to_proc ||=
        -> checker { -> value { checker.instance(value) } }.call(self)
    end

    def __is_instance__(value)
      value.kind_of?(__kind)
    end

    def is_instance_to_proc
      @is_instance_to_proc ||=
        -> checker { -> value { checker.__is_instance__(value) } }.call(self)
    end

    def instance?(*args)
      return is_instance_to_proc if args.empty?

      return args.all? { |object| __is_instance__(object) } if args.size > 1

      arg = args[0]
      arg == Kind::Undefined ? is_instance_to_proc : __is_instance__(arg)
    end

    def or_nil(value)
      return value if instance?(value)
    end

    def or_undefined(value)
      or_nil(value) || Kind::Undefined
    end

    def __as_maybe__(value)
      Kind::Maybe.new(or_nil(value))
    end

    def as_maybe_to_proc
      @as_maybe_to_proc ||=
        -> checker { -> value { checker.__as_maybe__(value) } }.call(self)
    end

    def as_maybe(value = Kind::Undefined)
      return __as_maybe__(value) if value != Kind::Undefined

      as_maybe_to_proc
    end

    def as_optional(value = Kind::Undefined)
      as_maybe(value)
    end
  end

  private_constant :Checkable

  class Checker
    include Checkable

    attr_reader :__kind

    def initialize(kind)
      @__kind = kind
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kind-2.1.0 lib/kind/checker.rb