linqts
Version:
LinQ + TypeScript
1,055 lines • 38.3 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import test from 'ava';
import List from '../src/list.js';
var Package = /** @class */ (function () {
function Package(p) {
this.Company = p.Company;
this.Weight = p.Weight;
this.TrackingNumber = p.TrackingNumber;
}
return Package;
}());
var Person = /** @class */ (function () {
function Person(pet) {
var _a;
this.Name = pet.Name;
this.Age = (_a = pet.Age) !== null && _a !== void 0 ? _a : 0;
}
return Person;
}());
var Pet = /** @class */ (function () {
function Pet(pet) {
var _a, _b;
this.Name = pet.Name;
this.Age = (_a = pet.Age) !== null && _a !== void 0 ? _a : 0;
this.Owner = pet.Owner;
this.Vaccinated = (_b = pet.Vaccinated) !== null && _b !== void 0 ? _b : false;
}
return Pet;
}());
var Dog = /** @class */ (function (_super) {
__extends(Dog, _super);
function Dog() {
return _super !== null && _super.apply(this, arguments) || this;
}
Dog.prototype.Speak = function () {
return 'Bark';
};
return Dog;
}(Pet));
var PetOwner = /** @class */ (function () {
function PetOwner(Name, Pets) {
this.Name = Name;
this.Pets = Pets;
}
return PetOwner;
}());
var Product = /** @class */ (function () {
function Product(product) {
this.Name = product.Name;
this.Code = product.Code;
}
return Product;
}());
test('Iterator', function (t) {
var e_1, _a;
var pets = new List([
new Pet({ Age: 10, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 6, Name: 'Bissy' })
]);
try {
for (var pets_1 = __values(pets), pets_1_1 = pets_1.next(); !pets_1_1.done; pets_1_1 = pets_1.next()) {
var pet = pets_1_1.value;
// determine whether all pet names
// in the array start with 'B'.
t.true(pet.Name.startsWith('B'));
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (pets_1_1 && !pets_1_1.done && (_a = pets_1.return)) _a.call(pets_1);
}
finally { if (e_1) throw e_1.error; }
}
});
test('Spread', function (t) {
var e_2, _a;
var pets = new List([
new Pet({ Age: 10, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 6, Name: 'Bissy' })
]);
var petsCopy = __spreadArray([], __read(pets), false);
try {
for (var petsCopy_1 = __values(petsCopy), petsCopy_1_1 = petsCopy_1.next(); !petsCopy_1_1.done; petsCopy_1_1 = petsCopy_1.next()) {
var pet = petsCopy_1_1.value;
// determine whether all pet names
// in the array start with 'B'.
t.true(pet.Name.startsWith('B'));
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (petsCopy_1_1 && !petsCopy_1_1.done && (_a = petsCopy_1.return)) _a.call(petsCopy_1);
}
finally { if (e_2) throw e_2.error; }
}
});
test('toStringTag', function (t) {
var pets = new List([]);
t.true(pets.toString() === '[object List]');
t.true("".concat(pets) === '[object List]');
});
test('Add', function (t) {
var list = new List();
list.Add('hey');
t.is(list.First(), 'hey');
});
test('Append', function (t) {
var list = new List();
list.AddRange(['hey', "what's", 'up']);
list.Append('there');
t.is(list.Last(), 'there');
});
test('Prepend', function (t) {
var list = new List();
list.AddRange(['hey', "what's", 'up']);
list.Prepend('there');
t.is(list.First(), 'there');
});
test('AddRange', function (t) {
var list = new List();
list.AddRange(['hey', "what's", 'up']);
t.deepEqual(list.ToArray(), ['hey', "what's", 'up']);
});
test('Aggregate', function (t) {
var sentence = 'the quick brown fox jumps over the lazy dog';
var reversed = 'dog lazy the over jumps fox brown quick the ';
var words = new List(sentence.split(' '));
t.is(words.Aggregate(function (workingSentence, next) { return next + ' ' + workingSentence; }, ''), reversed);
});
test('All', function (t) {
var pets = new List([
new Pet({ Age: 10, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 6, Name: 'Whiskers' })
]);
// determine whether all pet names
// in the array start with 'B'.
t.false(pets.All(function (pet) { return pet.Name.startsWith('B'); }));
});
test('Any', function (t) {
var pets = new List([
new Pet({ Age: 8, Name: 'Barley', Vaccinated: true }),
new Pet({ Age: 4, Name: 'Boots', Vaccinated: false }),
new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false })
]);
// determine whether any pets over age 1 are also unvaccinated.
t.true(pets.Any(function (p) { return p.Age > 1 && p.Vaccinated === false; }));
t.true(pets.Any());
});
test('Average', function (t) {
var grades = new List([78, 92, 100, 37, 81]);
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
t.is(grades.Average(), 77.6);
t.is(people.Average(function (x) { var _a; return (_a = x === null || x === void 0 ? void 0 : x.Age) !== null && _a !== void 0 ? _a : 0; }), 30);
});
test('Cast', function (t) {
var pets = new List([
new Dog({ Age: 8, Name: 'Barley', Vaccinated: true }),
new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false })
]);
var dogs = pets.Cast();
t.true(typeof dogs.First().Speak === 'function');
t.is(dogs.First().Speak(), 'Bark');
t.true(typeof dogs.Last().Speak === 'undefined');
});
test('Clear', function (t) {
var pets = new List([
new Dog({ Age: 8, Name: 'Barley', Vaccinated: true }),
new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false })
]);
t.is(pets.Count(), 2);
pets.Clear();
t.is(pets.Count(), 0);
});
test('Concat', function (t) {
var cats = new List([
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 1, Name: 'Whiskers' })
]);
var dogs = new List([
new Pet({ Age: 3, Name: 'Bounder' }),
new Pet({ Age: 14, Name: 'Snoopy' }),
new Pet({ Age: 9, Name: 'Fido' })
]);
var expected = ['Barley', 'Boots', 'Whiskers', 'Bounder', 'Snoopy', 'Fido'];
t.deepEqual(cats
.Select(function (cat) { return cat.Name; })
.Concat(dogs.Select(function (dog) { return dog.Name; }))
.ToArray(), expected);
});
test('Contains', function (t) {
var fruits = new List([
'apple',
'banana',
'mango',
'orange',
'passionfruit',
'grape'
]);
t.true(fruits.Contains('mango'));
});
test('Count', function (t) {
var fruits = new List([
'apple',
'banana',
'mango',
'orange',
'passionfruit',
'grape'
]);
t.is(fruits.Count(), 6);
t.is(fruits.Count(function (x) { return x.length > 5; }), 3);
});
test('DefaultIfEmpty', function (t) {
var pets = new List([
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 1, Name: 'Whiskers' })
]);
t.deepEqual(pets
.DefaultIfEmpty()
.Select(function (pet) { return pet.Name; })
.ToArray(), ['Barley', 'Boots', 'Whiskers']);
var numbers = new List();
t.deepEqual(numbers.DefaultIfEmpty(0).ToArray(), [0]);
});
test('Distinct', function (t) {
var ages = new List([21, 46, 46, 55, 17, 21, 55, 55]);
var pets = new List([
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 9, Name: 'Corey' })
]);
var expected = new List([
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 9, Name: 'Corey' })
]);
t.deepEqual(ages.Distinct(), new List([21, 46, 55, 17]));
t.deepEqual(pets.Distinct(), expected);
});
test('DistinctBy', function (t) {
var pets = new List([
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Daisy' })
]);
var result = new List([
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 8, Name: 'Barley' })
]);
t.deepEqual(pets.DistinctBy(function (pet) { return pet.Age; }), result);
});
test('ElementAt', function (t) {
var a = new List(['hey', 'hola', 'que', 'tal']);
t.is(a.ElementAt(0), 'hey');
t.throws(function () { return a.ElementAt(4); }, {
message: /ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source./
});
t.throws(function () { return a.ElementAt(-1); }, {
message: /ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source./
});
});
test('ElementAtOrDefault', function (t) {
var a = new List(['hey', 'hola', 'que', 'tal']);
var b = new List([2, 1, 0, -1, -2]);
t.is(a.ElementAtOrDefault(0), 'hey');
t.is(b.ElementAtOrDefault(2), 0);
t.is(a.ElementAtOrDefault(4), null);
});
test('Except', function (t) {
var numbers1 = new List([2.0, 2.1, 2.2, 2.3, 2.4, 2.5]);
var numbers2 = new List([2.2, 2.3]);
t.deepEqual(numbers1.Except(numbers2).ToArray(), [2, 2.1, 2.4, 2.5]);
});
test('First', function (t) {
t.is(new List(['hey', 'hola', 'que', 'tal']).First(), 'hey');
t.is(new List([1, 2, 3, 4, 5]).First(function (x) { return x > 2; }), 3);
t.throws(function () { return new List().First(); }, {
message: /InvalidOperationException: The source sequence is empty./
});
});
test('FirstOrDefault', function (t) {
t.is(new List(['hey', 'hola', 'que', 'tal']).FirstOrDefault('boo'), 'hey');
t.is(new List().FirstOrDefault('default'), 'default');
});
test('ForEach', function (t) {
var names = new List(['Bruce', 'Alfred', 'Tim', 'Richard']);
var test = '';
names.ForEach(function (x, i) { return (test += "".concat(x, " ").concat(i, " ")); });
t.is(test, 'Bruce 0 Alfred 1 Tim 2 Richard 3 ');
});
test('GroupBy', function (t) {
var pets = new List([
new Pet({ Age: 8, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 1, Name: 'Whiskers' }),
new Pet({ Age: 4, Name: 'Daisy' })
]);
var result = {
'1': ['Whiskers'],
'4': ['Boots', 'Daisy'],
'8': ['Barley']
};
t.deepEqual(pets.GroupBy(function (pet) { return pet.Age; }, function (pet) { return pet.Name; }), result);
// example taken from https://stackoverflow.com/a/7325306/2834553
var drivers = new List([
{ Id: 1, Car: 'Ferrari' },
{ Id: 1, Car: 'BMW' },
{ Id: 2, Car: 'Audi' }
]);
var result2 = {
'1': ['Ferrari', 'BMW'],
'2': ['Audi']
};
t.deepEqual(drivers.GroupBy(function (p) { return p.Id; }, function (p) { return p.Car; }
// (key, g) => ({ [key]: g.ToList() })
), result2);
});
test('GroupJoin', function (t) {
var magnus = new Person({ Name: 'Hedlund, Magnus' });
var terry = new Person({ Name: 'Adams, Terry' });
var charlotte = new Person({ Name: 'Weiss, Charlotte' });
var barley = new Pet({ Name: 'Barley', Owner: terry });
var boots = new Pet({ Name: 'Boots', Owner: terry });
var whiskers = new Pet({ Name: 'Whiskers', Owner: charlotte });
var daisy = new Pet({ Name: 'Daisy', Owner: magnus });
var people = new List([magnus, terry, charlotte]);
var pets = new List([barley, boots, whiskers, daisy]);
// create a list where each element is an anonymous
// type that contains a person's name and
// a collection of names of the pets they own.
var query = people.GroupJoin(pets, function (person) { return person; }, function (pet) { return pet.Owner; }, function (person, petCollection) { return ({
OwnerName: person.Name,
Pets: petCollection.Select(function (pet) { return pet.Name; })
}); });
var expected = [
'Hedlund, Magnus: Daisy',
'Adams, Terry: Barley,Boots',
'Weiss, Charlotte: Whiskers'
];
t.deepEqual(query.Select(function (obj) { return "".concat(obj.OwnerName, ": ").concat(obj.Pets.ToArray()); }).ToArray(), expected);
});
test('IndexOf', function (t) {
var fruits = new List([
'apple',
'banana',
'mango',
'orange',
'passionfruit',
'grape'
]);
var barley = new Pet({ Age: 8, Name: 'Barley', Vaccinated: true });
var boots = new Pet({ Age: 4, Name: 'Boots', Vaccinated: false });
var whiskers = new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false });
var pets = new List([barley, boots, whiskers]);
t.is(fruits.IndexOf('orange'), 3);
t.is(fruits.IndexOf('strawberry'), -1);
t.is(pets.IndexOf(boots), 1);
});
test('Insert', function (t) {
var pets = new List([
new Pet({ Age: 10, Name: 'Barley' }),
new Pet({ Age: 4, Name: 'Boots' }),
new Pet({ Age: 6, Name: 'Whiskers' })
]);
var newPet = new Pet({ Age: 12, Name: 'Max' });
pets.Insert(0, newPet);
pets.Insert(pets.Count(), newPet);
t.is(pets.First(), newPet);
t.is(pets.Last(), newPet);
t.throws(function () { return pets.Insert(-1, newPet); }, { message: /Index is out of range./ });
t.throws(function () { return pets.Insert(pets.Count() + 1, newPet); }, {
message: /Index is out of range./
});
});
test('Intersect', function (t) {
var id1 = new List([44, 26, 92, 30, 71, 38]);
var id2 = new List([39, 59, 83, 47, 26, 4, 30]);
t.is(id1.Intersect(id2).Sum(), 56);
});
test('Join', function (t) {
var magnus = new Person({ Name: 'Hedlund, Magnus' });
var terry = new Person({ Name: 'Adams, Terry' });
var charlotte = new Person({ Name: 'Weiss, Charlotte' });
var barley = new Pet({ Name: 'Barley', Owner: terry });
var boots = new Pet({ Name: 'Boots', Owner: terry });
var whiskers = new Pet({ Name: 'Whiskers', Owner: charlotte });
var daisy = new Pet({ Name: 'Daisy', Owner: magnus });
var people = new List([magnus, terry, charlotte]);
var pets = new List([barley, boots, whiskers, daisy]);
// create a list of Person-Pet pairs where
// each element is an anonymous type that contains a
// pet's name and the name of the Person that owns the Pet.
var query = people.Join(pets, function (person) { return person; }, function (pet) { return pet.Owner; }, function (person, pet) { return ({ OwnerName: person.Name, Pet: pet.Name }); });
var expected = [
'Hedlund, Magnus - Daisy',
'Adams, Terry - Barley',
'Adams, Terry - Boots',
'Weiss, Charlotte - Whiskers'
];
t.deepEqual(query.Select(function (obj) { return "".concat(obj.OwnerName, " - ").concat(obj.Pet); }).ToArray(), expected);
});
test('Last', function (t) {
t.is(new List(['hey', 'hola', 'que', 'tal']).Last(), 'tal');
t.is(new List([1, 2, 3, 4, 5]).Last(function (x) { return x > 2; }), 5);
t.throws(function () { return new List().Last(); }, {
message: /InvalidOperationException: The source sequence is empty./
});
});
test('LastOrDefault', function (t) {
t.is(new List(['hey', 'hola', 'que', 'tal']).LastOrDefault('not happening'), 'tal');
t.is(new List().LastOrDefault('default'), 'default');
});
test('Max', function (t) {
var people = new List([
{ Age: 50, Name: 'Bob' },
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' }
]);
t.is(people.Max(function (x) { var _a; return (_a = x.Age) !== null && _a !== void 0 ? _a : 0; }), 50);
t.is(new List([5, 4, 3, 2, 1]).Min(), 1);
});
test('Max_invalid_function_provided', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
// Provide an invalid selector (wrong type) to trigger the error
var invalidFn = function () { return 0; };
t.throws(function () { return people.Max(invalidFn); }, {
message: /InvalidOperationException: Invalid comparer or selector function provided./
});
});
test('Max_undefinedComparer', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
t.throws(function () { return people.Max(); }, {
message: /InvalidOperationException: No comparer available./
});
});
test('Max_emptyElements', function (t) {
var people = new List([]);
t.is(people.Max(), undefined);
});
test('Max_comparer', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
var comparer = function (a, b) { var _a, _b; return ((_a = a.Age) !== null && _a !== void 0 ? _a : 0) - ((_b = b.Age) !== null && _b !== void 0 ? _b : 0); };
t.is(people.Max(comparer), people.Last());
});
test('Max_number', function (t) {
var nums = new List([5, 10, -5]);
t.is(nums.Max(), 10);
});
test('Max_string', function (t) {
var people = new List(['Cathy', 'Alice', 'Bob']);
t.is(people.Max(), 'Cathy');
});
test('Max_boolean', function (t) {
var bools = new List([true, false, true, false]);
t.is(bools.Max(), true);
});
test('Min', function (t) {
var people = new List([
{ Age: 50, Name: 'Bob' },
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' }
]);
t.is(people.Min(function (x) { var _a; return (_a = x.Age) !== null && _a !== void 0 ? _a : 0; }), 15);
t.is(new List([5, 4, 3, 2, 1]).Min(), 1);
});
test('Min_invalid_function_provided', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
// Provide an invalid selector (wrong type) to trigger the error
var invalidFn = function () { return 0; };
t.throws(function () { return people.Min(invalidFn); }, {
message: /InvalidOperationException: Invalid comparer or selector function provided./
});
});
test('Min_undefinedComparer', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
t.throws(function () { return people.Min(); }, {
message: /InvalidOperationException: No comparer available./
});
});
test('Min_comparer', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
var comparer = function (a, b) { var _a, _b; return ((_a = a.Age) !== null && _a !== void 0 ? _a : 0) - ((_b = b.Age) !== null && _b !== void 0 ? _b : 0); };
t.is(people.Min(comparer), people.First());
});
test('Min_emptyElements', function (t) {
var people = new List([]);
t.is(people.Min(), undefined);
});
test('Min_number', function (t) {
var nums = new List([10, 5, -5]);
t.is(nums.Min(), -5);
});
test('Min_string', function (t) {
var people = new List(['Cathy', 'Alice', 'Bob']);
t.is(people.Min(), 'Alice');
});
test('Min_boolean', function (t) {
var bools = new List([true, false, true, false]);
t.is(bools.Min(), false);
});
test('OfType', function (t) {
var pets = new List([
new Dog({ Age: 8, Name: 'Barley', Vaccinated: true }),
new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false })
]);
var anyArray = new List(['dogs', 'cats', 13, true]);
t.is(anyArray.OfType(String).Count(), 2);
t.is(anyArray.OfType(Number).Count(), 1);
t.is(anyArray.OfType(Boolean).Count(), 1);
t.is(anyArray.OfType(Function).Count(), 0);
t.is(pets.OfType(Dog).Count(), 1);
t.is(pets
.OfType(Dog)
.First()
.Speak(), 'Bark');
});
test('OrderBy', function (t) {
var expected = [1, 2, 3, 4, 5, 6];
t.deepEqual(new List([4, 5, 6, 3, 2, 1])
.OrderBy(function (x) { return x; })
.ToArray(), expected);
t.deepEqual(new List(['Deutschland', 'Griechenland', 'Ägypten'])
.OrderBy(function (x) { return x; }, function (a, b) { return a.localeCompare(b); })
.ToArray(), ['Ägypten', 'Deutschland', 'Griechenland']);
});
test('OrderByDescending', function (t) {
t.deepEqual(new List([4, 5, 6, 3, 2, 1])
.OrderByDescending(function (x) { return x; })
.ToArray(), [6, 5, 4, 3, 2, 1]);
// sorting with custom comparer function
var items = new List([
new Product({ Name: 'Edward', Code: 21 }),
new Product({ Name: 'Sharpe', Code: 37 }),
new Product({ Name: 'And', Code: 45 }),
new Product({ Name: 'The', Code: -12 }),
new Product({ Name: 'Magnetic', Code: 13 }),
new Product({ Name: 'Zeros', Code: 37 })
]);
var nameComparerFn = function (a, b) {
var nameA = a.Name.toUpperCase(); // ignore upper and lowercase
var nameB = b.Name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
};
var ordered = new List([
new Product({ Name: 'And', Code: 45 }),
new Product({ Name: 'Edward', Code: 21 }),
new Product({ Name: 'Magnetic', Code: 13 }),
new Product({ Name: 'Sharpe', Code: 37 }),
new Product({ Name: 'The', Code: -12 }),
new Product({ Name: 'Zeros', Code: 37 })
]);
t.deepEqual(items.OrderByDescending(function (a) { return a; }, nameComparerFn).ToList(), ordered);
});
test('ThenBy', function (t) {
var fruits = new List([
'grape',
'passionfruit',
'banana',
'mango',
'orange',
'raspberry',
'apple',
'blueberry'
]);
// sort the strings first by their length and then
// alphabetically by passing the identity selector function.
var expected = [
'apple',
'grape',
'mango',
'banana',
'orange',
'blueberry',
'raspberry',
'passionfruit'
];
t.deepEqual(fruits
.OrderBy(function (fruit) { return fruit.length; })
.ThenBy(function (fruit) { return fruit; })
.ToArray(), expected);
var expectedNums = [1, 2, 3, 4, 5, 6];
// test omission of OrderBy
t.deepEqual(new List([4, 5, 6, 3, 2, 1])
.ThenBy(function (x) { return x; })
.ToArray(), expectedNums);
});
// see https://github.com/kutyel/linq.ts/issues/23
test('ThenByMultiple', function (t) {
var x = { a: 2, b: 1, c: 1 };
var y = { a: 1, b: 2, c: 2 };
var z = { a: 1, b: 1, c: 3 };
var unsorted = new List([x, y, z]);
var sorted = unsorted
.OrderBy(function (u) { return u.a; })
.ThenBy(function (u) { return u.b; })
.ThenBy(function (u) { return u.c; })
.ToArray();
t.is(sorted[0], z);
t.is(sorted[1], y);
t.is(sorted[2], x);
});
test('ThenByDescending', function (t) {
var fruits = new List([
'grape',
'passionfruit',
'banana',
'mango',
'orange',
'raspberry',
'apple',
'blueberry'
]);
// sort the strings first by their length and then
// alphabetically descending by passing the identity selector function.
var expected = [
'mango',
'grape',
'apple',
'orange',
'banana',
'raspberry',
'blueberry',
'passionfruit'
];
t.deepEqual(fruits
.OrderBy(function (fruit) { return fruit.length; })
.ThenByDescending(function (fruit) { return fruit; })
.ToArray(), expected);
t.deepEqual(new List([4, 5, 6, 3, 2, 1])
.ThenByDescending(function (x) { return x; })
.ToArray(), [6, 5, 4, 3, 2, 1]);
});
test('Remove', function (t) {
var fruits = new List([
'apple',
'banana',
'mango',
'orange',
'passionfruit',
'grape'
]);
var barley = new Pet({ Age: 8, Name: 'Barley', Vaccinated: true });
var boots = new Pet({ Age: 4, Name: 'Boots', Vaccinated: false });
var whiskers = new Pet({ Age: 1, Name: 'Whiskers', Vaccinated: false });
var pets = new List([barley, boots, whiskers]);
var lessPets = new List([barley, whiskers]);
t.true(fruits.Remove('orange'));
t.false(fruits.Remove('strawberry'));
t.true(pets.Remove(boots));
t.deepEqual(pets, lessPets);
});
test('RemoveAll', function (t) {
var dinosaurs = new List([
'Compsognathus',
'Amargasaurus',
'Oviraptor',
'Velociraptor',
'Deinonychus',
'Dilophosaurus',
'Gallimimus',
'Triceratops'
]);
var lessDinosaurs = new List([
'Compsognathus',
'Oviraptor',
'Velociraptor',
'Deinonychus',
'Gallimimus',
'Triceratops'
]);
t.deepEqual(dinosaurs.RemoveAll(function (x) { return x.endsWith('saurus'); }), lessDinosaurs);
});
test('RemoveAt', function (t) {
var dinosaurs = new List([
'Compsognathus',
'Amargasaurus',
'Oviraptor',
'Velociraptor',
'Deinonychus',
'Dilophosaurus',
'Gallimimus',
'Triceratops'
]);
var lessDinosaurs = new List([
'Compsognathus',
'Amargasaurus',
'Oviraptor',
'Deinonychus',
'Dilophosaurus',
'Gallimimus',
'Triceratops'
]);
dinosaurs.RemoveAt(3);
t.deepEqual(dinosaurs, lessDinosaurs);
});
test('Reverse', function (t) {
t.deepEqual(new List([1, 2, 3, 4, 5])
.Reverse()
.ToArray(), [5, 4, 3, 2, 1]);
});
test('Select', function (t) {
t.deepEqual(new List([1, 2, 3])
.Select(function (x) { return x * 2; })
.ToArray(), [2, 4, 6]);
});
test('SelectMany', function (t) {
var petOwners = new List([
new PetOwner('Higa, Sidney', new List([new Pet({ Name: 'Scruffy' }), new Pet({ Name: 'Sam' })])),
new PetOwner('Ashkenazi, Ronen', new List([new Pet({ Name: 'Walker' }), new Pet({ Name: 'Sugar' })])),
new PetOwner('Price, Vernette', new List([
new Pet({ Name: 'Scratches' }),
new Pet({ Name: 'Diesel' })
]))
]);
var expected = ['Scruffy', 'Sam', 'Walker', 'Sugar', 'Scratches', 'Diesel'];
t.deepEqual(petOwners
.SelectMany(function (petOwner) { return petOwner.Pets; })
.Select(function (pet) { return pet.Name; })
.ToArray(), expected);
});
test('SequenceEqual', function (t) {
var pet1 = new Pet({ Age: 2, Name: 'Turbo' });
var pet2 = new Pet({ Age: 8, Name: 'Peanut' });
// create three lists of pets.
var pets1 = new List([pet1, pet2]);
var pets2 = new List([pet1, pet2]);
var pets3 = new List([pet1]);
t.true(pets1.SequenceEqual(pets2));
t.false(pets1.SequenceEqual(pets3));
});
test('Single', function (t) {
var fruits1 = new List();
var fruits2 = new List(['orange']);
var fruits3 = new List(['orange', 'apple']);
var numbers1 = new List([1, 2, 3, 4, 5, 5]);
t.is(fruits2.Single(), 'orange');
t.throws(function () { return fruits1.Single(); }, {
message: /The collection does not contain exactly one element./
});
t.throws(function () { return fruits3.Single(); }, {
message: /The collection does not contain exactly one element./
});
t.is(numbers1.Single(function (x) { return x === 1; }), 1);
t.throws(function () { return numbers1.Single(function (x) { return x === 5; }); }, {
message: /The collection does not contain exactly one element./
});
t.throws(function () { return numbers1.Single(function (x) { return x > 5; }); }, {
message: /The collection does not contain exactly one element./
});
});
test('SingleOrDefault', function (t) {
var fruits1 = new List();
var fruits2 = new List(['orange']);
var fruits3 = new List(['orange', 'apple']);
var numbers1 = new List([1, 2, 3, 4, 5, 5]);
t.is(fruits1.SingleOrDefault('default'), 'default');
t.is(fruits2.SingleOrDefault('default'), 'orange');
t.throws(function () { return fruits3.SingleOrDefault('default'); }, {
message: /The collection does not contain exactly one element./
});
// t.is(
// numbers1.SingleOrDefault(x => x === 1),
// 1
// )
// t.is(
// numbers1.SingleOrDefault(x => x > 5),
// undefined
// )
t.throws(function () { return numbers1.SingleOrDefault(1); }, {
message: /The collection does not contain exactly one element./
});
});
test('Skip', function (t) {
var grades = new List([59, 82, 70, 56, 92, 98, 85]);
t.deepEqual(grades
.OrderByDescending(function (x) { return x; })
.Skip(3)
.ToArray(), [82, 70, 59, 56]);
});
test('SkipLast', function (t) {
var grades = new List([59, 82, 70, 56, 92, 98, 85]);
t.deepEqual(grades
.OrderByDescending(function (x) { return x; })
.SkipLast(3)
.ToArray(), [98, 92, 85, 82]);
});
test('SkipWhile', function (t) {
var grades = new List([59, 82, 70, 56, 92, 98, 85]);
t.deepEqual(grades
.OrderByDescending(function (x) { return x; })
.SkipWhile(function (grade) { return grade >= 80; })
.ToArray(), [70, 59, 56]);
});
test('Sum', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
t.is(new List([2, 3, 5]).Sum(), 10);
t.is(people.Sum(function (x) { var _a; return (_a = x === null || x === void 0 ? void 0 : x.Age) !== null && _a !== void 0 ? _a : 0; }), 90);
});
test('Take', function (t) {
var grades = new List([59, 82, 70, 56, 92, 98, 85]);
t.deepEqual(grades
.OrderByDescending(function (x) { return x; })
.Take(3)
.ToArray(), [98, 92, 85]);
});
test('TakeLast', function (t) {
var grades = new List([59, 82, 70, 56, 92, 98, 85]);
t.deepEqual(grades
.OrderByDescending(function (x) { return x; })
.TakeLast(3)
.ToArray(), [70, 59, 56]);
});
test('TakeWhile', function (t) {
var expected = ['apple', 'banana', 'mango'];
var fruits = new List([
'apple',
'banana',
'mango',
'orange',
'passionfruit',
'grape'
]);
t.deepEqual(fruits.TakeWhile(function (fruit) { return fruit !== 'orange'; }).ToArray(), expected);
});
test('ToArray', function (t) {
t.deepEqual(new List([1, 2, 3, 4, 5]).ToArray(), [1, 2, 3, 4, 5]);
});
test('ToDictionary', function (t) {
var people = new List([
{ Age: 15, Name: 'Cathy' },
{ Age: 25, Name: 'Alice' },
{ Age: 50, Name: 'Bob' }
]);
var dictionary = people.ToDictionary(function (x) { return x.Name; });
// t.deepEqual(dictionary['Bob'] as List<{ Key: string; Value: IPerson }>, {
// Age: 50,
// Name: 'Bob'
// })
// t.is(dictionary['Bob'].Age, 50)
// const dictionary2 = people.ToDictionary(
// x => x.Name,
// y => y.Age
// )
// t.is(dictionary2['Alice'], 25)
// Dictionary should behave just like in C#
t.is(dictionary.Max(function (x) { var _a, _b; return (_b = (_a = x === null || x === void 0 ? void 0 : x.Value) === null || _a === void 0 ? void 0 : _a.Age) !== null && _b !== void 0 ? _b : 0; }), 50);
t.is(dictionary.Min(function (x) { var _a, _b; return (_b = (_a = x === null || x === void 0 ? void 0 : x.Value) === null || _a === void 0 ? void 0 : _a.Age) !== null && _b !== void 0 ? _b : 0; }), 15);
var expectedKeys = new List(['Cathy', 'Alice', 'Bob']);
t.deepEqual(dictionary.Select(function (x) { return x.Key; }), expectedKeys);
t.deepEqual(dictionary.Select(function (x) { return x.Value; }), people);
// example taken from https://stackoverflow.com/a/3611140/2834553
var dict = people.ToDictionary(function (x) { return x; }, function (x) { return x.Age; });
t.is(dict.Select(function (x) { return x.Value; }).Max(), 50);
t.is(dict.Select(function (x) { return x.Value; }).Min(), 15);
});
test('ToList', function (t) {
t.deepEqual(new List([1, 2, 3])
.ToList()
.ToArray(), [1, 2, 3]);
});
test('ToLookup', function (t) {
// create a list of Packages
var packages = new List([
new Package({
Company: 'Coho Vineyard',
TrackingNumber: 89453312,
Weight: 25.2
}),
new Package({
Company: 'Lucerne Publishing',
TrackingNumber: 89112755,
Weight: 18.7
}),
new Package({
Company: 'Wingtip Toys',
TrackingNumber: 299456122,
Weight: 6.0
}),
new Package({
Company: 'Contoso Pharmaceuticals',
TrackingNumber: 670053128,
Weight: 9.3
}),
new Package({
Company: 'Wide World Importers',
TrackingNumber: 4665518773,
Weight: 33.8
})
]);
// create a Lookup to organize the packages.
// use the first character of Company as the key value.
// select Company appended to TrackingNumber
// as the element values of the Lookup.
var lookup = packages.ToLookup(function (p) { return p.Company.substring(0, 1); }, function (p) { return p.Company + ' ' + p.TrackingNumber; });
var result = {
C: ['Coho Vineyard 89453312', 'Contoso Pharmaceuticals 670053128'],
L: ['Lucerne Publishing 89112755'],
W: ['Wingtip Toys 299456122', 'Wide World Importers 4665518773']
};
t.deepEqual(lookup, result);
});
test('Union', function (t) {
var ints1 = new List([5, 3, 9, 7, 5, 9, 3, 7]);
var ints2 = new List([8, 3, 6, 4, 4, 9, 1, 0]);
t.deepEqual(ints1.Union(ints2).ToArray(), [5, 3, 9, 7, 8, 6, 4, 1, 0]);
var result = [
new Product({ Name: 'apple', Code: 9 }),
new Product({ Name: 'orange', Code: 4 }),
new Product({ Name: 'lemon', Code: 12 })
];
var store1 = new List([
new Product({ Name: 'apple', Code: 9 }),
new Product({ Name: 'orange', Code: 4 })
]);
var store2 = new List([
new Product({ Name: 'apple', Code: 9 }),
new Product({ Name: 'lemon', Code: 12 })
]);
t.deepEqual(store1.Union(store2).ToArray(), result);
});
test('Where', function (t) {
var fruits = new List([
'apple',
'passionfruit',
'banana',
'mango',
'orange',
'blueberry',
'grape',
'strawberry'
]);
var expected = ['apple', 'mango', 'grape'];
t.deepEqual(fruits.Where(function (fruit) { return fruit.length < 6; }).ToArray(), expected);
});
test('Zip', function (t) {
var numbers = new List([1, 2, 3, 4]);
var words = new List(['one', 'two', 'three']);
t.deepEqual(numbers.Zip(words, function (first, second) { return "".concat(first, " ").concat(second); }).ToArray(), ['1 one', '2 two', '3 three']);
// larger second array
var expected = ['one 1', 'two 2', 'three 3'];
var numbers2 = new List([1, 2, 3, 4]);
var words2 = new List(['one', 'two', 'three']);
t.deepEqual(words2.Zip(numbers2, function (first, second) { return "".concat(first, " ").concat(second); }).ToArray(), expected);
});
test('Where().Select()', function (t) {
t.deepEqual(new List([1, 2, 3, 4, 5])
.Where(function (x) { return x > 3; })
.Select(function (y) { return y * 2; })
.ToArray(), [8, 10]);
t.deepEqual(new List([1, 2, 3, 4, 5])
.Where(function (x) { return x > 3; })
.Select(function (y) { return y + 'a'; })
.ToArray(), ['4a', '5a']);
});
//# sourceMappingURL=list.test.js.map