linq.js
function single(predicate, defaultValue) {
  predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate;

  let count = 0;
  let singleItem = undefined;
  for (let item of this) {
    if (predicate(item)) {
      if (singleItem === undefined) {
        singleItem = item;
      } else {
        throw new Error('More than one element satisfies the condition in predicate.');
      }
    }

    count++;
  }

  if (singleItem === undefined && arguments.length == 2) return defaultValue;

  if (count === 0) throw new Error('The source sequence is empty.');
  if (!singleItem) throw new Error('No element satisfies the condition in predicate.');

  return singleItem;
}
function single(predicate, defaultValue) {
  predicate = typeof predicate === 'function' ? predicate : util.defaultPredicate;

  let count = 0;
  let singleItem = undefined;
  for (let item of this) {
    if (predicate(item)) {
      if (singleItem === undefined) {
        singleItem = item;
      } else {
        throw new Error('More than one element satisfies the condition in predicate.');
      }
    }

    count++;
  }

  if (singleItem === undefined && arguments.length == 2) return defaultValue;

  if (count === 0) throw new Error('The source sequence is empty.');
  if (!singleItem) throw new Error('No element satisfies the condition in predicate.');

  return singleItem;
}
function single ( predicate , defaultValue ) { predicate = typeof predicate === 'function' ? predicate : util . defaultPredicate ; let count = 0 ; let singleItem = undefined ; for ( let item of this ) { if ( predicate ( item ) ) { if ( singleItem === undefined ) { singleItem = item ; } else { throw new Error ( 'More than one element satisfies the condition in predicate.' ) ; } } count ++ ; } if ( singleItem === undefined && arguments . length == 2 ) return defaultValue ; if ( count === 0 ) throw new Error ( 'The source sequence is empty.' ) ; if ( ! singleItem ) throw new Error ( 'No element satisfies the condition in predicate.' ) ; return singleItem ; }
Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition or sequence is empty.

@param predicate A function to test an element for a condition.
@param defaultValue The default value if no such element exists.
@return The single element of the input sequence that satisfies a condition.
Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists ; this method throws an exception if more than one element satisfies the condition or sequence is empty .