In Typescript, I use this pattern often:
class Vegetable { constructor(public id: number, public name: string) { } } var vegetable_array = new Array<Vegetable>(); vegetable_array.push(new Vegetable(1, "Carrot")); vegetable_array.push(new Vegetable(2, "Bean")); vegetable_array.push(new Vegetable(3, "Peas")); var id = 1; var collection = vegetable_array.filter( xvegetable => { return xvegetable.id == id; }); var item = collection.length < 1 ? null : collection[0]; console.info( item.name );
I am thinking about creating a JavaScript extension similar to the LINQ SingleOrDefault
method where it returns null
if it's not in the array:
var item = vegetable.singleOrDefault( xvegetable => { return xvegetable.id == id});
My question is whether there is another way to achieve this without creating a custom interface?
SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)Returns the only element of a sequence, or a specified default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result. Single() asserts that one and only one element exists in the sequence. First() simply gives you the first one.
Single : It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection. SingleOrDefault: It returns a single specific element from a collection of elements if element match found.
You can always use Array.prototype.filter in this way:
var arr = [1,2,3]; var notFoundItem = arr.filter(id => id === 4)[0]; // will return undefined var foundItem = arr.filter(id => id === 3)[0]; // will return 3
Edit
My answer applies to FirstOrDefault
and not to SingleOrDefault
.SingleOrDefault
checks if there is only one match and in my case (and in your code) you return the first match without checking for another match.
BTW,If you wanted to achieve SingleOrDefault
then you would need to change this:
var item = collection.length < 1 ? null : collection[0];
into
if(collection.length > 1) throw "Not single result...."; return collection.length === 0 ? null : collection[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With