Skip to content

Instantly share code, notes, and snippets.

@gleba
Last active August 29, 2015 14:12
Show Gist options
  • Save gleba/917cd04fa517b799d0dd to your computer and use it in GitHub Desktop.
Save gleba/917cd04fa517b799d0dd to your computer and use it in GitHub Desktop.
Реализуйте структуру данных, обладающую преимуществами hash-map (быстрый доступ к элементам за O(1)) и array (размер, упорядоченный обход всех элементов и доступ по индексу).
package {
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
use namespace flash_proxy;
public class DataCollection extends Proxy {
public function DataCollection(identityFieldName:String) {
indexes = new Vector.<int>();
hashMap = new Dictionary();
source = new Object();
this.identityFieldName = identityFieldName;
}
private var identityFieldName:String;
private var indexes:Vector.<int>;
private var hashMap:Dictionary;
private var source:Object;
private var id:int;
public function get length():int {
return indexes.length;
}
public function addItemAt(item:Object, index:int):void {
id = item[identityFieldName];
if (source[id] == item) return;
if (source[id])
throw new Error("У двух разных элементов в коллекции не может быть одинакового id");
indexes.splice(index, 0, id);
source[id] = item;
hashMap[item] = id;
}
public function getItemAt(index:int):Object {
return source[indexes[index]];
}
public function removeItemAt(index:int):Object {
id = indexes[index];
indexes.splice(index, 1);
delete hashMap[source[id]];
delete source[id];
return true;
}
public function removeItem(item:Object):Object {
id = item[identityFieldName];
indexes.splice(getIndexById(id), 1);
delete source[id];
delete hashMap[item];
return true;
}
public function getIndexById(id:int):int {
for (var i:int = 0; i < indexes.length; i++) {
if (indexes[i] == id) return i;
}
return -1;
}
public function getItemById(id:int):Object {
return source[id];
}
public function removeItemById(id:int):Object {
indexes.splice(getIndexById(id), 1);
delete hashMap[source[id]];
delete source[id];
return true;
}
public function add(item:Object):void {
id = item[identityFieldName];
if (source[id] == item) return;
if (source[id])
throw new Error("У двух разных элементов в коллекции не может быть одинакового id");
source[id] = item;
hashMap[item] = id;
indexes.push(id);
}
/**
* добавлена возможность обхода по циклу
* for each (var item1:* in DataCollection) {
* и упрощён вызов по индексу DataCollection[index]
*/
override flash_proxy function getProperty(index:*):* {
return source[indexes[index]];
}
override flash_proxy function nextValue(index:int):* {
var o:Object = source[indexes[index - 1]];
return o;
}
override flash_proxy function nextNameIndex(index:int):int {
if (index < indexes.length) return index + 1;
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment