List Methods

Add: Add an element to the end of the list.
AddRange: Adds a range of elements to the list
ElementAt: Get the element at a specific index in the list.
Where: Return a copy of this List object with only the elements that meet the criteria.
FirstOrDefault: Return the first object in the list that meets the 'query' criteria or null if meet the given query
LastOrDefault: Return the last object in the list that meets the 'query' criteria or null if none meet the given query
First: Return the fire element in the list
Last: Return the last element in the list
Count: Return the number of elements in the list.
Clear: Empties the list of elements but keeps the associated type.
IndexOf: Returns the index of the element if contained in the list or -1
LastIndexOf: Returns the last index of the element if contained in the list or -1
Contains: Return a bool indicating if the element is contained in the list
Remove: Removes an element from the list
RemoveAll: Removes all specified element from the list which meet the given criteria
RemoveAt: Removes an element from the list at the specified index
RemoveRange: Removes elements from the list starting at the given index count times
CopyTo: Copies the list to the specified target
Count: Return the number of elements in the list.
Sort: Sorts the elements in the entire List using the specified comparer or genericSort.
Single: Returns the first object in the list that meets the 'query' criteria or null if no objects are found.
SkipWhile: Runs the given query on all elements in the list and returns a list containing the elements which were skipped
OrderBy: Order (ascending) the objects in the list by the given object property name.
OrderByDescending: Order (descending) the objects in the list by the given object property
Reverse: Gets a copy of the list in reverse order
TrueForAll: Determines weather every element in the list matches the given predicate
Distinct: Gets a copy of the list containing only unique entries
Dispose: Erases all elements and members from the list and remove this instance from the List instance memory (called via event window.unload).


The following public properties with a description of each are currently supported:

array: The native JavaScript Array which the List instance uses for storage
$key: The machine key which identifies the List instance in the List.instances member.
$type: The constructor function which all elements in the list must point at.

You may even access members of the list just like a native array with the indexer syntax.

There is also the beginning of a Type system which is attempting to represent C# syntax for classes.

This is completed by use of the cast Function.

Usage Example:

 

 

        //Utility Functions
        function except(ex) { alert(+ex ? 'Message: ' + ex : this.caller.toString()); }

        function ObjectKeysEqual(a, b) {
            for (var p in a) if (a.hasOwnProperty(p) && !a[p] === b[p]) return false;                
            return true;
        }

        function Verify(result, expected) {
            if (!result.forEach || !result || !isNaN(result) || (true === expected || false === expected)) return result === expected || ObjectKeysEqual(result, expected);
            if (expected.length) {
                result = Object.keys(result);
                expected = Object.keys(expected);
                if (result.length !== expected.length) return false;
            }
            try { result.forEach(function (o, i) { if (o !== expected[i]) throw Error; }); }
            catch (_) { return false; }
            return true;
        }

        //Classes

        //Define a class of car which we will store in the list later on.
        function Car(make, model) {
            //Could force the return of $default here or return null/undefined if make or model is missing
            this.make = make;
            this.model = model;
        }

        //Specify default value, could be anything
        Car.$default = new Car();

       //Unit Tests

        function TestReflection() {
            var myList = new List(),
                test = Reflection.getArguments(myList.Add);
            if (!Verify(test, ['object'])) except('Wrong Return');

            test = myList.Reverse.getArguments();
            if (!Verify(test, ['index', 'count'])) except('Wrong Return');
        }

        function TestCast() {
            var test = new myClass(),
            anotherTest = new anotherClass(),
            composed = test + anotherTest,
            yaComposed = test.cast(Number, function () {
                return this + anotherTest
            });
            if (!Verify(composed, 1)) except('Wrong Return');  //Because both types overload to return numbers which should equal 1 by default 0 + 1 = 1;
            if(!Verify(yaComposed, 1)) except('Wrong Return'); //Because test Casted as a Number return 0 added to the derived class which overloads + to return a number which is default 1;
            
            //Should fail because anotherClass hides the function cast
            try {
                yaCComposed = anotherTest.cast(Number, function () {
                    return this + test;
                });                
            } catch (ex) { console.log(ex); }

            //Should not fail because anotherClass is an instance of myClass
            t = test.cast(anotherClass, function () {
                return this + anotherTest
            });

            if (!Verify(t, 2)) except('Wrong Return');  //Because test is casted to anotherClass which gives it a default value of 1 and 1 + 1 = 2;

            //Should fail because anotherClass hides the function cast
            try {
                tt = anotherTest.cast(myClass, function () {
                    return this + test;
                });
            } catch (ex) { console.log(ex); }

            //Should fail because baseClass is abstract
            try { new baseClass(); }
            catch (e) {console.log(e); }

        }

        function TestList() {

            var myList = new List();
            myList.Add(new Car("Honda", "Civic"));
            myList.Add(new Car("Nissan", "Sentra"));
            myList.Add(new Car("Honda", "Cr-V"));
            myList.Add(new Car("Honda", "Cr-V"));

            //This will retrieve the 0th member from the List
            var testGetter = myList[0]; // Car{make:'Honda',model:'Civic'}

            try {
                //This will produce an exception
                var testGetterException = myList[9];
            }
            catch (_) {
                //_ = "index parameter out of range in List.Get"
            }

            var aFirst = myList.FirstOrDefault(function (c) { return c.make === 'Nissan'; });

            var anotherStringForm = myList.FirstOrDefault('c => c.make == "Nissan"'); // 1 in Count

            anotherStringForm = myList.FirstOrDefault('(c) => c.make == "Nissan"'); // 1 in Count

            anotherStringForm = myList.Where("(c) => c.make == 'Nissan' ? new Car('Acura', 'TL') : Car.$default"); // 4 in Count, 1 Acura and 3 Default Cars

            if (!Verify(anotherStringForm[1], new Car('Acura', 'TL'))) alert('Bug');

            var aDefault = myList.FirstOrDefault(function (c) { c.make === 'Nissan'; }); //Accidently left the return off so there is an undefined result

            var selList = myList.Where("make == 'Honda'").OrderByDescending("model").Distinct(); //2 in Count
            var anotherList = myList.Where(function () { return this.make == 'Honda' }).OrderByDescending("model").Distinct(); //2 in Count
            var yetAnotherList = myList.Where(function (c) { return c.make == 'Honda' }).OrderByDescending("model").Distinct(); //2 in Count
            var finalList = myList.Where(function () { return make == 'Honda' }).OrderByDescending("model").Distinct(); //2 in Count

            if (selList.Count() !== 2 || anotherList.Count() !== 2 || yetAnotherList.Count() !== 2 || finalList.Count() !== 2) alert('Bug');

            var outputString = '';
            for (var index = 0; index < selList.Count(); index++)
                outputString += selList.ElementAt(index).model + '\r\n';

            var outputElement = document.getElementById('output');
            if (outputElement)
                outputElement.innerText = outputString;
        }

        function init()
        {
            try
            {


                TestList();

                TestReflection();

                TestCast();

                
            }
            catch(ex)
            {
                alert('The following error occurred: ' + ex);
            }
        }

 

 

