Iter.js 21 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
/***

MochiKit.Iter 0.80

See <http://mochikit.com/> for documentation, downloads, license, etc.

(c) 2005 Bob Ippolito.  All rights Reserved.

***/
if (typeof(dojo) != 'undefined') {
    dojo.provide('MochiKit.Iter');
    dojo.require('MochiKit.Base');
}

if (typeof(JSAN) != 'undefined') {
    JSAN.use("MochiKit.Base", []);
}   

try {
    if (typeof(MochiKit.Base) == 'undefined') {
        throw "";
    }
} catch (e) {
    throw "MochiKit.Iter depends on MochiKit.Base!";
}  
            
if (typeof(MochiKit.Iter) == 'undefined') {
    MochiKit.Iter = {};
}           
        
MochiKit.Iter.NAME = "MochiKit.Iter";
MochiKit.Iter.VERSION = "0.80";
MochiKit.Iter.__repr__ = function () {
    return "[" + this.NAME + " " + this.VERSION + "]";
}
MochiKit.Iter.toString = function () {
    return this.__repr__();
}

MochiKit.Iter.registerIteratorFactory = function (name, check, iterfactory, /* optional */ override) {
    /***

        Register an iterator factory for use with the iter function.

        check is a function (a) that returns true if a can be converted
        into an iterator with iterfactory.

        iterfactory is a function (a) that returns an object with a
        "next" function that returns the next value in the sequence.

        iterfactory is guaranteed to only be called if check(a)
        returns a true value.

        If override is given and true, then it will be made the
        highest precedence iterator factory.  Otherwise, the lowest.

    ***/

    MochiKit.Iter.iteratorRegistry.register(name, check, iterfactory, override);
};

MochiKit.Iter.iter = function (iterable, /* optional */ sentinel) {
    /***

        Convert the given argument to an iterator (object implementing
        "next").
        
        1. If iterable is an iterator (implements "next"), then it will be
           returned as-is.
        2. If iterable is an iterator factory (implements "iter"), then the
           result of iterable.iter() will be returned.
        3. Otherwise, the iterator factory registry is used to find a 
           match.
        4. If no factory is found, it will throw TypeError

        When used directly, using an iterator should look like this::

            var it = iter(iterable);
            try {
                while (var o = it.next()) {
                    // use o
                }
            } catch (e) {
                if (e != StopIteration) {
                    throw e;
                }
                // pass
            }

    ***/
    
    if (arguments.length == 2) {
        return MochiKit.Iter.takewhile(
            function (a) { return a != sentinel; },
            iterable);
    }
    if (typeof(iterable.next) == 'function') {
        return iterable;
    } else if (typeof(iterable.iter) == 'function') {
        return iterable.iter();
    }
    try {
        return MochiKit.Iter.iteratorRegistry.match(iterable);
    } catch (e) {
        if (e == MochiKit.Base.NotFound) {
            e = new TypeError(typeof(iterable) + ": " + MochiKit.Base.repr(iterable) + " is not iterable");
        }
        throw e;
    }
};

MochiKit.Iter.count = function (n) {
    /***

        count([n]) --> n, n + 1, n + 2, ...

    ***/
    if (!n) {
        n = 0;
    }
    return {
        "repr": function () { return "count(" + n + ")"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () { return n++; }
    };
};

MochiKit.Iter.cycle = function (p) {
    /***

        cycle(p) --> p0, p1, ... plast, p0, p1, ...

    ***/
    var lst = [];
    var iterator = MochiKit.Iter.iter(p);
    return {
        "repr": function () { return "cycle(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            try {
                var rval = iterator.next();
                lst.push(rval);
                return rval;
            } catch (e) {
                if (e != MochiKit.Iter.StopIteration) {
                    throw e;
                }
                if (lst.length == 0) {
                    this.next = function () {
                        throw MochiKit.Iter.StopIteration;
                    };
                } else {
                    var i = -1;
                    this.next = function () {
                        i = (i + 1) % lst.length;
                        return lst[i];
                    }
                }
                return this.next();
            }
        }
    }
};

