UNPKG

@walts81/linq-ts

Version:

Typescript/Javascript LINQ implementation library

28 lines (27 loc) 865 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.singleOrDefault = void 0; const _common_1 = require("./_common"); Array.prototype.singleOrDefault = singleOrDefault; function singleOrDefault(expression, defaultValue = null) { const length = this.length; if (length === 0) return defaultValue; if (!expression) if (length > 1) throw new _common_1.MultipleMatchException(); else return this[0]; let result = undefined; for (let i = 0; i < length; i++) { const item = this[i]; if (expression(item, i)) { if (result === undefined) result = item; else throw new _common_1.MultipleMatchException(); } } return result || defaultValue; } exports.singleOrDefault = singleOrDefault;