Return to Snippet

Revision: 21753
at December 20, 2009 02:33 by alejandromb


Initial Code
package kc.tda {
	import kc.api.IStack;
	import kc.events.CollectionEvent;

	[Event( name="addAll", type="kc.events.CollectionEvent" )]
	[Event( name="clear", type="kc.events.CollectionEvent" )]
	[Event( name="remove", type="kc.events.CollectionEvent" )]
	[Event( name="removeAll", type="kc.events.CollectionEvent" )]
	[Event( name="retain", type="kc.events.CollectionEvent" )]	
	[Event( name="push", type="kc.events.CollectionEvent" )]
	[Event( name="pop", type="kc.events.CollectionEvent" )]

	public class ArrayStack extends ArrayCollection implements IStack {
		
		// @constructor

		public function ArrayStack( capacity:int = undefined, expandableCapacity:Boolean = false, loadFactor:Number = NaN ) {
			
			super( capacity, expandableCapacity, loadFactor );
			
			_events = [
				CollectionEvent.ADD_ALL,
				CollectionEvent.CLEAR,
				CollectionEvent.REMOVE,
				CollectionEvent.REMOVE_ALL,
				CollectionEvent.RETAIN,
				CollectionEvent.PUSH,
				CollectionEvent.POP				
			];
			
		}
		
		// @override
		
		override public function add( value:* ):Boolean {			
			return push( value );			
		}
		
		override public function remove( value:* ):Boolean {
			return ( value != null )
				? super.remove( value )
				: ( pop() != null )
					? true
					: false;
		}
		
		// @methods
		
		public function element():* {
			ThrowIsEmpty();
			return _records[0];
		}
		
		public function peek():* {
			try{
				var value:* = element();
			}catch(e:Error){
				return null;
			} return value;
		}
		
		public function push( value:* ):Boolean {
			
			if( ! ResolveStatus() ) {
				return false;
			}
				
			var quantity:int = size();
			_records.unshift( value ); 
			
			if( size() != quantity ){
				ResolveDispatchEvent( CollectionEvent.PUSH ); 
				return true;
			} return false;
			
		}
		
		public function pop():* {
			var quantity:int = size();
			var value:* = _records.shift();
			if( size() != quantity ) {
				ResolveDispatchEvent( CollectionEvent.POP );
				return value;
			} return null;
		}
		
	}
	
}

// @INTERFACE

package kc.api {

	public interface IStack extends ICollection {
	
		// @methods
	
		function element():*;
		function peek():*;
		function push(value:*):Boolean;
		function pop():*;
		
	}
	
}

Initial URL
http://www.kirikacode.com

Initial Description

                                

Initial Title
AS3 | ArrayStack

Initial Tags

                                

Initial Language
ActionScript 3