Skip to content

Instantly share code, notes, and snippets.

@Turbo87
Created February 9, 2016 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Turbo87/ff5b9792f47536a35286 to your computer and use it in GitHub Desktop.
Save Turbo87/ff5b9792f47536a35286 to your computer and use it in GitHub Desktop.
import Ember from 'ember';
/**
* If the specified keyName is not already associated with a value, attempts to compute its value using
* the given value function and enters it into the object.
*
* @param obj The object to query (and modify)
* @param keyName The property key to query (and set)
* @param valueFunc The function that is called with the keyName if the keyName does not yet exist
* @returns {boolean} The current (existing or computed) value associated with the specified key
*/
export default function computeIfAbsent(obj, keyName, valueFunc) {
let value = Ember.get(obj, keyName);
if (value !== undefined)
return value;
let newValue = valueFunc(keyName);
if (newValue !== undefined)
Ember.set(obj, keyName, newValue);
return newValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment