on e13195c help sign in
elk/libraries/Native/Array.js
663 lines 21 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 while (array.lengths[slot] <= i) {
39 slot++;
40 }
41 if (slot > 0) {
42 i -= array.lengths[slot - 1];
43 }
44 array = array.table[slot];
45 }
46 return array.table[i];
47 }
49 // Sets the value at the index i. Only the nodes leading to i will get
50 // copied and updated.
51 function set(i, item, array) {
52 if (i < 0 || length(array) <= i) {
53 return array;
54 }
55 return unsafeSet(i, item, array);
56 }
58 function unsafeSet(i, item, array) {
59 array = nodeCopy(array);
61 if (array.height == 0) {
62 array.table[i] = item;
63 } else {
64 var slot = getSlot(i, array);
65 if (slot > 0) {
66 i -= array.lengths[slot - 1];
67 }
68 array.table[slot] = unsafeSet(i, item, array.table[slot]);
69 }
70 return array;
71 }
73 function initialize(len, f) {
74 if (len == 0) { return empty; }
75 var h = Math.floor(Math.log(len)/Math.log(M));
76 return initialize_(f, h, 0, len);
77 }
79 function initialize_(f, h, from, to) {
80 if (h == 0) {
81 var table = new Array((to - from) % (M + 1));
82 for (var i = 0; i < table.length; i++) {
83 table[i] = f(from + i);
84 }
85 return { ctor:"_Array", height:0, table:table };
86 }
88 var step = Math.pow(M, h);
89 var table = new Array(Math.ceil((to - from) / step));
90 var lengths = new Array(table.length);
91 for (var i = 0; i < table.length; i++) {
92 table[i] = initialize_( f, h - 1, from + (i * step)
93 , Math.min(from + ((i + 1) * step), to));
94 lengths[i] = length(table[i]) + (i > 0 ? lengths[i-1] : 0);
95 }
96 return { ctor:"_Array", height:h, table:table, lengths:lengths };
97 }
99 function fromList(list) {
100 if (list == List.Nil) { return empty; }
102 // Allocate M sized blocks (table) and write list elements to it.
103 var table = new Array(M);
104 var nodes = new Array();
105 var i = 0;
107 while (list.ctor !== '[]') {
108 table[i] = list._0;
109 list = list._1;
110 i++;
112 // table is full, so we can push a leaf containing it into the
113 // next node.
114 if (i == M) {
115 fromListPush({ ctor:"_Array", height:0, table:table }
116 , nodes);
117 table = new Array(M);
118 i = 0;
119 }
120 }
122 // Maybe there is something left on the table.
123 if (i > 0) {
124 fromListPush({ ctor:"_Array", height:0, table:table.splice(0,i) }
125 , nodes);
126 }
128 // Go through all of the nodes and eventually push them into higher nodes.
129 for (var h = 0; h < nodes.length - 1; h++) {
130 if (nodes[h].table.length > 0) {
131 fromListPush(nodes[h], nodes);
132 }
133 }
135 var head = nodes[nodes.length - 1];
136 if (head.height > 0 && head.table.length == 1) {
137 return head.table[0];
138 } else {
139 return head;
140 }
141 }
143 // Push a node into a higher node as a child.
144 function fromListPush(toPush, nodes) {
145 var h = toPush.height;
147 // Maybe the node on this height does not exist.
148 if (nodes.length == h) {
149 nodes.push({ ctor:"_Array", height:h + 1
150 , table:new Array()
151 , lengths:new Array() });
152 }
154 nodes[h].table.push(toPush);
155 var len = length(toPush);
156 if (nodes[h].lengths.length > 0) {
157 len += nodes[h].lengths[nodes[h].lengths.length - 1];
158 }
159 nodes[h].lengths.push(len);
161 if (nodes[h].table.length == M) {
162 fromListPush(nodes[h], nodes);
163 nodes[h] = { ctor:"_Array", height:h + 1
164 , table:new Array()
165 , lengths:new Array() };
166 }
167 }
169 // Pushes an item via push_ to the bottom right of a tree.
170 function push(item, a) {
171 var pushed = push_(item, a);
172 if (pushed !== null) {
173 return pushed;
174 }
176 var newTree = create(item, a.height);
177 return siblise(a, newTree);
178 }
180 // Recursively tries to push an item to the bottom-right most
181 // tree possible. If there is no space left for the item,
182 // null will be returned.
183 function push_(item, a) {
184 // Handle resursion stop at leaf level.
185 if (a.height == 0) {
186 if (a.table.length < M) {
187 var newA = { ctor:"_Array", height:0, table:a.table.slice() };
188 newA.table.push(item);
189 return newA;
190 } else {
191 return null;
192 }
193 }
195 // Recursively push
196 var pushed = push_(item, botRight(a));
198 // There was space in the bottom right tree, so the slot will
199 // be updated.
200 if (pushed != null) {
201 var newA = nodeCopy(a);
202 newA.table[newA.table.length - 1] = pushed;
203 newA.lengths[newA.lengths.length - 1]++;
204 return newA
205 }
207 // When there was no space left, check if there is space left
208 // for a new slot with a tree which contains only the item
209 // at the bottom.
210 if (a.table.length < M) {
211 var newSlot = create(item, a.height - 1);
212 var newA = nodeCopy(a);
213 newA.table.push(newSlot);
214 newA.lengths.push(newA.lengths[newA.lengths.length - 1] + length(newSlot));
215 return newA
216 } else {
217 return null;
218 }
219 }
221 // Converts an array into a list of elements.
222 function toList(a) {
223 return toList_(List.Nil, a);
224 }
226 function toList_(list, a) {
227 for (var i = a.table.length - 1; i >= 0; i--) {
228 list = a.height == 0 ? List.Cons(a.table[i], list) : toList_(list, a.table[i]);
229 }
230 return list;
231 }
233 // Maps a function over the elements of an array.
234 function map(f, a) {
235 var newA = { ctor:"_Array", height:a.height, table:new Array(a.table) };
236 if (a.height > 0) { newA.lengths = a.lengths; }
237 for (var i = 0; i < a.table.length; i++) {
238 newA.table[i] = a.height == 0 ? f(a.table[i]) : map(f, a.table[i]);
239 }
240 return newA;
241 }
243 // Maps a function over the elements with their index as first argument.
244 function indexedMap(f, a) {
245 return indexedMap_(f, a, 0);
246 }
248 function indexedMap_(f, a, from) {
249 var newA = { ctor:"_Array", height:a.height, table:new Array(a.table) };
250 if (a.height > 0) { newA.lengths = a.lengths; }
251 for (var i = 0; i < a.table.length; i++) {
252 newA.table[i] = a.height == 0 ? A2(f, from + i, a.table[i])
253 : indexedMap_( f, a.table[i]
254 , i == 0 ? 0 : a.lengths[i - 1]);
255 }
256 return newA;
257 }
259 function foldl(f, b, a) {
260 if (a.height == 0) {
261 for (var i = 0; i < a.table.length; i++) {
262 b = A2(f, a.table[i], b);
263 }
264 } else {
265 for (var i = 0; i < a.table.length; i++) {
266 b = foldl(f, b, a.table[i]);
267 }
268 }
269 return b;
270 }
272 function foldr(f, b, a) {
273 if (a.height == 0) {
274 for (var i = a.table.length; i--; ) {
275 b = A2(f, a.table[i], b);
276 }
277 } else {
278 for (var i = a.table.length; i--; ) {
279 b = foldl(f, b, a.table[i]);
280 }
281 }
282 return b;
283 }
285 // TODO: currently, it slices the right, then the left. This can be
286 // optimized.
287 function slice(from, to, a) {
288 if (from < 0) { from += length(a); }
289 if (to < 0) { to += length(a); }
290 return sliceLeft(from, sliceRight(to, a));
291 }
293 function sliceRight(to, a) {
294 if (to == length(a)) {
295 return a;
296 }
298 // Handle leaf level.
299 if (a.height == 0) {
300 var newA = { ctor:"_Array", height:0 };
301 newA.table = a.table.slice(0, to);
302 return newA;
303 }
305 // Slice the right recursively.
306 var right = getSlot(to, a);
307 var sliced = sliceRight(to - (right > 0 ? a.lengths[right - 1] : 0), a.table[right]);
309 // Maybe the a node is not even needed, as sliced contains the whole slice.
310 if (right == 0) {
311 return sliced;
312 }
314 // Create new node.
315 var newA = { ctor:"_Array", height:a.height
316 , table:a.table.slice(0, right)
317 , lengths:a.lengths.slice(0, right) };
318 if (sliced.table.length > 0) {
319 newA.table[right] = sliced;
320 newA.lengths[right] = length(sliced) + (right > 0 ? newA.lengths[right - 1] : 0);
321 }
322 return newA;
323 }
325 function sliceLeft(from, a) {
326 if (from == 0) {
327 return a;
328 }
330 // Handle leaf level.
331 if (a.height == 0) {
332 var newA = { ctor:"_Array", height:0 };
333 newA.table = a.table.slice(from, a.table.length + 1);
334 return newA;
335 }
337 // Slice the left recursively.
338 var left = getSlot(from, a);
339 var sliced = sliceLeft(from - (left > 0 ? a.lengths[left - 1] : 0), a.table[left]);
341 // Maybe the a node is not even needed, as sliced contains the whole slice.
342 if (left == a.table.length - 1) {
343 return sliced;
344 }
346 // Create new node.
347 var newA = { ctor:"_Array", height:a.height
348 , table:a.table.slice(left, a.table.length + 1)
349 , lengths:new Array(a.table.length - left) };
350 newA.table[0] = sliced;
351 var len = 0;
352 for (var i = 0; i < newA.table.length; i++) {
353 len += length(newA.table[i]);
354 newA.lengths[i] = len;
355 }
357 return newA;
358 }
360 // Appends two trees.
361 // TODO: Add support for appending trees of different sizes. Current
362 // behavior will just rise the lower tree and then append them.
363 function append(a,b) {
364 if (a.table.length == 0) return b;
365 if (b.table.length == 0) return a;
366 if (b.height > a.height) return append(parentise(a, b.height), b);
367 if (a.height > b.height) return append(a, parentise(b, a.height));
368 if (a.height == 0) return append(parentise(a, 1), parentise(b, 1));
370 var c = append_(a, b);
371 if (c[1].table.length > 0) {
372 return siblise(c[0], c[1]);
373 } else {
374 return c[0];
375 }
376 }
378 // Returns an array of two nodes. The second node _may_ be empty. This case
379 // needs to be handled by the function, that called append_. May be only
380 // called for trees with an minimal height of 1.
381 function append_(a, b) {
382 if (a.height == 1) {
383 // Check if balancing is needed and return based on that.
384 var toRemove = calcToRemove(a, b);
385 if (toRemove <= E) {
386 return [a,b];
387 }
389 return shuffle(a, b, toRemove);
390 }
392 var appended = append_(botRight(a), botLeft(b));
393 a = nodeCopy(a), b = nodeCopy(b);
395 // Adjust the bottom right side of the new tree.
396 a.table[a.table.length - 1] = appended[0];
397 a.lengths[a.lengths.length - 1] = length(appended[0])
398 a.lengths[a.lengths.length - 1] += a.lengths.length > 1 ? a.lengths[a.lengths.length - 2] : 0;
400 // Adjust the bottom left side of the new tree.
401 if (appended[1].table.length > 0) {
402 b.table[0] = appended[1];
403 b.lengths[0] = length(appended[1]);
404 for (var i = 1, len = length(b.table[0]); i < b.lengths.length; i++) {
405 len += length(b.table[i]);
406 b.lengths[i] = len;
407 }
408 } else {
409 b.table.shift();
410 for (var i = 1; i < b.lengths.length; i++) {
411 b.lengths[i] = b.lengths[i] - b.lengths[0];
412 }
413 b.lengths.shift();
414 }
416 // Check if balancing is needed and return based on that.
417 var toRemove = calcToRemove(a, b);
418 if (toRemove <= E || b.table.length == 0) {
419 return [a,b];
420 }
422 return shuffle(a, b, toRemove);
423 }
425 // Returns the extra search steps for E. Refer to the paper.
426 function calcToRemove(a, b) {
427 var subLengths = 0;
428 for (var i = 0; i < a.table.length; i++) {
429 subLengths += a.table[i].table.length;
430 }
431 for (var i = 0; i < b.table.length; i++) {
432 subLengths += b.table[i].table.length;
433 }
435 var toRemove = a.table.length + b.table.length
436 return toRemove - (Math.floor((subLengths - 1) / M) + 1);
437 }
439 // get2, set2 and saveSlot are helpers for accessing elements over two arrays.
440 function get2(a, b, index) {
441 return index < a.length ? a[index] : b[index - a.length];
442 }
444 function set2(a, b, index, value) {
445 if (index < a.length) {
446 a[index] = value;
447 } else {
448 b[index - a.length] = value;
449 }
450 }
452 function saveSlot(a, b, index, slot) {
453 set2(a.table, b.table, index, slot);
455 var l = (index == 0 || index == a.lengths.length) ?
456 0 : get2(a.lengths, a.lengths, index - 1);
457 set2(a.lengths, b.lengths, index, l + length(slot));
458 }
460 // Creates a node or leaf with a given length at their arrays for perfomance.
461 // Is only used by shuffle.
462 function createNode(h, length) {
463 if (length < 0) { length = 0; }
464 var a = { ctor:"_Array", height:h, table:new Array(length) };
465 if (h > 0) {
466 a.lengths = new Array(length);
467 }
468 return a;
469 }
471 // Returns an array of two balanced nodes.
472 function shuffle(a, b, toRemove) {
473 var newA = createNode(a.height, Math.min(M, a.table.length + b.table.length - toRemove));
474 var newB = createNode(a.height, newA.table.length - (a.table.length + b.table.length - toRemove));
476 // Skip the slots with size M. More precise: copy the slot references
477 // to the new node
478 var read = 0;
479 while (get2(a.table, b.table, read).table.length % M == 0) {
480 set2(newA.table, newB.table, read, get2(a.table, b.table, read));
481 set2(newA.lengths, newB.lengths, read, get2(a.lengths, b.lengths, read));
482 read++;
483 }
485 // Pulling items from left to right, caching in a slot before writing
486 // it into the new nodes.
487 var write = read;
488 var slot = new createNode(a.height - 1, 0);
489 var from = 0;
491 // If the current slot is still containing data, then there will be at
492 // least one more write, so we do not break this loop yet.
493 while (read - write - (slot.table.length > 0 ? 1 : 0) < toRemove) {
494 // Find out the max possible items for copying.
495 var source = get2(a.table, b.table, read);
496 var to = Math.min(M - slot.table.length, source.table.length)
498 // Copy and adjust size table.
499 slot.table = slot.table.concat(source.table.slice(from, to));
500 if (slot.height > 0) {
501 var len = slot.lengths.length;
502 for (var i = len; i < len + to - from; i++) {
503 slot.lengths[i] = length(slot.table[i]);
504 slot.lengths[i] += (i > 0 ? slot.lengths[i - 1] : 0);
505 }
506 }
508 from += to;
510 // Only proceed to next slots[i] if the current one was
511 // fully copied.
512 if (source.table.length <= to) {
513 read++; from = 0;
514 }
516 // Only create a new slot if the current one is filled up.
517 if (slot.table.length == M) {
518 saveSlot(newA, newB, write, slot);
519 slot = createNode(a.height - 1,0);
520 write++;
521 }
522 }
524 // Cleanup after the loop. Copy the last slot into the new nodes.
525 if (slot.table.length > 0) {
526 saveSlot(newA, newB, write, slot);
527 write++;
528 }
530 // Shift the untouched slots to the left
531 while (read < a.table.length + b.table.length ) {
532 saveSlot(newA, newB, write, get2(a.table, b.table, read));
533 read++; write++;
534 }
536 return [newA, newB];
537 }
539 // Navigation functions
540 function botRight(a) { return a.table[a.table.length - 1]; }
541 function botLeft(a) { return a.table[0]; }
543 // Copies a node for updating. Note that you should not use this if
544 // only updating only one of "table" or "lengths" for performance reasons.
545 function nodeCopy(a) {
546 var newA = { ctor:"_Array", height:a.height
547 , table:a.table.slice() };
548 if (a.height > 0) { newA.lengths = a.lengths.slice(); }
549 return newA;
550 }
552 // Returns how many items are in the tree.
553 function length(array) {
554 if (array.height == 0) {
555 return array.table.length;
556 } else {
557 return array.lengths[array.lengths.length - 1];
558 }
559 }
561 // Calculates in which slot of "table" the item probably is, then
562 // find the exact slot via forward searching in "lengths". Returns the index.
563 function getSlot(i, a) {
564 var slot = i >> (5 * a.height);
565 while (a.lengths[slot] <= i) {
566 slot++;
567 }
568 return slot;
569 }
571 // Recursively creates a tree with a given height containing
572 // only the given item.
573 function create(item, h) {
574 if (h == 0) {
575 return { ctor:"_Array", height:0
576 , table:[item] };
577 } else {
578 return { ctor:"_Array", height:h
579 , table:[create(item, h - 1)]
580 , lengths:[1] };
581 }
582 }
584 // Recursively creates a tree that contains the given tree.
585 function parentise(tree, h) {
586 if (h == tree.height) {
587 return tree;
588 } else {
589 return { ctor:"_Array", height:h
590 , table:[parentise(tree, h - 1)]
591 , lengths:[length(tree)] };
592 }
593 }
595 // Emphasizes blood brotherhood beneath two trees.
596 function siblise(a, b) {
597 return { ctor:"_Array", height:a.height + 1
598 , table:[a, b]
599 , lengths:[length(a), length(a) + length(b)] };
600 }
602 function toJSArray(a) {
603 var jsArray = new Array(length(a));
604 toJSArray_(jsArray, 0, a);
605 return jsArray;
606 }
608 function toJSArray_(jsArray, i, a) {
609 for (var t = 0; t < a.table.length; t++) {
610 if (a.height == 0) {
611 jsArray[i + t] = a.table[t];
612 } else {
613 var inc = t == 0 ? 0 : a.lengths[t - 1];
614 toJSArray_(jsArray, i + inc, a.table[t]);
615 }
616 }
617 }
619 function fromJSArray(jsArray) {
620 if (jsArray.length == 0) { return empty; }
621 var h = Math.floor(Math.log(jsArray.length) / Math.log(M));
622 return fromJSArray_(jsArray, h, 0, jsArray.length);
623 }
625 function fromJSArray_(jsArray, h, from, to) {
626 if (h == 0) {
627 return { ctor:"_Array", height:0
628 , table:jsArray.slice(from, to) };
629 }
631 var step = Math.pow(M, h);
632 var table = new Array(Math.ceil((to - from) / step));
633 var lengths = new Array(table.length);
634 for (var i = 0; i < table.length; i++) {
635 table[i] = fromJSArray_( jsArray, h - 1, from + (i * step)
636 , Math.min(from + ((i + 1) * step), to));
637 lengths[i] = length(table[i]) + (i > 0 ? lengths[i-1] : 0);
638 }
639 return { ctor:"_Array", height:h, table:table, lengths:lengths };
640 }
642 Elm.Native.Array.values = {
643 empty:empty,
644 fromList:fromList,
645 toList:toList,
646 initialize:F2(initialize),
647 append:F2(append),
648 push:F2(push),
649 slice:F3(slice),
650 get:F2(get),
651 set:F3(set),
652 map:F2(map),
653 indexedMap:F2(indexedMap),
654 foldl:F3(foldl),
655 foldr:F3(foldr),
656 length:length,
658 toJSArray:toJSArray,
659 fromJSArray:fromJSArray
660 };
662 return elm.Native.Array.values = Elm.Native.Array.values;