MochiKit.Iter.repeat = function (elem, /* optional */n) {
    /***
    
        repeat(elem, [,n]) --> elem, elem, elem, ... endlessly or up to n
            times

    ***/
    if (typeof(n) == 'undefined') {
        return {
            "repr": function () {
                return "repeat(" + MochiKit.Base.repr(elem) + ")";
            },
            "toString": MochiKit.Base.forward("repr"),
            "next": function () {
                return elem;
            }
        };
    }
    return {
        "repr": function () {
            return "repeat(" + MochiKit.Base.repr(elem) + ", " + n + ")";
        },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            if (n <= 0) {
                throw MochiKit.Iter.StopIteration;
            }
            n -= 1;
            return elem;
        }
    };
};
        
MochiKit.Iter.next = function (iterator) {
    /***

        Return the next value from the iterator

    ***/
    return iterator.next();
};

MochiKit.Iter.izip = function (p, q/*, ...*/) {
    /***

        izip(p, q, ...) --> (p0, q0, ...), (p1, q1, ...), ...

    ***/
    var map = MochiKit.Base.map;
    var next = MochiKit.Iter.next;
    var iterables = map(iter, arguments);
    return {
        "repr" : function () { return "izip(...)"; },
        "toString" : MochiKit.Base.forward("repr"),
        "next": function () { return map(next, iterables); }
    };
};

MochiKit.Iter.ifilter = function (pred, seq) {
    /***

        ifilter(pred, seq) --> elements of seq where pred(elem) is true

    ***/
    seq = MochiKit.Iter.iter(seq);
    if (pred == null) {
        pred = MochiKit.Base.operator.truth;
    }
    return {
        "repr": function () { return "ifilter(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            while (true) {
                var rval = seq.next();
                if (pred(rval)) {
                    return rval;
                }
            }
        }
    }
};

MochiKit.Iter.ifilterfalse = function (pred, seq) {
    /***

        ifilterfalse(pred, seq) --> elements of seq where pred(elem) is
            false

    ***/
    seq = MochiKit.Iter.iter(seq);
    if (pred == null) {
        pred = MochiKit.Base.operator.truth;
    }
    return {
        "repr": function () { return "ifilterfalse(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            while (true) {
                var rval = seq.next();
                if (!pred(rval)) {
                    return rval;
                }
            }
        }
    }
};
 
MochiKit.Iter.islice = function (seq/*, [start,] stop[, step] */) {
    /***

        islice(seq, [start,] stop[, step])  --> elements from 
            seq[start:stop:step] (in Python slice syntax)

    ***/
    seq = MochiKit.Iter.iter(seq);
    var start = 0;
    var stop = 0;
    var step = 1;
    var i = -1;
    if (arguments.length == 2) {
        stop = arguments[1];
    } else if (arguments.length == 3) {
        start = arguments[1];
        stop = arguments[2];
    } else {
        start = arguments[1];
        stop = arguments[2];
        step = arguments[3];
    }
    return {
        "repr": function () {
            return "islice(" + ["...", start, stop, step].join(", ") + ")";
        },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            var rval;
            while (i < start) {
                rval = seq.next();
                i++;
            }
            if (start >= stop) {
                throw MochiKit.Iter.StopIteration;
            }
            start += step;
            return rval;
        }
    };
};

MochiKit.Iter.imap = function (fun, p, q/*, ...*/) {
    /***

        imap(fun, p, q, ...) --> fun(p0, q0, ...), fun(p1, q1, ...), ...

    ***/
    var map = MochiKit.Base.map;
    var iterables = map(MochiKit.Iter.iter, MochiKit.Base.extend(null, arguments, 1));
    var next = MochiKit.Iter.next;
    return {
        "repr": function () { return "imap(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            return fun.apply(this, map(next, iterables));
        }
    };
};
    
