JSFiddle - React, Tailwind, and code Playground

by ronilan

HTML

// once (memoize)

JavaScript

function expensive () {
  console.log("Work...");
  return 123; // Some generated value
}

function once(fn) {
  
  var cached = null;

  result = function () {

    if (!cached) {
      
      cached = fn();
    
    }
    
    return cached;
    
  }
  
  return result;
}

var wrapped = once(expensive);

console.log(wrapped()); // Work..., 123
console.log(wrapped()); // Work..., 123