on 513ce27 help sign in
elk/libraries/Native/Array.js
637 lines 20 kB history raw
1Elm.Native.Array = {};
2Elm.Native.Array.make = function(elm) {
3 elm.Native = elm.Native || {};
4 elm.Native.Array = elm.Native.Array || {};
5 if (elm.Native.Array.values) return elm.Native.Array.values;
6 if ('values' in Elm.Native.Array)
7 return elm.Native.Array.values = Elm.Native.Array.values;
9 var List = Elm.Native.List.make(elm);
11 // A RRB-Tree has two distinct data types.
12 // Leaf -> "height" is always 0
13 // "table" is an array of elements
14 // Node -> "height" is always greater than 0
15 // "table" is an array of child nodes
16 // "lengths" is an array of accumulated lengths of the child nodes
18 // M is the maximal table size. 32 seems fast. E is the allowed increase
19 // of search steps when concatting to find an index. Lower values will
20 // decrease balancing, but will increase search steps.
21 var M = 32;
22 var E = 2;
24 // An empty array.
25 var empty = { ctor:"_Array", height:0, table:new Array() };
27 function get(i, array) {
28 if (i < 0 || i >= length(array)) {
29 throw new Error("Index " + i + " is out of range. Check the length of " +
30 "your array first or use getMaybe or getWithDefault.");
31 }
32 return unsafeGet(i, array);
33 }
35 function unsafeGet(i, array) {
36 for (var x = array.height; x > 0; x--) {
37 var slot = i >> (x * 5);
38 if (slot > 0) {
39 while (array.lengths[slot - 1] > i) { slot--; }
40 i -= array.lengths[slot - 1];
41 }
42 array = array.table[slot];
43 }
44 return array.table[i];
45 }
47 // Sets the value at the index i. Only the nodes leading to i will get
48 // copied and updated.
49 function set(i, item, array) {
50 if (i < 0 || length(array) <= i) {
51 return array;
52 }
53 return unsafeSet(i, item, array);
54 }
56 function unsafeSet(i, item, array) {
57 array = nodeCopy(array);
59 if (array.height == 0) {
60 array.table[i] = item;
61 } else {
62 var slot = getSlot(i, array);
63 if (slot > 0) {
64 i -= array.lengths[slot - 1];
65 }
66 array.table[slot] = unsafeSet(i, item, array.table[slot]);
67 }
68 return array;
69 }
71 function initialize(len, f) {
72 if (len == 0) { return empty; }
73 var h = Math.floor(Math.log(len)/Math.log(M));
74 return initialize_(f, h, 0, len);
75 }
77 function initialize_(f, h, from, to) {
78 if (h == 0) {
79 var table = new Array((to - from) % (M + 1));
80 for (var i = 0; i < table.length; i++) {
81 table[i] = f(from + i);
82 }
83 return { ctor:"_Array", height:0, table:table };
84 }
86 var step = Math.pow(M, h);
87 var table = new Array(Math.ceil((to - from) / step));
88 var lengths = new Array(table.length);
89 for (var i = 0; i < table.length; i++) {
90 table[i] = initialize_( f, h - 1, from + (i * step)
91 , Math.min(from + ((i + 1) * step), to));
92 lengths[i] = length(table[i]) + (i > 0 ? lengths[i-1] : 0);
93 }
94 return { ctor:"_Array", height:h, table:table, lengths:lengths };
95 }
97 function fromList(list) {
98 if (list == List.Nil) { return empty; }
100 // Allocate M sized blocks (table) and write list elements to it.
101 var table = new Array(M);
102 var nodes = new Array();
103 var i = 0;
105 while (list.ctor !== '[]') {
106 table[i] = list._0;
107 list = list._1;
108 i++;
110 // table is full, so we can push a leaf containing it into the
111 // next node.
112 if (i == M) {
113 fromListPush({ ctor:"_Array", height:0, table:table }
114 , nodes);
115 table = new Array(M);
116 i = 0;
117 }
118 }
120 // Maybe there is something left on the table.
121 if (i > 0) {
122 fromListPush({ ctor:"_Array", height:0, table:table.splice(0,i) }
123 , nodes);
124 }
126 // Go through all of the nodes and eventually push them into higher nodes.
127 for (var h = 0; h < nodes.length - 1; h++) {
128 if (nodes[h].table.length > 0) {
129 fromListPush(nodes[h], nodes);
130 }
131 }
133 var head = nodes[nodes.length - 1];
134 if (head.height > 0 && head.table.length == 1) {
135 return head.table[0];
136 } else {
137 return head;
138 }
139 }
141 // Push a node into a higher node as a child.
142 function fromListPush(toPush, nodes) {
143 var h = toPush.height;
145 // Maybe the node on this height does not exist.
146 if (nodes.length == h) {
147 nodes.push({ ctor:"_Array", height:h + 1
148 , table:new Array()
149 , lengths:new Array() });
150 }
152 nodes[h].table.push(toPush);
153 var len = length(toPush);
154 if (nodes[h].lengths.length > 0) {
155 len += nodes[h].lengths[nodes[h].lengths.length - 1];
156 }
157 nodes[h].lengths.push(len);
159 if (nodes[h].table.length == M) {
160 fromListPush(nodes[h], nodes);
161 nodes[h] = { ctor:"_Array", height:h + 1
162 , table:new Array()
163 , lengths:new Array() };
164 }
165 }
167 // Pushes an item via push_ to the bottom right of a tree.
168 function push(item, a) {
169 var pushed = push_(item, a);
170 if (pushed !== null) {
171 return pushed;
172 }
174 var newTree = create(item, a.height);
175 return siblise(a, newTree);
176 }
178 // Recursively tries to push an item to the bottom-right most
179 // tree possible. If there is no space left for the item,
180 // null will be returned.
181 function push_(item, a) {
182 // Handle resursion stop at leaf level.
183 if (a.height == 0) {
184 if (a.table.length < M) {
185 var newA = { ctor:"_Array", height:0, table:a.table.slice() };
186 newA.table.push(item);
187 return newA;
188 } else {
189 return null;
190 }
191 }
193 // Recursively push
194 var pushed = push_(item, botRight(a));
196 // There was space in the bottom right tree, so the slot will
197 // be updated.
198 if (pushed != null) {
199 var newA = nodeCopy(a);
200 newA.table[newA.table.length - 1] = pushed;
201 newA.lengths[newA.lengths.length - 1]++;
202 return newA
203 }
205 // When there was no space left, check if there is space left
206 // for a new slot with a tree which contains only the item
207 // at the bottom.
208 if (a.table.length < M) {
209 var newSlot = create(item, a.height - 1);
210 var newA = nodeCopy(a);
211 newA.table.push(newSlot);
212 newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot));
213 return newA
214 } else {
215 return null;
216 }
217 }
219 // Converts an array into a list of elements.
220 function toList(a) {
221 return toList_(List.Nil, a);
222 }
224 function toList_(list, a) {
225 for (var i = a.table.length - 1; i >= 0; i--) {
226 list = a.height == 0 ? List.Cons(a.table[i], list) : toList_(list, a.table[i]);
227 }
228 return list;
229 }
231 // Maps a function over the elements of an array.
232 function map(f, a) {
233 var newA = { ctor:"_Array", height:a.height, table:new Array(a.table) };
234 if (a.height > 0) { newA.lengths = a.lengths; }
235 for (var i = 0; i < a.table.length; i++) {
236 newA.table[i] = a.height == 0 ? f(a.table[i]) : map(f, a.table[i]);
237 }
238 return newA;
239 }
241 // Maps a function over the elements with their index as first argument.
242 function indexedMap(f, a) {
243 var newA = { ctor:"_Array", height:a.height, table:new Array(a.table) };
244 if (a.height > 0) { newA.lengths = a.lengths; }
245 for (var i = 0; i < a.table.length; i++) {
246 newA.table[i] = a.height == 0 ? A2(f, i, a.table[i]) : indexedMap(f, a.table[i]);
247 }
248 return newA;
249 }
251 function foldl(f, b, a) {
252 for (var i = 0; i < a.table.length; i++) {
253 b = A2(f, a.height == 0 ? a.table[i] : foldl(f, b, a.table[i]), b);
254 }
255 return b;
256 }
258 function foldr(f, b, a) {
259 for (var i = a.table.length; i--; ) {
260 b = A2(f, a.height == 0 ? a.table[i] : foldr(f, b, a.table[i]), b);
261 }
262 return b;
263 }
265 // TODO: currently, it slices the right, then the left. This can be
266 // optimized.
267 function slice(from, to, a) {
268 if (from < 0) { from += length(a); }
269 if (to < 0) { to += length(a); }
270 return sliceLeft(from, sliceRight(to, a));
271 }
273 function sliceRight(to, a) {
274 if (to == length(a)) {
275 return a;
276 }
278 // Handle leaf level.
279 if (a.height == 0) {
280 var newA = { ctor:"_Array", height:0 };
281 newA.table = a.table.slice(0, to);
282 return newA;
283 }
285 // Slice the right recursively.
286 var right = getSlot(to, a);
287 var sliced = sliceRight(to - (right > 0 ? a.lengths[right - 1] : 0), a.table[right]);
289 // Maybe the a node is not even needed, as sliced contains the whole slice.
290 if (right == 0) {
291 return sliced;
292 }
294 // Create new node.
295 var newA = { ctor:"_Array", height:a.height
296 , table:a.table.slice(0, right + 1)
297 , lengths:a.lengths.slice(0, right + 1) };
298 newA.table[right] = sliced;
299 newA.lengths[right] = length(sliced) + (right > 0 ? newA.lengths[right - 1] : 0);
300 return newA;
301 }
303 function sliceLeft(from, a) {
304 if (from == 0) {
305 return a;
306 }
308 // Handle leaf level.
309 if (a.height == 0) {
310 var newA = { ctor:"_Array", height:0 };
311 newA.table = a.table.slice(from, a.table.length + 1);
312 return newA;
313 }
315 // Slice the left recursively.
316 var left = getSlot(from, a);
317 var sliced = sliceLeft(from - (left > 0 ? a.lengths[left - 1] : 0), a.table[left]);
319 // Maybe the a node is not even needed, as sliced contains the whole slice.
320 if (left == a.table.length - 1) {
321 return sliced;
322 }
324 // Create new node.
325 var newA = { ctor:"_Array", height:a.height
326 , table:a.table.slice(left, a.table.length + 1)
327 , lengths:new Array(a.table.length - left) };
328 newA.table[left] = sliced;
329 var len = 0;
330 for (var i = 0; i < newA.table.length; i++) {
331 len += length(newA.table[i]);
332 newA.lengths[i] = len;
333 }
335 return newA;
336 }
338 // Appends two trees.
339 // TODO: Add support for appending trees of different sizes. Current
340 // behavior will just rise the lower tree and then append them.
341 function append(a,b) {
342 if (b.height > a.height) { return append(parentise(a, b.height), b); }
343 if (a.height > b.height) { return append(a, parentise(b, a.height)); }
344 if (a.height == 0) { return append(parentise(a, 1), parentise(b, 1)); }
346 var c = append_(a, b);
347 if (c[1].table.length > 0) {
348 return siblise(c[0], c[1]);
349 } else {
350 return c[0];
351 }
352 }
354 // Returns an array of two nodes. The second node _may_ be empty. This case
355 // needs to be handled by the function, that called append_. May be only
356 // called for trees with an minimal height of 1.
357 function append_(a, b) {
358 if (a.height == 1) {
359 // Check if balancing is needed and return based on that.
360 var toRemove = calcToRemove(a, b);
361 if (toRemove <= E) {
362 return [a,b];
363 }
365 return shuffle(a, b, toRemove);
366 }
368 var appended = append_(botRight(a), botLeft(b));
369 a = nodeCopy(a), b = nodeCopy(b);
371 // Adjust the bottom right side of the new tree.
372 a.table[a.table.length - 1] = appended[0];
373 a.lengths[a.lengths.length - 1] = length(appended[0])
374 a.lengths[a.lengths.length - 1] += a.lengths.length > 1 ? a.lengths[a.lengths.length - 2] : 0;
376 // Adjust the bottom left side of the new tree.
377 if (appended[1].table.length > 0) {
378 b.table[0] = appended[1];
379 b.lengths[0] = length(appended[1]);
380 for (var i = 1, len = length(b.table[0]); i < b.lengths.length; i++) {
381 len += length(b.table[i]);
382 b.lengths[i] = len;
383 }
384 } else {
385 b.table.shift();
386 for (var i = 1; i < b.lengths.length; i++) {
387 b.lengths[i] = b.lengths[i] - b.lengths[0];
388 }
389 b.lengths.shift();
390 }
392 // Check if balancing is needed and return based on that.
393 var toRemove = calcToRemove(a, b);
394 if (toRemove <= E || b.table.length == 0) {
395 return [a,b];
396 }
398 return shuffle(a, b, toRemove);
399 }
401 // Returns the extra search steps for E. Refer to the paper.
402 function calcToRemove(a, b) {
403 var subLengths = 0;
404 for (var i = 0; i < a.table.length; i++) {
405 subLengths += a.table[i].table.length;
406 }
407 for (var i = 0; i < b.table.length; i++) {
408 subLengths += b.table[i].table.length;
409 }
411 var toRemove = a.table.length + b.table.length
412 return toRemove - (Math.floor((subLengths - 1) / M) + 1);
413 }
415 // get2, set2 and saveSlot are helpers for accessing elements over two arrays.
416 function get2(a, b, index) {
417 return index < a.length ? a[index] : b[index - a.length];
418 }
420 function set2(a, b, index, value) {
421 if (index < a.length) {
422 a[index] = value;
423 } else {
424 b[index - a.length] = value;
425 }
426 }
428 function saveSlot(a, b, index, slot) {
429 set2(a.table, b.table, index, slot);
431 var l = (index == 0 || index == a.lengths.length) ?
432 0 : get2(a.lengths, a.lengths, index - 1);
433 set2(a.lengths, b.lengths, index, l + length(slot));
434 }
436 // Creates a node or leaf with a given length at their arrays for perfomance.
437 // Is only used by shuffle.
438 function createNode(h, length) {
439 if (length < 0) { length = 0; }
440 var a = { ctor:"_Array", height:h, table:new Array(length) };
441 if (h > 0) {
442 a.lengths = new Array(length);
443 }
444 return a;
445 }
447 // Returns an array of two balanced nodes.
448 function shuffle(a, b, toRemove) {
449 var newA = createNode(a.height, Math.min(M, a.table.length + b.table.length - toRemove));
450 var newB = createNode(a.height, newA.table.length - (a.table.length + b.table.length - toRemove));
452 // Skip the slots with size M. More precise: copy the slot references
453 // to the new node
454 var read = 0;
455 while (get2(a.table, b.table, read).table.length % M == 0) {
456 set2(newA.table, newB.table, read, get2(a.table, b.table, read));
457 set2(newA.lengths, newB.lengths, read, get2(a.lengths, b.lengths, read));
458 read++;
459 }
461 // Pulling items from left to right, caching in a slot before writing
462 // it into the new nodes.
463 var write = read;
464 var slot = new createNode(a.height - 1, 0);
465 var from = 0;
467 // If the current slot is still containing data, then there will be at
468 // least one more write, so we do not break this loop yet.
469 while (read - write - (slot.table.length > 0 ? 1 : 0) < toRemove) {
470 // Find out the max possible items for copying.
471 var source = get2(a.table, b.table, read);
472 var to = Math.min(M - slot.table.length, source.table.length)
474 // Copy and adjust size table.
475 slot.table = slot.table.concat(source.table.slice(from, to));
476 if (slot.height > 0) {
477 var len = slot.lengths.length;
478 for (var i = len; i < len + to - from; i++) {
479 slot.lengths[i] = length(slot.table[i]);
480 slot.lengths[i] += (i > 0 ? slot.lengths[i - 1] : 0);
481 }
482 }
484 from += to;
486 // Only proceed to next slots[i] if the current one was
487 // fully copied.
488 if (source.table.length <= to) {
489 read++; from = 0;
490 }
492 // Only create a new slot if the current one is filled up.
493 if (slot.table.length == M) {
494 saveSlot(newA, newB, write, slot);
495 slot = createNode(a.height - 1,0);
496 write++;
497 }
498 }
500 // Cleanup after the loop. Copy the last slot into the new nodes.
501 if (slot.table.length > 0) {
502 saveSlot(newA, newB, write, slot);
503 write++;
504 }
506 // Shift the untouched slots to the left
507 while (read < a.table.length + b.table.length ) {
508 saveSlot(newA, newB, write, get2(a.table, b.table, read));
509 read++; write++;
510 }
512 return [newA, newB];
513 }
515 // Navigation functions
516 function botRight(a) { return a.table[a.table.length - 1]; }
517 function botLeft(a) { return a.table[0]; }
519 // Copies a node for updating. Note that you should not use this if
520 // only updating only one of "table" or "lengths" for performance reasons.
521 function nodeCopy(a) {
522 var newA = { ctor:"_Array", height:a.height
523 , table:a.table.slice() };
524 if (a.height > 0) { newA.lengths = a.lengths.slice(); }
525 return newA;
526 }
528 // Returns how many items are in the tree.
529 function length(array) {
530 if (array.height == 0) {
531 return array.table.length;
532 } else {
533 return array.lengths[array.lengths.length - 1];
534 }
535 }
537 // Calculates in which slot of "table" the item probably is, then
538 // find the exact slot via forward searching in "lengths". Returns the index.
539 function getSlot(i, a) {
540 var slot = i >> (5 * a.height);
541 while (a.lengths[slot - 1] > i) { slot--; }
542 return slot;
543 }
545 // Recursively creates a tree with a given height containing
546 // only the given item.
547 function create(item, h) {
548 if (h == 0) {
549 return { ctor:"_Array", height:0
550 , table:[item] };
551 } else {
552 return { ctor:"_Array", height:h
553 , table:[create(item, h - 1)]
554 , lengths:[1] };
555 }
556 }
558 // Recursively creates a tree that contains the given tree.
559 function parentise(tree, h) {
560 if (h == tree.height) {
561 return tree;
562 } else {
563 return { ctor:"_Array", height:h
564 , table:[parentise(tree, h - 1)]
565 , lengths:[length(tree)] };
566 }
567 }
569 // Emphasizes blood brotherhood beneath two trees.
570 function siblise(a, b) {
571 return { ctor:"_Array", height:a.height + 1
572 , table:[a, b]
573 , lengths:[length(a), length(a) + length(b)] };
574 }
576 function toJSArray(a) {
577 var jsArray = new Array(length(a));
578 toJSArray_(jsArray, 0, a);
579 return jsArray;
580 }
582 function toJSArray_(jsArray, i, a) {
583 for (var t = 0; t < a.table.length; t++) {
584 if (a.height == 0) {
585 jsArray[i + t] = a.table[t];
586 } else {
587 var inc = t == 0 ? 0 : a.lengths[t - 1];
588 toJSArray_(jsArray, i + inc, a.table[t]);
589 }
590 }
591 }
593 function fromJSArray(jsArray) {
594 if (jsArray.length == 0) { return empty; }
595 var h = Math.floor(Math.log(jsArray.length) / Math.log(M));
596 return fromJSArray_(jsArray, h, 0, jsArray.length);
597 }
599 function fromJSArray_(jsArray, h, from, to) {
600 if (h == 0) {
601 return { ctor:"_Array", height:0
602 , table:jsArray.slice(from, to) };
603 }
605 var step = Math.pow(M, h);
606 var table = new Array(Math.ceil((to - from) / step));
607 var lengths = new Array(table.length);
608 for (var i = 0; i < table.length; i++) {
609 table[i] = fromJSArray_( jsArray, h - 1, from + (i * step)
610 , Math.min(from + ((i + 1) * step), to));
611 lengths[i] = length(table[i]) + (i > 0 ? lengths[i-1] : 0);
612 }
613 return { ctor:"_Array", height:h, table:table, lengths:lengths };
614 }
616 Elm.Native.Array.values = {
617 empty:empty,
618 fromList:fromList,
619 toList:toList,
620 initialize:F2(initialize),
621 append:F2(append),
622 push:F2(push),
623 slice:F3(slice),
624 get:F2(get),
625 set:F3(set),
626 map:F2(map),
627 indexedMap:F2(indexedMap),
628 foldl:F3(foldl),
629 foldr:F3(foldr),
630 length:length,
632 toJSArray:toJSArray,
633 fromJSArray:fromJSArray
634 };
636 return elm.Native.Array.values = Elm.Native.Array.values;