MochiKit.Iter.applymap = function (fun, seq, self) {
    /***

        applymap(fun, seq) -->
            fun.apply(self, seq0), fun.apply(self, seq1), ...

    ***/
    seq = MochiKit.Iter.iter(seq);
    return {
        "repr": function () { return "applymap(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            return fun.apply(self, seq.next());
        }
    };
};

MochiKit.Iter.chain = function (p, q/*, ...*/) {
    /***

        chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ...

    ***/
    // dumb fast path
    var iter = MochiKit.Iter.iter;
    if (arguments.length == 1) {
        return iter(arguments[0]);
    }
    var argiter = MochiKit.Base.map(iter, arguments);
    var bind = MochiKit.Base.bind;
    return {
        "repr": function () { return "chain(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            while (argiter.length > 1) {
                try {
                    return argiter[0].next();
                } catch (e) {
                    if (e != MochiKit.Iter.StopIteration) {
                        throw e;
                    }
                    argiter.shift();
                }
            }
            if (argiter.length == 1) {
                // optimize last element
                var arg = argiter.shift();
                this.next = bind(arg.next, arg);
                return this.next();
            }
            throw MochiKit.Iter.StopIteration;
        }
    };
};

MochiKit.Iter.takewhile = function (pred, seq) {
    /***

        takewhile(pred, seq) --> seq[0], seq[1], ... until pred(seq[n])
            fails

    ***/
    seq = MochiKit.Iter.iter(seq);
    return {
        "repr": function () { return "takewhile(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            var rval = seq.next();
            if (!pred(rval)) {
                this.next = function () {
                    throw MochiKit.Iter.StopIteration;
                };
                throw MochiKit.Iter.StopIteration;
            }
            return rval;
        }
    };
};

MochiKit.Iter.dropwhile = function (pred, seq) {
    /***

        dropwhile(pred, seq) --> seq[n], seq[n + 1], starting when
            pred(seq[n]) fails

    ***/
    seq = MochiKit.Iter.iter(seq);
    var bind = MochiKit.Base.bind;
    return {
        "repr": function () { return "dropwhile(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            while (true) {
                var rval = seq.next();
                if (!pred(rval)) {
                    break;
                }
            }
            this.next = bind(seq.next, seq);
            return rval;
        }
    };
};

MochiKit.Iter._tee = function (ident, sync, iterable) {
    sync.pos[ident] = -1;
    var listMin = MochiKit.Base.listMin;
    return {
        "repr": function () { return "tee(" + ident + ", ...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            var rval;
            var i = sync.pos[ident];

            if (i == sync.max) {
                rval = iterable.next();
                sync.deque.push(rval);
                sync.max += 1;
                sync.pos[ident] += 1;
            } else {
                rval = sync.deque[i - sync.min];
                sync.pos[ident] += 1;
                if (i == sync.min && listMin(sync.pos) != sync.min) {
                    sync.min += 1;
                    sync.deque.shift();
                }
            }
            return rval;
        }
    };
};

MochiKit.Iter.tee = function (iterable, n/* = 2 */) {
    /***

        tee(it, n=2) --> (it1, it2, it3, ... itn) splits one iterator
            into n

    ***/
    var rval = [];
    var sync = {
        "pos": [],
        "deque": [],
        "max": -1,
        "min": -1
    };
    if (arguments.length == 1) {
        n = 2;
    }
    iterable = MochiKit.Iter.iter(iterable);
    var _tee = MochiKit.Iter._tee;
    for (var i = 0; i < n; i++) {
        rval.push(_tee(i, sync, iterable));
    }
    return rval;
};

