Debian Codegraph @

Nasal/Autopush/dynarr.nas

raw
1 # Class for dynamic arrays
2 #
3 # Copyright (c) 2018 dynamic arrays authors:
4 # Merspieler http://gitlab.com/merspieler
5 # Distribute under the terms of GPLv2.
6
7 ## Useage
8 # to create a new object: var <name> = dynarr.new();
9 # to add elements: <name>.add(<element>);
10 # you can access the full stored array as: <name>.arr
11 # to get only the used area of the array: var <spliced_array> = <name>.get_spliced()
12
13 var dynarr =
14 {
15 new: func(size = 8)
16 {
17 var this = {parents:[dynarr]};
18 this.maxsize = size;
19 this.size = 0;
20 this.arr = setsize([], size);
21
22 return this;
23 },
24
25 # add a new element to the array
26 add: func(obj)
27 {
28 # case there's no space left
29 if (me.size + 1 >= me.maxsize)
30 {
31 # double array size
32 me.maxsize *= 2;
33 me.arr = setsize(me.arr, me.maxsize);
34 }
35
36 # add object and increase used counter
37 me.arr[me.size] = obj;
38 me.size += 1;
39 },
40
41 # delete an element from the array
42 del: func(id)
43 {
44 me.size -= 1;
45 for(ii = id; ii < me.size - 1; ii += 1){
46 me.arr[ii] = me.arr[ii + 1];
47 }
48 },
49
50 # returns only the filled part of the array or nil if array is empty
51 get_sliced: func()
52 {
53 if (me.size == 0)
54 {
55 return nil;
56 }
57
58 return me.arr[0:me.size - 1];
59 }
60 };