digitallinguistics/javascript

add internal utility to create alias properties

dwhieb opened this issue · 0 comments

MultiLangString and Transcription objects may be either Strings or Objects. When they are Objects, it is often convenient to alias the default string / transcription, so that it can be accessed directly.

This utility should provide a factory method that adds an aliased property to an object.

// This function should really be called "createMultiLangStringAlias"

/**
 * Adds a new property to the provided Object, which aliases the default analysis language of the provided MultiLangString
 * @param  {Object} obj         The Object to add the aliased property to
 * @param  {String} stringProp  The name of the MultiLangString property to use as the source of the data
 * @param  {String} defaultProp The name of the new property to add
 * @return {Object}             Returns the original Object with the new property added
 */
function aliasLanguage(obj, stringProp, defaultProp) {

  Object.defineProperty(obj, defaultProp, {
    configurable: true,
    enumerable:   false,
    get() {
      return obj[stringProp][obj.defaultAnalysisLanguage];
    },
    set(val) {
      // eslint-disable-next-line no-param-reassign
      obj[stringProp][obj.defaultAnalysisLanguage] = val;
    },
  });

  return obj;

}
// This method should really be called "createTranscriptionAlias"

/**
 * Adds a new property to the provided Object, which aliases the default transcription of the provided Transcription
 * @param  {Object} obj         The Object to add the aliased property to
 * @param  {String} txnProp     The name of the Transcription property to use as the source of the data
 * @param  {String} defaultProp The name of the new property to add
 * @return {Object}             Returns the original Object with the new property added
 */
function aliasTranscription(obj, txnProp, defaultProp) {

  Object.defineProperty(obj, defaultProp, {
    configurable: true,
    enumerable:   false,
    get() {
      return obj[txnProp][obj.defaultOrthography];
    },
    set(val) {
      obj[txnProp][obj.defaultOrthography] = val; // eslint-disable-line no-param-reassign
    },
  });

  return obj;

}