MochiKit.Iter.list = function (iterable) {
    /***

        Convert an iterable to a new array

    ***/

    // Fast-path for Array and Array-like
    if (typeof(iterable.slice) == 'function') {
        return iterable.slice();
    } else if (MochiKit.Base.isArrayLike(iterable)) {
        return MochiKit.Base.concat(iterable);
    }

    iterable = MochiKit.Iter.iter(iterable);
    var rval = [];
    try {
        while (true) {
            rval.push(iterable.next());
        }
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
        return rval;
    }
};

    
MochiKit.Iter.reduce = function (fn, iterable, /* optional */initial) {
    /***
    
        Apply a fn = function (a, b) cumulatively to the items of an
        iterable from left to right, so as to reduce the iterable
        to a single value.

        For example::
        
            reduce(function (a, b) { return x + y; }, [1, 2, 3, 4, 5])

        calculates::

            ((((1 + 2) + 3) + 4) + 5).
        
        If initial is given, it is placed before the items of the sequence
        in the calculation, and serves as a default when the sequence is
        empty.

        Note that the above example could be written more clearly as::

            reduce(operator.add, [1, 2, 3, 4, 5])

        Or even simpler::

            sum([1, 2, 3, 4, 5])

    ***/
    var i = 0;
    var x = initial;
    iterable = MochiKit.Iter.iter(iterable);
    if (arguments.length < 3) {
        try {
            x = iterable.next();
        } catch (e) {
            if (e == MochiKit.Iter.StopIteration) {
                e = new TypeError("reduce() of empty sequence with no initial value");
            }
            throw e;
        }
        i++;
    }
    try {
        while (true) {
            x = fn(x, iterable.next());
        }
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
        return x;
    }
};

MochiKit.Iter.range = function (/* [start,] stop[, step] */) {
    /***

    Return an iterator containing an arithmetic progression of integers.
    range(i, j) returns iter([i, i + 1, i + 2, ..., j - 1]);
    start (!) defaults to 0.  When step is given, it specifies the
    increment (or decrement).  For example, range(4) returns
    iter([0, 1, 2, 3]).  The end point is omitted!  These are exactly the
    valid elements for an array of 4 elements.

    ***/
    var start = 0;
    var stop = 0;
    var step = 1;
    if (arguments.length == 1) {
        stop = arguments[0];
    } else if (arguments.length == 2) {
        start = arguments[0];
        stop = arguments[1];
    } else if (arguments.length == 3) {
        start = arguments[0];
        stop = arguments[1];
        step = arguments[2];
    } else {
        throw TypeError("range() takes 1, 2, or 3 arguments!");
    }
    return {
        "next": function () {
            if (start >= stop) {
                throw MochiKit.Iter.StopIteration;
            }
            var rval = start;
            start += step;
            return rval;
        },
        "repr": function () {
            return "range(" + [start, stop, step].join(", ") + ")";
        },
        "toString": MochiKit.Base.forward("repr")
    };
};
        
MochiKit.Iter.sum = function (iterable, start/* = 0 */) {
    /***

    Returns the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start' (with a default of 0).  When the sequence is
    empty, returns start.

    Equivalent to::

        reduce(operator.add, iterable, start);

    ***/
    var x = start ? start : 0;
    iterable = MochiKit.Iter.iter(iterable);
    try {
        while (true) {
            x += iterable.next();
        }
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
        return x;
    }
};
        
MochiKit.Iter.exhaust = function (iterable) {
    /***

        Exhausts an iterable without saving the results anywhere,
        like list(iterable) when you don't care what the output is.

    ***/

    iterable = MochiKit.Iter.iter(iterable);
    try {
        while (true) {
            iterable.next();
        }
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
    }
};

MochiKit.Iter.forEach = function (iterable, func, /* optional */self) {
    /***
    
        Call func for each item in iterable.

    ***/
    if (arguments.length > 2) {
        func = MochiKit.Base.bind(func, self);
    }
    // fast path for array
    if (MochiKit.Base.isArrayLike(iterable)) {
        for (var i = 0; i < iterable.length; i++) {
            func(iterable[i]);
        }
    } else {
        MochiKit.Iter.exhaust(MochiKit.Iter.imap(func, iterable));
    }
};