Dictionary Methods

ContainsKey: Indicates if they given key is contained in the Dictionary
ContainsValue: Indicates if they given value is contained in the Dictionary
IndexOf: Returns the index of the given object if it is a key or a value based on the given options
IndexOfKey: Returns the index of the given object if it is a key contained in the Dictionary
IndexOfValue: Returns the index of the given object if it is a value contained in the Dictionary
KeyOf: Returns the key of the given value if contained or null 
TryGetValue / ValueOf: Returns the value of the given key if contained or null  
Add: Adds the given key and value if not already added 
Remove: Removes the given key or objects which match the optionally given value the specified times or at least once. Returns an Array of KeyValuePair which contains the keys and values removed.
RemoveAll: Removes the specified key or all objects given which optionally match the corresponding value
Count: Indicates the amount of Pairs stored in the Dictionary or optionally the amount of keys or values which match the given parameter.
ToArray: Returns an array of the keys or values stored in the Dictionary based on the given parameters

The following public properties with a description of each are currently supported: 

Keys: The native JavaScript Array which the Dictionary instance uses for storage of the keys in the Dictionary
Values: The native JavaScript Array which the Dictionary instance uses for storage of the values in the Dictionary
$KeyType: The constructor function which all elements in the list must derive from to be inserted as keys
$ValueType: The constructor function which all elements in the list must derive from to be inserted as values

Example:

 

 var myDictionary = new Dictionary(String, Number);

            myDictionary.Add('Test', 0);

            myDictionary.Add('Test1', 1);

            myDictionary.Add('Test2', 2);

            myDictionary.Add('VA', 240);

            if (!System.Diagnostics.Assert(myDictionary.Count(), 4)) alert('Bug');

            if (!System.Diagnostics.Assert(myDictionary['VA'], 240)) alert('Bug');

            if (!System.Diagnostics.Assert(myDictionary['Test'], 0)) alert('Bug');

            if (!System.Diagnostics.Assert(myDictionary['Test1'], 1)) alert('Bug');

            if (!System.Diagnostics.Assert(myDictionary['Test1'], 2)) alert('Bug');

            myDictionary['Test'] = myDictionary['Test1'];

            if (!System.Diagnostics.Assert(myDictionary['Test'], 1)) alert('Bug');

            //Should not add
            try { myDictionary.Add({}, 'Test'); } //Should Eventually be a DictionaryException
            catch (_) { if (_ !== 'Only one object type is allowed in a list') alert('Bug'); }

            //Should not modify
            try {
                myDictionary['Test'] = {};
                if (!System.Diagnostics.Assert(myDictionary['Test'], 1)) alert('Bug');
            } //Should Eventually be a DictionaryException
            catch (_) { if (_ !== 'Only one object type is allowed in a list') alert('Bug'); }

            if (!System.Diagnostics.Assert(myDictionary.Count(), 4)) alert('Bug');

Last edited May 29, 2012 at 4:54 PM by juliusfriedman, version 17

Comments

No comments yet.