John John
John John

Reputation: 1500

Converting ternary operator to if

This is a trivial question but I am having hard time to convert ternary operator to if. Here is what I tried.

function memoize(fn) {
  const cache = {};
  return (...args) => {
    const stringifiedArgs = stringifyArgs(args);
    const result = (cache[stringifiedArgs] = !cache.hasOwnProperty(
      stringifiedArgs
    )
      ? fn(...args)
      : cache[stringifiedArgs]);
    return result;
  };
}

// function memoize(fn) {
//   const cache = {};
//   return (...args) => {
//     const stringifiedArgs = stringifyArgs(args);
//     return result = (if (cache[stringifiedArgs] = !cache.hasOwnProperty(stringifiedArgs)) {
//       fn(...args);
//     } else {
//       cache[stringifiedArgs];
//     })
//   };
// }

Upvotes: 2

Views: 117

Answers (2)

Matteo Basso
Matteo Basso

Reputation: 2704

You probably need an iife if you want to maintain the same structure. However, this is not the cleanest way to do it...

function memoize(fn) {
  const cache = {};
  return (...args) => {
    const stringifiedArgs = stringifyArgs(args);
    const result = cache[stringifiedArgs] = (() => {
      if (!cache.hasOwnProperty(stringifiedArgs)) {
        return fn(...args);
      } else {
        return cache[stringifiedArgs];
      }
    })();
    return result;
  };
}

Upvotes: 1

ggorlen
ggorlen

Reputation: 57204

This is the cleanest I can get it--check the property and save the result of the memoized function in the cache if it doesn't exist. Then return it from the cache.

function memoize(fn) {
  const cache = {};
  return (...args) => {
    const stringifiedArgs = stringifyArgs(args);
    
    if (!cache.hasOwnProperty(stringifiedArgs)) {
      cache[stringifiedArgs] = fn(...args);
    }
      
    return cache[stringifiedArgs];
  };
}

You could also use the in operator pretty safely here:

function memoize(fn) {
  const cache = {};
  return (...args) => {
    const stringifiedArgs = args.join(`,`); // just for testing

    if (!(stringifiedArgs in cache)) {
      cache[stringifiedArgs] = fn(...args);
    }

    return cache[stringifiedArgs];
  };
}

const fib = memoize(n => n < 2 ? n : fib(n - 1) + fib(n - 2));
console.log(fib(78));

Upvotes: 4

Related Questions