MochiKit.Iter.every = function (iterable, func) {
    /***

        Return true if func(item) is true for every item in iterable

    ***/
    try {
        MochiKit.Iter.ifilterfalse(func, iterable).next();
        return false;
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
        return true;
    }
};

MochiKit.Iter.sorted = function (iterable, /* optional */cmp) {
    /***

        Return a sorted array from iterable

    ***/
    var rval = MochiKit.Iter.list(iterable);
    if (arguments.length == 1) {
        cmp = MochiKit.Base.compare;
    }
    rval.sort(cmp);
    return rval;
};

MochiKit.Iter.reversed = function (iterable) {
    /***

        Return a reversed array from iterable.

    ***/
    var rval = MochiKit.Iter.list(iterable);
    rval.reverse();
    return rval;
};

MochiKit.Iter.some = function (iterable, func) {
    /***

        Return true if func(item) is true for at least one item in iterable

    ***/
    try {
        MochiKit.Iter.ifilter(func, iterable).next();
        return true;
    } catch (e) {
        if (e != MochiKit.Iter.StopIteration) {
            throw e;
        }
        return false;
    }
};

MochiKit.Iter.iextend = function (lst, iterable) {
    /***
        
        Just like list(iterable), except it pushes results on lst
    
    ***/
    
    if (MochiKit.Base.isArrayLike(iterable)) {
        // fast-path for array-like
        for (var i = 0; i < iterable.length; i++) {
            lst.push(iterable[i]);
        }
    } else {
        iterable = MochiKit.Iter.iter(iterable);
        try {
            while (true) {
                lst.push(iterable.next());
            }
        } catch (e) {
            if (e != MochiKit.Iter.StopIteration) {
                throw e;
            }
        }
    }
    return lst;
};


MochiKit.Iter.arrayLikeIter = function (iterable) {
    var i = 0;
    return {
        "repr": function () { return "arrayLikeIter(...)"; },
        "toString": MochiKit.Base.forward("repr"),
        "next": function () {
            if (i >= iterable.length) {
                throw MochiKit.Iter.StopIteration;
            }
            return iterable[i++];
        }
    };
};


MochiKit.Iter.EXPORT_OK = [
    "iteratorRegistry",
    "arrayLikeIter"
];

MochiKit.Iter.EXPORT = [
    "StopIteration",
    "registerIteratorFactory",
    "iter",
    "count",
    "cycle",
    "repeat",
    "next",
    "izip",
    "ifilter",
    "ifilterfalse",
    "islice",
    "imap",
    "applymap",
    "chain",
    "takewhile",
    "dropwhile",
    "tee",
    "list",
    "reduce",
    "range",
    "sum",
    "exhaust",
    "forEach",
    "every",
    "sorted",
    "reversed",
    "some",
    "iextend"
];

MochiKit.Iter.__new__ = function () {
    this.StopIteration = new MochiKit.Base.NamedError("StopIteration");
    this.iteratorRegistry = new MochiKit.Base.AdapterRegistry();
    // Register the iterator factory for arrays
    this.registerIteratorFactory(
        "arrayLike",
        MochiKit.Base.isArrayLike,
        this.arrayLikeIter
    );

    this.EXPORT_TAGS = {
        ":common": this.EXPORT,
        ":all": MochiKit.Base.concat(this.EXPORT, this.EXPORT_OK)
    };

    MochiKit.Base.nameFunctions(this);
        
};

MochiKit.Iter.__new__();

//
// XXX: Internet Explorer blows
//
reduce = MochiKit.Iter.reduce;

if ((typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
    || (typeof(MochiKit.__compat__) == 'boolean' && MochiKit.__compat__)) {
    (function (self) {
            var all = self.EXPORT_TAGS[":all"];
            for (var i = 0; i < all.length; i++) {
                this[all[i]] = self[all[i]];
            }
        })(MochiKit.Iter);
}