Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Last active October 15, 2018 14:01
Show Gist options
  • Save akramsaouri/20f8769806bb251c4375bb811d94a8d7 to your computer and use it in GitHub Desktop.
Save akramsaouri/20f8769806bb251c4375bb811d94a8d7 to your computer and use it in GitHub Desktop.
Lazy evaluation in JavaScript
function Let(f) {
let called = false
let v = null
return function () {
if(called) return v
console.log('evaluating.')
v = f()
called = true
return v
}
}
const n = Let(function() { return 23 })
console.log(n())
console.log(n() + 42)
console.log(n() - 4)
@thegreyfellow
Copy link

A close inmplementation in Ruby

class Let
  attr_accessor :called, :v, :func

  def initialize(&func)
    @called = false
    @v = nil
    @func = func
  end

  def call
    if @called
      @v
    else
      @called = true
      @v = @func.call
    end
  end
end

p = Let.new do
  13
end
# => #<Let:0x00007f810a87b3a0 @called=false, @func=#<Proc:0x00007f810a87b378@(pry):19>, @v=nil>

p.call # => 13
p # => #<Let:0x00007f810a87b3a0 @called=true, @func=#<Proc:0x00007f810a87b378@(pry):19>, @v=13>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment