diff --git a/TODO b/TODO index 0245474..41f5301 100644 --- a/TODO +++ b/TODO @@ -76,6 +76,8 @@ DONE Fix marble hover and dragging styles for Firefox DONE Fix affordance animation stuck for combineLatest >>> v1.4.0 +DONE Added an alphabetical operators presentation and a switch to select one + TODO Fix visual semantics of concat diagram >>> diff --git a/dist/js/app.js b/dist/js/app.js index 45c6efd..2fde19d 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -1,16 +1,26918 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oy?1:x=rStartingLine&&lineNumber<=rEndingLine}function isNodeFrame(stackLine){return stackLine.indexOf("(module.js:")!==-1||stackLine.indexOf("(node.js:")!==-1}function captureLine(){if(!hasStacks){return}try{throw new Error}catch(e){var lines=e.stack.split("\n");var firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2];var fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber){return}rFileName=fileNameAndLineNumber[0];return fileNameAndLineNumber[1]}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1){return[attempt1[1],Number(attempt1[2])]}var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2){return[attempt2[1],Number(attempt2[2])]}var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3){return[attempt3[1],Number(attempt3[2])]}}var EmptyError=Rx.EmptyError=function(){this.message="Sequence contains no elements.";Error.call(this)};EmptyError.prototype=Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError=function(){this.message="Object has been disposed";Error.call(this)};ObjectDisposedError.prototype=Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError=function(){this.message="Argument out of range";Error.call(this)};ArgumentOutOfRangeError.prototype=Error.prototype;var NotSupportedError=Rx.NotSupportedError=function(message){this.message=message||"This operation is not supported";Error.call(this)};NotSupportedError.prototype=Error.prototype;var NotImplementedError=Rx.NotImplementedError=function(message){this.message=message||"This operation is not implemented";Error.call(this)};NotImplementedError.prototype=Error.prototype;var notImplemented=Rx.helpers.notImplemented=function(){throw new NotImplementedError};var notSupported=Rx.helpers.notSupported=function(){throw new NotSupportedError};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};var isIterable=Rx.helpers.isIterable=function(o){return o[$iterator$]!==undefined};var isArrayLike=Rx.helpers.isArrayLike=function(o){return o&&o.length!==undefined};Rx.helpers.iterator=$iterator$;var bindCallback=Rx.internals.bindCallback=function(func,thisArg,argCount){if(typeof thisArg==="undefined"){return func}switch(argCount){case 0:return function(){return func.call(thisArg)};case 1:return function(arg){return func.call(thisArg,arg)};case 2:return function(value,index){return func.call(thisArg,value,index)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)}}return function(){return func.apply(thisArg,arguments)}};var dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,supportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,stringProto=String.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{supportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){supportNodeClass=true}var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);var isObject=Rx.internals.isObject=function(value){var type=typeof value;return value&&(type=="function"||type=="object")||false};function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=dontEnumsLength;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index-1}})}}stackA.pop();stackB.pop();return result}var hasProp={}.hasOwnProperty,slice=Array.prototype.slice;var inherits=this.inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){for(var sources=[],i=1,len=arguments.length;i=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left0){var item=queue.dequeue();!item.isCancelled()&&item.invoke()}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue=new PriorityQueue(4);queue.enqueue(si);var result=tryCatch(runTrampoline)();queue=null;if(result===errorObj){return thrower(result.e)}}else{queue.enqueue(si)}return si.disposable}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired=function(){return!queue};return currentScheduler}();var scheduleMethod,clearMethod;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else if(!!root.WScript){localSetTimeout=function(fn,time){root.WScript.Sleep(time);fn()}}else{throw new NotSupportedError}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;clearMethod=function(handle){delete tasksByHandle[handle]};function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle)},0)}else{var task=tasksByHandle[handle];if(task){currentlyRunning=true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning=false;if(result===errorObj){return thrower(result.e)}}}}var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(isFunction(setImmediate)){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;setImmediate(function(){runTask(id)});return id}}else if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;process.nextTick(function(){runTask(id)});return id}}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random();function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length))}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else if(root.attachEvent){root.attachEvent("onmessage",onGlobalPostMessage)}else{root.onmessage=onGlobalPostMessage}scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;root.postMessage(MSG_PREFIX+currentId,"*");return id}}else if(!!root.MessageChannel){var channel=new root.MessageChannel;channel.port1.onmessage=function(e){runTask(e.data)};scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;channel.port2.postMessage(id);return id}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");var id=nextHandle++;tasksByHandle[id]=action;scriptElement.onreadystatechange=function(){runTask(id);scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement);return id}}else{scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;localSetTimeout(function(){runTask(id)},0);return id}}})();var timeoutScheduler=Scheduler.timeout=Scheduler["default"]=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime),disposable=new SingleAssignmentDisposable;if(dt===0){return scheduler.scheduleWithState(state,action)}var id=localSetTimeout(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(__super__){function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,__super__);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler;this._recursiveOriginal=null;this._recursiveWrapper=null;__super__.call(this,this._scheduler.now.bind(this._scheduler),scheduleNow,scheduleRelative,scheduleAbsolute)}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){ -if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind=kind;this.value=value;this.exception=exception;this._accept=accept;this._acceptObservable=acceptObservable;this.toString=toString}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var self=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){return new Notification("N",value,null,_accept,_acceptObservable,toString)}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(e){return new Notification("E",null,e,_accept,_acceptObservable,toString)}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){return new Notification("C",null,null,_accept,_acceptObservable,toString)}}();var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){return new AnonymousObserver(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){return new AnonymousObserver(function(x){return handler.call(thisArg,notificationCreateOnNext(x))},function(e){return handler.call(thisArg,notificationCreateOnError(e))},function(){return handler.call(thisArg,notificationCreateOnCompleted())})};Observer.prototype.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};Observer.prototype.makeSafe=function(disposable){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,disposable)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false;__super__.call(this)}AbstractObserver.prototype.next=notImplemented;AbstractObserver.prototype.error=notImplemented;AbstractObserver.prototype.completed=notImplemented;AbstractObserver.prototype.onNext=function(value){if(!this.isStopped){this.next(value)}};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(__super__){inherits(CheckedObserver,__super__);function CheckedObserver(observer){__super__.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();var res=tryCatch(this._observer.onNext).call(this._observer,value);this._state=0;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onError=function(err){this.checkAccess();var res=tryCatch(this._observer.onError).call(this._observer,err);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();var res=tryCatch(this._observer.onCompleted).call(this._observer);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(e){var self=this;this.queue.push(function(){self.observer.onError(e)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false,parent=this;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}try{work()}catch(ex){parent.queue=[];parent.hasFaulted=true;throw ex}self()}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(scheduler,observer,cancel){__super__.call(this,scheduler,observer);this._cancel=cancel}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};ObserveOnObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this._cancel&&this._cancel.dispose();this._cancel=null};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function Observable(subscribe){if(Rx.config.longStackSupport&&hasStacks){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var self=this;this._subscribe=function(observer){var oldOnError=observer.onError.bind(observer);observer.onError=function(err){makeStackTraceLong(err,self);oldOnError(err)};return subscribe.call(self,observer)}}else{this._subscribe=subscribe}}observableProto=Observable.prototype;observableProto.subscribe=observableProto.forEach=function(observerOrOnNext,onError,onCompleted){return this._subscribe(typeof observerOrOnNext==="object"?observerOrOnNext:observerCreate(observerOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();var ObservableBase=Rx.ObservableBase=function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function ObservableBase(){__super__.call(this,subscribe)}ObservableBase.prototype.subscribeCore=notImplemented;return ObservableBase}(Observable);var Enumerable=Rx.internals.Enumerable=function(){};var ConcatEnumerableObservable=function(__super__){inherits(ConcatEnumerableObservable,__super__);function ConcatEnumerableObservable(sources){this.sources=sources;__super__.call(this)}ConcatEnumerableObservable.prototype.subscribeCore=function(o){var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](),function(e,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(new InnerObserver(o,self,e)))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};function InnerObserver(o,s,e){this.o=o;this.s=s;this.e=e;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.o.onNext(x)}};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.s(this.e)}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err);return true}return false};return ConcatEnumerableObservable}(ObservableBase);Enumerable.prototype.concat=function(){return new ConcatEnumerableObservable(this)};var CatchErrorObservable=function(__super__){inherits(CatchErrorObservable,__super__);function CatchErrorObservable(sources){this.sources=sources;__super__.call(this)}CatchErrorObservable.prototype.subscribeCore=function(o){var e=this.sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return lastException!==null?o.onError(lastException):o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},self,function(){o.onCompleted()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};return CatchErrorObservable}(ObservableBase);Enumerable.prototype.catchError=function(){return new CatchErrorObservable(this)};Enumerable.prototype.catchErrorWhen=function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject,notifier=new Subject,handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){if(lastException){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable;var inner=new SingleAssignmentDisposable;subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex)},function(){o.onCompleted()}));exceptions.onNext(exn)},function(){o.onCompleted()}))});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var RepeatEnumerable=function(__super__){inherits(RepeatEnumerable,__super__);function RepeatEnumerable(v,c){this.v=v;this.c=c==null?-1:c}RepeatEnumerable.prototype[$iterator$]=function(){return new RepeatEnumerator(this)};function RepeatEnumerator(p){this.v=p.v;this.l=p.c}RepeatEnumerator.prototype.next=function(){if(this.l===0){return doneEnumerator}if(this.l>0){this.l--}return{done:false,value:this.v}};return RepeatEnumerable}(Enumerable);var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){return new RepeatEnumerable(value,repeatCount)};var OfEnumerable=function(__super__){inherits(OfEnumerable,__super__);function OfEnumerable(s,fn,thisArg){this.s=s;this.fn=fn?bindCallback(fn,thisArg,3):null}OfEnumerable.prototype[$iterator$]=function(){return new OfEnumerator(this)};function OfEnumerator(p){this.i=-1;this.s=p.s;this.l=this.s.length;this.fn=p.fn}OfEnumerator.prototype.next=function(){return++this.imaxSafeInteger){return maxSafeInteger}return len}var observableFrom=Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isFunction(mapFn)){throw new Error("mapFn when provided must be a function")}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2)}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler)};var FromArrayObservable=function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args=args;this.scheduler=scheduler;__super__.call(this)}FromArrayObservable.prototype.subscribeCore=function(observer){var sink=new FromArraySink(observer,this);return sink.run()};return FromArrayObservable}(ObservableBase);function FromArraySink(observer,parent){this.observer=observer;this.parent=parent}FromArraySink.prototype.run=function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i0){observer.onNext(value);i>0&&i--}if(i===0){return observer.onCompleted()}recurse(i)}return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,loopRecursive)};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RepeatObservable(value,repeatCount,scheduler)};var JustObservable=function(__super__){inherits(JustObservable,__super__);function JustObservable(value,scheduler){this.value=value;this.scheduler=scheduler;__super__.call(this)}JustObservable.prototype.subscribeCore=function(observer){var sink=new JustSink(observer,this);return sink.run()};function JustSink(observer,parent){this.observer=observer;this.parent=parent}function scheduleItem(s,state){var value=state[0],observer=state[1];observer.onNext(value);observer.onCompleted()}JustSink.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],scheduleItem)};return JustObservable}(ObservableBase);var observableReturn=Observable["return"]=Observable.just=Observable.returnValue=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new JustObservable(value,scheduler)};var ThrowObservable=function(__super__){inherits(ThrowObservable,__super__);function ThrowObservable(error,scheduler){this.error=error;this.scheduler=scheduler;__super__.call(this)}ThrowObservable.prototype.subscribeCore=function(o){var sink=new ThrowSink(o,this);return sink.run()};function ThrowSink(o,p){this.o=o;this.p=p}function scheduleItem(s,state){var e=state[0],o=state[1];o.onError(e)}ThrowSink.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],scheduleItem)};return ThrowObservable}(ObservableBase);var observableThrow=Observable["throw"]=Observable.throwError=Observable.throwException=function(error,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new ThrowObservable(error,scheduler)};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(observer){var disposable=disposableEmpty,resource,source;try{resource=resourceFactory();resource&&(disposable=resource);source=observableFactory(resource)}catch(exception){return new CompositeDisposable(observableThrow(exception).subscribe(observer),disposable)}return new CompositeDisposable(source.subscribe(observer),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}leftSubscription.setDisposable(leftSource.subscribe(function(left){choiceL();choice===leftChoice&&observer.onNext(left)},function(err){choiceL();choice===leftChoice&&observer.onError(err)},function(){choiceL();choice===leftChoice&&observer.onCompleted()}));rightSubscription.setDisposable(rightSource.subscribe(function(right){choiceR();choice===rightChoice&&observer.onNext(right)},function(err){choiceR();choice===rightChoice&&observer.onError(err)},function(){choiceR();choice===rightChoice&&observer.onCompleted()}));return new CompositeDisposable(leftSubscription,rightSubscription)})};Observable.amb=function(){var acc=observableNever(),items=[];if(Array.isArray(arguments[0])){items=arguments[0]}else{for(var i=0,len=arguments.length;i0){parent.handleSubscribe(parent.q.shift())}else{parent.activeCount--;parent.done&&parent.activeCount===0&&parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeObserver}();observableProto.merge=function(maxConcurrentOrOther){return typeof maxConcurrentOrOther!=="number"?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther)};var observableMerge=Observable.merge=function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler=immediateScheduler;for(i=1;i0})){var queuedValues=queues.map(function(x){return x.shift()}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},parent)};Observable.zip=function(){var len=arguments.length,args=new Array(len);for(var i=0;i0})){var res=queues.map(function(x){return x.shift()});o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){return o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}))})(idx)}return new CompositeDisposable(subscriptions)})};observableProto.asObservable=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(o)},source)};observableProto.bufferWithCount=function(count,skip){if(typeof skip!=="number"){skip=count}return this.windowWithCount(count,skip).selectMany(function(x){return x.toArray()}).where(function(x){return x.length>0})};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto.distinctUntilChanged=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var hasCurrentKey=false,currentKey;return source.subscribe(function(value){var key=value;if(keySelector){key=tryCatch(keySelector)(value);if(key===errorObj){return o.onError(key.e)}}if(hasCurrentKey){var comparerEquals=tryCatch(comparer)(currentKey,key);if(comparerEquals===errorObj){return o.onError(comparerEquals.e)}}if(!hasCurrentKey||!comparerEquals){hasCurrentKey=true;currentKey=key;o.onNext(value)}},function(e){o.onError(e)},function(){o.onCompleted()})},this)};var TapObservable=function(__super__){inherits(TapObservable,__super__);function TapObservable(source,observerOrOnNext,onError,onCompleted){this.source=source;this.t=!observerOrOnNext||isFunction(observerOrOnNext)?observerCreate(observerOrOnNext||noop,onError||noop,onCompleted||noop):observerOrOnNext;__super__.call(this)}TapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.t))};function InnerObserver(o,t){this.o=o;this.t=t;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var res=tryCatch(this.t.onNext).call(this.t,x);if(res===errorObj){this.o.onError(res.e)}this.o.onNext(x)};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onError).call(this.t,err);if(res===errorObj){return this.o.onError(res.e)}this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onCompleted).call(this.t);if(res===errorObj){return this.o.onError(res.e)}this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return TapObservable}(ObservableBase);observableProto["do"]=observableProto.tap=observableProto.doAction=function(observerOrOnNext,onError,onCompleted){return new TapObservable(this,observerOrOnNext,onError,onCompleted)};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=observableProto.ensure=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription;try{subscription=source.subscribe(observer)}catch(e){action();throw e}return disposableCreate(function(){try{subscription.dispose()}catch(e){throw e}finally{action()}})},this)};observableProto.finallyAction=function(action){return this.ensure(action)};var IgnoreElementsObservable=function(__super__){inherits(IgnoreElementsObservable,__super__);function IgnoreElementsObservable(source){this.source=source;__super__.call(this)}IgnoreElementsObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o))};function InnerObserver(o){this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=noop;InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};return IgnoreElementsObservable}(ObservableBase);observableProto.ignoreElements=function(){return new IgnoreElementsObservable(this)};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})},source)};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchError()};observableProto.retryWhen=function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier)};var ScanObservable=function(__super__){inherits(ScanObservable,__super__);function ScanObservable(source,accumulator,hasSeed,seed){this.source=source;this.accumulator=accumulator;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ScanObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new ScanObserver(observer,this))};return ScanObservable}(ObservableBase);function ScanObserver(observer,parent){this.observer=observer;this.accumulator=parent.accumulator;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.accumulation=null;this.hasValue=false;this.isStopped=false}ScanObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);try{if(this.hasAccumulation){this.accumulation=this.accumulator(this.accumulation,x)}else{this.accumulation=this.hasSeed?this.accumulator(this.seed,x):x;this.hasAccumulation=true}}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)};ScanObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e)}};ScanObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed);this.observer.onCompleted()}};ScanObserver.prototype.dispose=function(){this.isStopped=true};ScanObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};observableProto.scan=function(){var hasSeed=false,seed,accumulator,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new ScanObservable(this,accumulator,hasSeed,seed)};observableProto.skipLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&o.onNext(q.shift())},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}for(var args=[],i=start,len=arguments.length;icount&&q.shift()},function(e){o.onError(e)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()})},source)};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){o.onNext(q);o.onCompleted()})},source)};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new ArgumentOutOfRangeError}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};function concatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.concatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})})}return isFunction(selector)?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this,onNextFunc=bindCallback(onNext,thisArg,2),onErrorFunc=bindCallback(onError,thisArg,1),onCompletedFunc=bindCallback(onCompleted,thisArg,0);return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNextFunc(x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onErrorFunc(err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompletedFunc()}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},this).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;defaultValue===undefined&&(defaultValue=null);return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},function(e){observer.onError(e)},function(){!found&&observer.onNext(defaultValue);observer.onCompleted()})},source)};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i0){o.onNext(x);remaining<=0&&o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.takeWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running=callback(x,i++,source)}catch(e){o.onError(e);return}if(running){o.onNext(x)}else{o.onCompleted()}}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};var FilterObservable=function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source=source;this.predicate=bindCallback(predicate,thisArg,3);__super__.call(this)}FilterObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.predicate,this))};function innerPredicate(predicate,self){return function(x,i,o){return self.predicate(x,i,o)&&predicate.call(this,x,i,o)}}FilterObservable.prototype.internalFilter=function(predicate,thisArg){return new FilterObservable(this.source,innerPredicate(predicate,this),thisArg)};function InnerObserver(o,predicate,source){this.o=o;this.predicate=predicate;this.source=source;this.i=0;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var shouldYield=tryCatch(this.predicate)(x,this.i++,this.source);if(shouldYield===errorObj){return this.o.onError(shouldYield.e)}shouldYield&&this.o.onNext(x)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return FilterObservable}(ObservableBase);observableProto.filter=observableProto.where=function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg)};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(o){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){o.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){o.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},function(e){o.onError(e)},function(){o.onNext(list);o.onCompleted()})},source)}function firstOnly(x){if(x.length===0){throw new EmptyError}return x[0]}observableProto.aggregate=function(){var hasSeed=false,accumulator,seed,source=this;if(arguments.length===2){hasSeed=true;seed=arguments[0];accumulator=arguments[1]}else{accumulator=arguments[0]}return new AnonymousObservable(function(o){var hasAccumulation,accumulation,hasValue;return source.subscribe(function(x){!hasValue&&(hasValue=true);try{if(hasAccumulation){accumulation=accumulator(accumulation,x)}else{accumulation=hasSeed?accumulator(seed,x):x;hasAccumulation=true}}catch(e){return o.onError(e)}},function(e){o.onError(e)},function(){hasValue&&o.onNext(accumulation);!hasValue&&hasSeed&&o.onNext(seed);!hasValue&&!hasSeed&&o.onError(new EmptyError);o.onCompleted()})},source)};var ReduceObservable=function(__super__){inherits(ReduceObservable,__super__);function ReduceObservable(source,acc,hasSeed,seed){this.source=source;this.acc=acc;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ReduceObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new InnerObserver(observer,this))};function InnerObserver(o,parent){this.o=o;this.acc=parent.acc;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.result=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.result=tryCatch(this.acc)(this.result,x)}else{this.result=this.hasSeed?tryCatch(this.acc)(this.seed,x):x;this.hasAccumulation=true}if(this.result===errorObj){this.o.onError(this.result.e)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.hasValue&&this.o.onNext(this.result);!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);!this.hasValue&&!this.hasSeed&&this.o.onError(new EmptyError);this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return ReduceObservable}(ObservableBase);observableProto.reduce=function(accumulator){var hasSeed=false;if(arguments.length===2){hasSeed=true;var seed=arguments[1]}return new ReduceObservable(this,accumulator,hasSeed,seed)};observableProto.some=function(predicate,thisArg){var source=this;return predicate?source.filter(predicate,thisArg).some():new AnonymousObservable(function(observer){return source.subscribe(function(){observer.onNext(true);observer.onCompleted()},function(e){observer.onError(e)},function(){observer.onNext(false);observer.onCompleted()})},source)};observableProto.any=function(){return this.some.apply(this,arguments)};observableProto.isEmpty=function(){return this.any().map(not)};observableProto.every=function(predicate,thisArg){return this.filter(function(v){return!predicate(v)},thisArg).some().map(not)};observableProto.all=function(){return this.every.apply(this,arguments)};observableProto.includes=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(false);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){o.onNext(true);o.onCompleted()}},function(e){o.onError(e)},function(){o.onNext(false);o.onCompleted()})},this)};observableProto.contains=function(searchElement,fromIndex){observableProto.includes(searchElement,fromIndex)};observableProto.count=function(predicate,thisArg){return predicate?this.filter(predicate,thisArg).count():this.reduce(function(count){return count+1},0)};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(-1);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){o.onNext(i);o.onCompleted()}i++},function(e){o.onError(e)},function(){o.onNext(-1);o.onCompleted()})},source)};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.reduce(function(prev,curr){return prev+curr},0)};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.average=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).average():this.reduce(function(prev,cur){return{sum:prev.sum+cur,count:prev.count+1}},{sum:0,count:0}).map(function(s){if(s.count===0){throw new EmptyError}return s.sum/s.count})};observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){o.onError(e);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(doner){o.onNext(false);o.onCompleted()}else{ql.push(x)}},function(e){o.onError(e)},function(){donel=true;if(ql.length===0){if(qr.length>0){o.onNext(false);o.onCompleted()}else if(doner){o.onNext(true);o.onCompleted()}}});(isArrayLike(second)||isIterable(second))&&(second=observableFrom(second));isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){o.onError(exception);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(donel){o.onNext(false);o.onCompleted()}else{qr.push(x)}},function(e){o.onError(e)},function(){doner=true;if(qr.length===0){if(ql.length>0){o.onNext(false);o.onCompleted()}else if(donel){o.onNext(true);o.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)},first)};function elementAtOrDefault(source,index,hasDefault,defaultValue){if(index<0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(o){var i=index;return source.subscribe(function(x){if(i--===0){o.onNext(x);o.onCompleted()}},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new ArgumentOutOfRangeError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.elementAt=function(index){return elementAtOrDefault(this,index,false)};observableProto.elementAtOrDefault=function(index,defaultValue){return elementAtOrDefault(this,index,true,defaultValue)};function singleOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){if(seenValue){o.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.single=function(predicate,thisArg){return predicate&&isFunction(predicate)?this.where(predicate,thisArg).single():singleOrDefaultAsync(this,false)};observableProto.singleOrDefault=function(predicate,defaultValue,thisArg){return predicate&&isFunction(predicate)?this.filter(predicate,thisArg).singleOrDefault(null,defaultValue):singleOrDefaultAsync(this,true,defaultValue)};function firstOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){return source.subscribe(function(x){o.onNext(x);o.onCompleted()},function(e){o.onError(e)},function(){if(!hasDefault){o.onError(new EmptyError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)}observableProto.first=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).first():firstOrDefaultAsync(this,false)};observableProto.firstOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate).firstOrDefault(null,defaultValue):firstOrDefaultAsync(this,true,defaultValue)};function lastOrDefaultAsync(source,hasDefault,defaultValue){return new AnonymousObservable(function(o){var value=defaultValue,seenValue=false;return source.subscribe(function(x){value=x;seenValue=true},function(e){o.onError(e)},function(){if(!seenValue&&!hasDefault){o.onError(new EmptyError)}else{o.onNext(value);o.onCompleted()}})},source)}observableProto.last=function(predicate,thisArg){return predicate?this.where(predicate,thisArg).last():lastOrDefaultAsync(this,false)};observableProto.lastOrDefault=function(predicate,defaultValue,thisArg){return predicate?this.where(predicate,thisArg).lastOrDefault(null,defaultValue):lastOrDefaultAsync(this,true,defaultValue)};function findValue(source,predicate,thisArg,yieldIndex){var callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=callback(x,i,source)}catch(e){o.onError(e);return}if(shouldRun){o.onNext(yieldIndex?i:x);o.onCompleted()}else{i++}},function(e){o.onError(e)},function(){o.onNext(yieldIndex?-1:undefined);o.onCompleted()})},source)}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};observableProto.toSet=function(){if(typeof root.Set==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var s=new root.Set;return source.subscribe(function(x){s.add(x)},function(e){o.onError(e)},function(){o.onNext(s);o.onCompleted()})},source)};observableProto.toMap=function(keySelector,elementSelector){if(typeof root.Map==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){o.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){o.onError(e);return}}m.set(key,element)},function(e){o.onError(e)},function(){o.onNext(m);o.onCompleted()})},source)};var fnString="function",throwString="throw",isObject=Rx.internals.isObject;function toThunk(obj,ctx){if(Array.isArray(obj)){return objectToThunk.call(ctx,obj)}if(isGeneratorFunction(obj)){return observableSpawn(obj.call(ctx))}if(isGenerator(obj)){return observableSpawn(obj)}if(isObservable(obj)){return observableToThunk(obj)}if(isPromise(obj)){return promiseToThunk(obj)}if(typeof obj===fnString){return obj}if(isObject(obj)||Array.isArray(obj)){return objectToThunk.call(ctx,obj)}return obj}function objectToThunk(obj){var ctx=this;return function(done){var keys=Object.keys(obj),pending=keys.length,results=new obj.constructor,finished;if(!pending){timeoutScheduler.schedule(function(){done(null,results)});return}for(var i=0,len=keys.length;i2){for(var res=[],i=1,len=arguments.length;i0){o.onNext(q.shift())}}var subscription=combineLatestSource(this.source,this.pauser.distinctUntilChanged().startWith(false),function(data,shouldFire){return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){drainQueue()}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){o.onNext(results.data)}else{q.push(results.data)}}},function(err){drainQueue();o.onError(err)},function(){drainQueue();o.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};var ControlledObservable=function(__super__){inherits(ControlledObservable,__super__);function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue,scheduler){__super__.call(this,subscribe,source);this.subject=new ControlledSubject(enableQueue,scheduler);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){return this.subject.request(numberOfItems==null?-1:numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=function(__super__){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue,scheduler){enableQueue==null&&(enableQueue=true);__super__.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=disposableEmpty;this.error=null;this.hasFailed=false;this.hasCompleted=false;this.scheduler=scheduler||currentThreadScheduler}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0){this.subject.onCompleted()}else{this.queue.push(Notification.createOnCompleted())}},onError:function(error){this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0){this.subject.onError(error)}else{this.queue.push(Notification.createOnError(error))}},onNext:function(value){var hasRequested=false;if(this.requestedCount===0){this.enableQueue&&this.queue.push(Notification.createOnNext(value))}else{this.requestedCount!==-1&&this.requestedCount--===0&&this.disposeCurrentRequest();hasRequested=true}hasRequested&&this.subject.onNext(value)},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>=numberOfItems&&numberOfItems>0||this.queue.length>0&&this.queue[0].kind!=="N"){var first=this.queue.shift();first.accept(this.subject);if(first.kind==="N"){numberOfItems--}else{this.disposeCurrentRequest();this.queue=[]}}return{numberOfItems:numberOfItems,returnValue:this.queue.length!==0}}return{numberOfItems:numberOfItems,returnValue:false}},request:function(number){this.disposeCurrentRequest();var self=this;this.requestedDisposable=this.scheduler.scheduleWithState(number,function(s,i){var r=self._processRequest(i),remaining=r.numberOfItems;if(!r.returnValue){self.requestedCount=remaining;self.requestedDisposable=disposableCreate(function(){self.requestedCount=0})}});return this.requestedDisposable},disposeCurrentRequest:function(){this.requestedDisposable.dispose();this.requestedDisposable=disposableEmpty}});return ControlledSubject}(Observable);observableProto.controlled=function(enableQueue,scheduler){if(enableQueue&&isScheduler(enableQueue)){scheduler=enableQueue;enableQueue=true}if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue,scheduler)};var StopAndWaitObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new StopAndWaitObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(1)});return this.subscription}inherits(StopAndWaitObservable,__super__);function StopAndWaitObservable(source){__super__.call(this,subscribe,source);this.source=source}var StopAndWaitObserver=function(__sub__){inherits(StopAndWaitObserver,__sub__);function StopAndWaitObserver(observer,observable,cancel){__sub__.call(this);this.observer=observer;this.observable=observable;this.cancel=cancel}var stopAndWaitObserverProto=StopAndWaitObserver.prototype;stopAndWaitObserverProto.completed=function(){this.observer.onCompleted();this.dispose()};stopAndWaitObserverProto.error=function(error){this.observer.onError(error);this.dispose()};stopAndWaitObserverProto.next=function(value){this.observer.onNext(value);var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(1); -})};stopAndWaitObserverProto.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return StopAndWaitObserver}(AbstractObserver);return StopAndWaitObservable}(Observable);ControlledObservable.prototype.stopAndWait=function(){return new StopAndWaitObservable(this)};var WindowedObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new WindowedObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(self.windowSize)});return this.subscription}inherits(WindowedObservable,__super__);function WindowedObservable(source,windowSize){__super__.call(this,subscribe,source);this.source=source;this.windowSize=windowSize}var WindowedObserver=function(__sub__){inherits(WindowedObserver,__sub__);function WindowedObserver(observer,observable,cancel){this.observer=observer;this.observable=observable;this.cancel=cancel;this.received=0}var windowedObserverPrototype=WindowedObserver.prototype;windowedObserverPrototype.completed=function(){this.observer.onCompleted();this.dispose()};windowedObserverPrototype.error=function(error){this.observer.onError(error);this.dispose()};windowedObserverPrototype.next=function(value){this.observer.onNext(value);this.received=++this.received%this.observable.windowSize;if(this.received===0){var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(self.observable.windowSize)})}};windowedObserverPrototype.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return WindowedObserver}(AbstractObserver);return WindowedObservable}(Observable);ControlledObservable.prototype.windowed=function(windowSize){return new WindowedObservable(this,windowSize)};observableProto.pipe=function(dest){var source=this.pausableBuffered();function onDrain(){source.resume()}dest.addListener("drain",onDrain);source.subscribe(function(x){!dest.write(String(x))&&source.pause()},function(err){dest.emit("error",err)},function(){!dest._isStdio&&dest.end();dest.removeListener("drain",onDrain)});source.resume();return dest};observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())},source):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,windowSize,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler))};observableProto.shareReplay=function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.hasError=false}addProperties(BehaviorSubject.prototype,Observer,{getValue:function(){checkDisposed(this);if(this.hasError){throw this.error}return this.value},hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i=min){return num}}candidate=min|1;while(candidate>>16;key=key+(key<<3);key=key^key>>>4;key=key*c2;key=key^key>>>15;return key}var getHashCode=function(){var uniqueIdCounter=0;return function(obj){if(obj==null){throw new Error(noSuchkey)}if(typeof obj==="string"){return stringHashFn(obj)}if(typeof obj==="number"){return numberHashFn(obj)}if(typeof obj==="boolean"){return obj===true?1:0}if(obj instanceof Date){return numberHashFn(obj.valueOf())}if(obj instanceof RegExp){return stringHashFn(obj.toString())}if(typeof obj.valueOf==="function"){var valueOf=obj.valueOf();if(typeof valueOf==="number"){return numberHashFn(valueOf)}if(typeof valueOf==="string"){return stringHashFn(valueOf)}}if(obj.hashCode){return obj.hashCode()}var id=17*uniqueIdCounter++;obj.hashCode=function(){return id};return id}}();function newEntry(){return{key:null,value:null,next:0,hashCode:0}}function Dictionary(capacity,comparer){if(capacity<0){throw new ArgumentOutOfRangeError}if(capacity>0){this._initialize(capacity)}this.comparer=comparer||defaultComparer;this.freeCount=0;this.size=0;this.freeList=-1}var dictionaryProto=Dictionary.prototype;dictionaryProto._initialize=function(capacity){var prime=getPrime(capacity),i;this.buckets=new Array(prime);this.entries=new Array(prime);for(i=0;i=0;index2=this.entries[index2].next){if(this.entries[index2].hashCode===num&&this.comparer(this.entries[index2].key,key)){if(add){throw new Error(duplicatekey)}this.entries[index2].value=value;return}}if(this.freeCount>0){index3=this.freeList;this.freeList=this.entries[index3].next;--this.freeCount}else{if(this.size===this.entries.length){this._resize();index1=num%this.buckets.length}index3=this.size;++this.size}this.entries[index3].hashCode=num;this.entries[index3].next=this.buckets[index1];this.entries[index3].key=key;this.entries[index3].value=value;this.buckets[index1]=index3};dictionaryProto._resize=function(){var prime=getPrime(this.size*2),numArray=new Array(prime);for(index=0;index=0;index3=this.entries[index3].next){if(this.entries[index3].hashCode===num&&this.comparer(this.entries[index3].key,key)){if(index2<0){this.buckets[index1]=this.entries[index3].next}else{this.entries[index2].next=this.entries[index3].next}this.entries[index3].hashCode=-1;this.entries[index3].next=this.freeList;this.entries[index3].key=null;this.entries[index3].value=null;this.freeList=index3;++this.freeCount;return true}else{index2=index3}}}return false};dictionaryProto.clear=function(){var index,len;if(this.size<=0){return}for(index=0,len=this.buckets.length;index=0;index=this.entries[index].next){if(this.entries[index].hashCode===num&&this.comparer(this.entries[index].key,key)){return index}}}return-1};dictionaryProto.count=function(){return this.size-this.freeCount};dictionaryProto.tryGetValue=function(key){var entry=this._findEntry(key);return entry>=0?this.entries[entry].value:undefined};dictionaryProto.getValues=function(){var index=0,results=[];if(this.entries){for(var index1=0;index1=0){results[index++]=this.entries[index1].value}}}return results};dictionaryProto.get=function(key){var entry=this._findEntry(key);if(entry>=0){return this.entries[entry].value}throw new Error(noSuchkey)};dictionaryProto.set=function(key,value){this._insert(key,value,false)};dictionaryProto.containskey=function(key){return this._findEntry(key)>=0};return Dictionary}();observableProto.join=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var leftDone=false,rightDone=false;var leftId=0,rightId=0;var leftMap=new Dictionary,rightMap=new Dictionary;group.add(left.subscribe(function(value){var id=leftId++;var md=new SingleAssignmentDisposable;leftMap.add(id,value);group.add(md);var expire=function(){leftMap.remove(id)&&leftMap.count()===0&&leftDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));rightMap.getValues().forEach(function(v){var result;try{result=resultSelector(value,v)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){leftDone=true;(rightDone||leftMap.count()===0)&&observer.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++;var md=new SingleAssignmentDisposable;rightMap.add(id,value);group.add(md);var expire=function(){rightMap.remove(id)&&rightMap.count()===0&&rightDone&&observer.onCompleted();group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,observer.onError.bind(observer),expire));leftMap.getValues().forEach(function(v){var result;try{result=resultSelector(v,value)}catch(exn){observer.onError(exn);return}observer.onNext(result)})},observer.onError.bind(observer),function(){rightDone=true;(leftDone||rightMap.count()===0)&&observer.onCompleted()}));return group},left)};observableProto.groupJoin=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(observer){var group=new CompositeDisposable;var r=new RefCountDisposable(group);var leftMap=new Dictionary,rightMap=new Dictionary;var leftId=0,rightId=0;function handleError(e){return function(v){v.onError(e)}}group.add(left.subscribe(function(value){var s=new Subject;var id=leftId++;leftMap.add(id,s);var result;try{result=resultSelector(value,addRef(s,r))}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}observer.onNext(result);rightMap.getValues().forEach(function(v){s.onNext(v)});var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){leftMap.remove(id)&&s.onCompleted();group.remove(md)};var duration;try{duration=leftDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire))},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},observer.onCompleted.bind(observer)));group.add(right.subscribe(function(value){var id=rightId++;rightMap.add(id,value);var md=new SingleAssignmentDisposable;group.add(md);var expire=function(){rightMap.remove(id);group.remove(md)};var duration;try{duration=rightDurationSelector(value)}catch(e){leftMap.getValues().forEach(handleError(e));observer.onError(e);return}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)},expire));leftMap.getValues().forEach(function(v){v.onNext(value)})},function(e){leftMap.getValues().forEach(handleError(e));observer.onError(e)}));return r},left)};observableProto.buffer=function(bufferOpeningsOrClosingSelector,bufferClosingSelector){return this.window.apply(this,arguments).selectMany(function(x){return x.toArray()})};observableProto.window=function(windowOpeningsOrClosingSelector,windowClosingSelector){if(arguments.length===1&&typeof arguments[0]!=="function"){return observableWindowWithBoundaries.call(this,windowOpeningsOrClosingSelector)}return typeof windowOpeningsOrClosingSelector==="function"?observableWindowWithClosingSelector.call(this,windowOpeningsOrClosingSelector):observableWindowWithOpenings.call(this,windowOpeningsOrClosingSelector,windowClosingSelector)};function observableWindowWithOpenings(windowOpenings,windowClosingSelector){return windowOpenings.groupJoin(this,windowClosingSelector,observableEmpty,function(_,win){return win})}function observableWindowWithBoundaries(windowBoundaries){var source=this;return new AnonymousObservable(function(observer){var win=new Subject,d=new CompositeDisposable,r=new RefCountDisposable(d);observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));isPromise(windowBoundaries)&&(windowBoundaries=observableFromPromise(windowBoundaries));d.add(windowBoundaries.subscribe(function(w){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r))},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));return r},source)}function observableWindowWithClosingSelector(windowClosingSelector){var source=this;return new AnonymousObservable(function(observer){var m=new SerialDisposable,d=new CompositeDisposable(m),r=new RefCountDisposable(d),win=new Subject;observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));function createWindowClose(){var windowClose;try{windowClose=windowClosingSelector()}catch(e){observer.onError(e);return}isPromise(windowClose)&&(windowClose=observableFromPromise(windowClose));var m1=new SingleAssignmentDisposable;m.setDisposable(m1);m1.setDisposable(windowClose.take(1).subscribe(noop,function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r));createWindowClose()}))}createWindowClose();return r},source)}observableProto.pairwise=function(){var source=this;return new AnonymousObservable(function(observer){var previous,hasPrevious=false;return source.subscribe(function(x){if(hasPrevious){observer.onNext([previous,x])}else{hasPrevious=true}previous=x},observer.onError.bind(observer),observer.onCompleted.bind(observer))},source)};observableProto.partition=function(predicate,thisArg){return[this.filter(predicate,thisArg),this.filter(function(x,i,o){return!predicate.call(thisArg,x,i,o)})]};var WhileEnumerable=function(__super__){inherits(WhileEnumerable,__super__);function WhileEnumerable(c,s){this.c=c;this.s=s}WhileEnumerable.prototype[$iterator$]=function(){var self=this;return{next:function(){return self.c()?{done:false,value:self.s}:{done:true,value:void 0}}}};return WhileEnumerable}(Enumerable);function enumerableWhile(condition,source){return new WhileEnumerable(condition,source)}observableProto.letBind=observableProto["let"]=function(func){return func(this)};Observable["if"]=Observable.ifThen=function(condition,thenSource,elseSourceOrScheduler){return observableDefer(function(){elseSourceOrScheduler||(elseSourceOrScheduler=observableEmpty());isPromise(thenSource)&&(thenSource=observableFromPromise(thenSource));isPromise(elseSourceOrScheduler)&&(elseSourceOrScheduler=observableFromPromise(elseSourceOrScheduler));typeof elseSourceOrScheduler.now==="function"&&(elseSourceOrScheduler=observableEmpty(elseSourceOrScheduler));return condition()?thenSource:elseSourceOrScheduler})};Observable["for"]=Observable.forIn=function(sources,resultSelector,thisArg){return enumerableOf(sources,resultSelector,thisArg).concat()};var observableWhileDo=Observable["while"]=Observable.whileDo=function(condition,source){isPromise(source)&&(source=observableFromPromise(source));return enumerableWhile(condition,source).concat()};observableProto.doWhile=function(condition){return observableConcat([this,observableWhileDo(condition,this)])};Observable["case"]=Observable.switchCase=function(selector,sources,defaultSourceOrScheduler){return observableDefer(function(){isPromise(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableFromPromise(defaultSourceOrScheduler));defaultSourceOrScheduler||(defaultSourceOrScheduler=observableEmpty());typeof defaultSourceOrScheduler.now==="function"&&(defaultSourceOrScheduler=observableEmpty(defaultSourceOrScheduler));var result=sources[selector()];isPromise(result)&&(result=observableFromPromise(result));return result||defaultSourceOrScheduler})};observableProto.expand=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[],m=new SerialDisposable,d=new CompositeDisposable(m),activeCount=0,isAcquired=false;var ensureActive=function(){var isOwner=false;if(q.length>0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d},this)};Observable.forkJoin=function(){var allSources=[];if(Array.isArray(arguments[0])){allSources=arguments[0]}else{for(var i=0,len=arguments.length;i0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count);self(count+1,d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!==undefined&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){period=periodOrScheduler;return observableTimerDateAndPeriod(dueTime.getTime(),period,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)},source)}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.debounce=observableProto.throttleWithTimeout=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)},this)};observableProto.throttle=function(dueTime,scheduler){return this.debounce(dueTime,scheduler)};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}o.onCompleted()})},source)};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){o.onNext(next.value)}}o.onCompleted()})},source)};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();now-next.interval<=duration&&res.push(next.value)}o.onNext(res);o.onCompleted()})},source)};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))},source)};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()}))},source)};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler[schedulerMethod](endTime,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.throttleFirst=function(windowDuration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var duration=+windowDuration||0;if(duration<=0){throw new RangeError("windowDuration cannot be less or equal zero.")}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext===0||now-lastOnNext>=duration){lastOnNext=now;o.onNext(x)}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.transduce=function(transducer){var source=this;function transformForObserver(o){return{"@@transducer/init":function(){return o},"@@transducer/step":function(obs,input){return obs.onNext(input)},"@@transducer/result":function(obs){return obs.onCompleted()}}}return new AnonymousObservable(function(o){var xform=transducer(transformForObserver(o));return source.subscribe(function(v){try{xform["@@transducer/step"](o,v)}catch(e){o.onError(e)}},function(e){o.onError(e)},function(){xform["@@transducer/result"](o)})},source)};observableProto.exclusive=function(){var sources=this;return new AnonymousObservable(function(observer){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer),observer.onError.bind(observer),function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},observer.onError.bind(observer),function(){isStopped=true;if(!hasCurrent&&g.length===1){observer.onCompleted()}}));return g},this)};observableProto.exclusiveMap=function(selector,thisArg){var sources=this,selectorFunc=bindCallback(selector,thisArg,3);return new AnonymousObservable(function(observer){var index=0,hasCurrent=false,isStopped=true,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){var result;try{result=selectorFunc(x,index++,innerSource)}catch(e){observer.onError(e);return}observer.onNext(result)},function(e){observer.onError(e)},function(){g.remove(innerSubscription);hasCurrent=false;if(isStopped&&g.length===1){observer.onCompleted()}}))}},function(e){observer.onError(e)},function(){isStopped=true;if(g.length===1&&!hasCurrent){observer.onCompleted()}}));return g},this)};Rx.VirtualTimeScheduler=function(__super__){function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new ArgumentOutOfRangeError}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],subscribe=state[1];var sub=tryCatch(subscribe)(ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function AnonymousObservable(subscribe,parent){this.source=parent;function s(observer){var ado=new AutoDetachObserver(observer),state=[ado,subscribe];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}__super__.call(this,s)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result===errorObj){this.dispose();thrower(result.e)}};AutoDetachObserverPrototype.error=function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.completed=function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(){return this.m.getDisposable()};AutoDetachObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,__super__);function Subject(){__super__.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[];this.hasError=false}addProperties(Subject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(!this.isStopped){this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i0},onCompleted:function(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped=true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i=0;i=0;i--){vtree.children[i]=replaceCustomElementsWithSomething(vtree.children[i],registry,toSomethingFn)}}return vtree}function makeCustomElementsRegistry(definitions){var registry=new Map;for(var tagName in definitions){if(definitions.hasOwnProperty(tagName)){registry.set(tagName.toUpperCase(),makeWidgetClass(tagName,definitions[tagName]))}}return registry}module.exports={replaceCustomElementsWithSomething:replaceCustomElementsWithSomething,makeCustomElementsRegistry:makeCustomElementsRegistry}},{"./custom-element-widget":4,"es6-map":9}],6:[function(require,module,exports){"use strict";var VirtualDOM=require("virtual-dom");var svg=require("virtual-dom/virtual-hyperscript/svg");var _require=require("./render-dom");var makeDOMDriver=_require.makeDOMDriver;var _require2=require("./render-html");var makeHTMLDriver=_require2.makeHTMLDriver;var CycleDOM={makeDOMDriver:makeDOMDriver,makeHTMLDriver:makeHTMLDriver,h:VirtualDOM.h,hJSX:function hJSX(tag,attrs){for(var _len=arguments.length,children=Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){children[_key-2]=arguments[_key]}return VirtualDOM.h(tag,attrs,children)},svg:svg};module.exports=CycleDOM},{"./render-dom":7,"./render-html":8,"virtual-dom":82,"virtual-dom/virtual-hyperscript/svg":103}],7:[function(require,module,exports){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break}}catch(err){_d=true;_e=err}finally{try{if(!_n&&_i["return"])_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr)){return arr}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i)}else{throw new TypeError("Invalid attempt to destructure non-iterable instance")}}}();var _require=require("@cycle/core");var Rx=_require.Rx;var VDOM={h:require("virtual-dom").h,diff:require("virtual-dom/diff"),patch:require("virtual-dom/patch"),parse:typeof window!=="undefined"?require("vdom-parser"):function(){}};var _require2=require("./custom-elements");var replaceCustomElementsWithSomething=_require2.replaceCustomElementsWithSomething;var makeCustomElementsRegistry=_require2.makeCustomElementsRegistry;function isElement(obj){return typeof HTMLElement==="object"?obj instanceof HTMLElement||obj instanceof DocumentFragment:obj&&typeof obj==="object"&&obj!==null&&(obj.nodeType===1||obj.nodeType===11)&&typeof obj.nodeName==="string"}function fixRootElem$(rawRootElem$,domContainer){var originalClasses=(domContainer.className||"").trim().split(/\s+/);var originalId=domContainer.id;return rawRootElem$.map(function fixRootElemClassNameAndId(rootElem){var previousClasses=rootElem.className.trim().split(/\s+/);var missingClasses=originalClasses.filter(function(clss){return previousClasses.indexOf(clss)<0});rootElem.className=previousClasses.concat(missingClasses).join(" ");rootElem.id=originalId;return rootElem}).replay(null,1)}function isVTreeCustomElement(vtree){return vtree.type==="Widget"&&vtree.isCustomElementWidget}function makeReplaceCustomElementsWithWidgets(CERegistry,driverName){return function replaceCustomElementsWithWidgets(vtree){return replaceCustomElementsWithSomething(vtree,CERegistry,function(_vtree,WidgetClass){return new WidgetClass(_vtree,CERegistry,driverName)})}}function getArrayOfAllWidgetFirstRootElem$(vtree){if(vtree.type==="Widget"&&vtree.firstRootElem$){return[vtree.firstRootElem$]}var array=[];if(Array.isArray(vtree.children)){for(var i=vtree.children.length-1;i>=0;i--){array=array.concat(getArrayOfAllWidgetFirstRootElem$(vtree.children[i]))}}return array}function checkRootVTreeNotCustomElement(vtree){if(isVTreeCustomElement(vtree)){throw new Error("Illegal to use a Cycle custom element as the root of "+"a View.")}}function isRootForCustomElement(rootElem){return!!rootElem.cycleCustomElementMetadata}function wrapTopLevelVTree(vtree,rootElem){if(isRootForCustomElement(rootElem)){return vtree}var _vtree$properties$id=vtree.properties.id;var vtreeId=_vtree$properties$id===undefined?"":_vtree$properties$id;var _vtree$properties$className=vtree.properties.className;var vtreeClass=_vtree$properties$className===undefined?"":_vtree$properties$className;var sameId=vtreeId===rootElem.id;var sameClass=vtreeClass===rootElem.className;var sameTagName=vtree.tagName.toUpperCase()===rootElem.tagName;if(sameId&&sameClass&&sameTagName){return vtree}else{return VDOM.h(rootElem.tagName,{id:rootElem.id,className:rootElem.className},[vtree])}}function makeDiffAndPatchToElement$(rootElem){return function diffAndPatchToElement$(_ref){var _ref2=_slicedToArray(_ref,2);var oldVTree=_ref2[0];var newVTree=_ref2[1];if(typeof newVTree==="undefined"){return Rx.Observable.empty()}var prevVTree=wrapTopLevelVTree(oldVTree,rootElem);var nextVTree=wrapTopLevelVTree(newVTree,rootElem);var waitForChildrenStreams=getArrayOfAllWidgetFirstRootElem$(nextVTree);var rootElemAfterChildrenFirstRootElem$=Rx.Observable.combineLatest(waitForChildrenStreams,function(){return rootElem});var cycleCustomElementMetadata=rootElem.cycleCustomElementMetadata;rootElem=VDOM.patch(rootElem,VDOM.diff(prevVTree,nextVTree));if(cycleCustomElementMetadata){rootElem.cycleCustomElementMetadata=cycleCustomElementMetadata}if(waitForChildrenStreams.length===0){return Rx.Observable.just(rootElem)}else{return rootElemAfterChildrenFirstRootElem$}}}function renderRawRootElem$(vtree$,domContainer,CERegistry,driverName){var diffAndPatchToElement$=makeDiffAndPatchToElement$(domContainer);return vtree$.startWith(VDOM.parse(domContainer)).map(makeReplaceCustomElementsWithWidgets(CERegistry,driverName)).doOnNext(checkRootVTreeNotCustomElement).pairwise().flatMap(diffAndPatchToElement$)}function makeRootElemToEvent$(selector,eventName){return function rootElemToEvent$(rootElem){if(!rootElem){return Rx.Observable.empty()}var klass=selector.replace(".","");if(rootElem.className.search(new RegExp("\\b"+klass+"\\b"))>=0){return Rx.Observable.fromEvent(rootElem,eventName)}var targetElements=rootElem.querySelectorAll(selector);if(targetElements&&targetElements.length>0){return Rx.Observable.fromEvent(targetElements,eventName)}else{return Rx.Observable.empty()}}}function makeResponseGetter(rootElem$){return function get(selector,eventName){if(typeof selector!=="string"){throw new Error("DOM driver's get() expects first argument to be a "+"string as a CSS selector")}if(selector.trim()===":root"){return rootElem$}if(typeof eventName!=="string"){throw new Error("DOM driver's get() expects second argument to be a "+"string representing the event type to listen for.")}return rootElem$.flatMapLatest(makeRootElemToEvent$(selector,eventName)).share()}}function validateDOMDriverInput(vtree$){if(!vtree$||typeof vtree$.subscribe!=="function"){throw new Error("The DOM driver function expects as input an "+"Observable of virtual DOM elements")}}function makeDOMDriverWithRegistry(container,CERegistry){return function domDriver(vtree$,driverName){validateDOMDriverInput(vtree$);var rawRootElem$=renderRawRootElem$(vtree$,container,CERegistry,driverName);if(!isRootForCustomElement(container)){rawRootElem$=rawRootElem$.startWith(container)}var rootElem$=fixRootElem$(rawRootElem$,container);var disposable=rootElem$.connect();return{get:makeResponseGetter(rootElem$),dispose:disposable.dispose.bind(disposable)}}}function makeDOMDriver(container){var customElementDefinitions=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];var domContainer=typeof container==="string"?document.querySelector(container):container;if(typeof container==="string"&&domContainer===null){throw new Error("Cannot render into unknown element '"+container+"'")}else if(!isElement(domContainer)){throw new Error("Given container is not a DOM element neither a selector "+"string.")}var registry=makeCustomElementsRegistry(customElementDefinitions);return makeDOMDriverWithRegistry(domContainer,registry)}module.exports={isElement:isElement,fixRootElem$:fixRootElem$,isVTreeCustomElement:isVTreeCustomElement,makeReplaceCustomElementsWithWidgets:makeReplaceCustomElementsWithWidgets,getArrayOfAllWidgetFirstRootElem$:getArrayOfAllWidgetFirstRootElem$,isRootForCustomElement:isRootForCustomElement,wrapTopLevelVTree:wrapTopLevelVTree,checkRootVTreeNotCustomElement:checkRootVTreeNotCustomElement,makeDiffAndPatchToElement$:makeDiffAndPatchToElement$,renderRawRootElem$:renderRawRootElem$,makeResponseGetter:makeResponseGetter,validateDOMDriverInput:validateDOMDriverInput,makeDOMDriverWithRegistry:makeDOMDriverWithRegistry,makeDOMDriver:makeDOMDriver}},{"./custom-elements":5,"@cycle/core":1,"vdom-parser":64,"virtual-dom":82,"virtual-dom/diff":80,"virtual-dom/patch":90}],8:[function(require,module,exports){"use strict";var _require=require("@cycle/core");var Rx=_require.Rx;var toHTML=require("vdom-to-html");var _require2=require("./custom-elements");var replaceCustomElementsWithSomething=_require2.replaceCustomElementsWithSomething;var makeCustomElementsRegistry=_require2.makeCustomElementsRegistry;var _require3=require("./custom-element-widget");var makeCustomElementInput=_require3.makeCustomElementInput;var ALL_PROPS=_require3.ALL_PROPS;function makePropertiesDriverFromVTree(vtree){return{get:function get(propertyName){if(propertyName===ALL_PROPS){return Rx.Observable.just(vtree.properties)}else{return Rx.Observable.just(vtree.properties[propertyName])}}}}function transposeVTree(vtree){if(typeof vtree.subscribe==="function"){return vtree}else if(vtree.type==="VirtualText"){return Rx.Observable.just(vtree)}else if(vtree.type==="VirtualNode"&&Array.isArray(vtree.children)&&vtree.children.length>0){return Rx.Observable.combineLatest(vtree.children.map(transposeVTree),function(){for(var _len=arguments.length,arr=Array(_len),_key=0;_key<_len;_key++){arr[_key]=arguments[_key]}vtree.children=arr;return vtree})}else if(vtree.type==="VirtualNode"){return Rx.Observable.just(vtree)}else{throw new Error("Unhandled case in transposeVTree()")}}function makeReplaceCustomElementsWithVTree$(CERegistry,driverName){return function replaceCustomElementsWithVTree$(vtree){return replaceCustomElementsWithSomething(vtree,CERegistry,function toVTree$(_vtree,WidgetClass){var interactions={get:function get(){return Rx.Observable.empty()}};var props=makePropertiesDriverFromVTree(_vtree);var input=makeCustomElementInput(interactions,props);var output=WidgetClass.definitionFn(input);var vtree$=output[driverName].last();return convertCustomElementsToVTree(vtree$,CERegistry,driverName)})}}function convertCustomElementsToVTree(vtree$,CERegistry,driverName){return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry,driverName)).flatMap(transposeVTree)}function makeResponseGetter(){return function get(selector){if(selector===":root"){return this}else{return Rx.Observable.empty()}}}function makeHTMLDriver(){var customElementDefinitions=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];var registry=makeCustomElementsRegistry(customElementDefinitions);return function htmlDriver(vtree$,driverName){var vtreeLast$=vtree$.last();var output$=convertCustomElementsToVTree(vtreeLast$,registry,driverName).map(function(vtree){return toHTML(vtree)});output$.get=makeResponseGetter();return output$}}module.exports={makePropertiesDriverFromVTree:makePropertiesDriverFromVTree,makeReplaceCustomElementsWithVTree$:makeReplaceCustomElementsWithVTree$,convertCustomElementsToVTree:convertCustomElementsToVTree,makeHTMLDriver:makeHTMLDriver}},{"./custom-element-widget":4,"./custom-elements":5,"@cycle/core":1,"vdom-to-html":68}],9:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Map:require("./polyfill")},{"./is-implemented":10,"./polyfill":63}],10:[function(require,module,exports){"use strict";module.exports=function(){var map,iterator,result;if(typeof Map!=="function")return false;try{map=new Map([["raz","one"],["dwa","two"],["trzy","three"]])}catch(e){return false}if(map.size!==3)return false;if(typeof map.clear!=="function")return false;if(typeof map.delete!=="function")return false;if(typeof map.entries!=="function")return false;if(typeof map.forEach!=="function")return false;if(typeof map.get!=="function")return false;if(typeof map.has!=="function")return false;if(typeof map.keys!=="function")return false;if(typeof map.set!=="function")return false;if(typeof map.values!=="function")return false;iterator=map.entries();result=iterator.next();if(result.done!==false)return false;if(!result.value)return false;if(result.value[0]!=="raz")return false;if(result.value[1]!=="one")return false;return true}},{}],11:[function(require,module,exports){"use strict";module.exports=function(){if(typeof Map==="undefined")return false;return Object.prototype.toString.call(Map.prototype)==="[object Map]"}()},{}],12:[function(require,module,exports){"use strict";module.exports=require("es5-ext/object/primitive-set")("key","value","key+value")},{"es5-ext/object/primitive-set":37}],13:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Iterator=require("es6-iterator"),toStringTagSymbol=require("es6-symbol").toStringTag,kinds=require("./iterator-kinds"),defineProperties=Object.defineProperties,unBind=Iterator.prototype._unBind,MapIterator;MapIterator=module.exports=function(map,kind){if(!(this instanceof MapIterator))return new MapIterator(map,kind);Iterator.call(this,map.__mapKeysData__,map);if(!kind||!kinds[kind])kind="key+value";defineProperties(this,{__kind__:d("",kind),__values__:d("w",map.__mapValuesData__)})};if(setPrototypeOf)setPrototypeOf(MapIterator,Iterator);MapIterator.prototype=Object.create(Iterator.prototype,{constructor:d(MapIterator),_resolve:d(function(i){if(this.__kind__==="value")return this.__values__[i];if(this.__kind__==="key")return this.__list__[i];return[this.__list__[i],this.__values__[i]]}),_unBind:d(function(){this.__values__=null;unBind.call(this)}),toString:d(function(){return"[object Map Iterator]"})});Object.defineProperty(MapIterator.prototype,toStringTagSymbol,d("c","Map Iterator"))},{"./iterator-kinds":12,d:15,"es5-ext/object/set-prototype-of":38,"es6-iterator":50,"es6-symbol":59}],14:[function(require,module,exports){"use strict";var copy=require("es5-ext/object/copy"),map=require("es5-ext/object/map"),callable=require("es5-ext/object/valid-callable"),validValue=require("es5-ext/object/valid-value"),bind=Function.prototype.bind,defineProperty=Object.defineProperty,hasOwnProperty=Object.prototype.hasOwnProperty,define;define=function(name,desc,bindTo){var value=validValue(desc)&&callable(desc.value),dgs;dgs=copy(desc);delete dgs.writable;delete dgs.value;dgs.get=function(){if(hasOwnProperty.call(this,name))return value;desc.value=bind.call(value,bindTo==null?this:this[bindTo]);defineProperty(this,name,desc);return this[name]};return dgs};module.exports=function(props){var bindTo=arguments[1];return map(props,function(desc,name){return define(name,desc,bindTo)})}},{"es5-ext/object/copy":27,"es5-ext/object/map":35,"es5-ext/object/valid-callable":41,"es5-ext/object/valid-value":42}],15:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":24,"es5-ext/object/is-callable":30,"es5-ext/object/normalize-options":36,"es5-ext/string/#/contains":43}],16:[function(require,module,exports){"use strict";var value=require("../../object/valid-value");module.exports=function(){value(this).length=0;return this}},{"../../object/valid-value":42}],17:[function(require,module,exports){"use strict";var toPosInt=require("../../number/to-pos-integer"),value=require("../../object/valid-value"),indexOf=Array.prototype.indexOf,hasOwnProperty=Object.prototype.hasOwnProperty,abs=Math.abs,floor=Math.floor;module.exports=function(searchElement){var i,l,fromIndex,val;if(searchElement===searchElement){return indexOf.apply(this,arguments)}l=toPosInt(value(this).length);fromIndex=arguments[1];if(isNaN(fromIndex))fromIndex=0;else if(fromIndex>=0)fromIndex=floor(fromIndex);else fromIndex=toPosInt(this.length)-floor(abs(fromIndex));for(i=fromIndex;i0?1:-1}},{}],21:[function(require,module,exports){"use strict";var sign=require("../math/sign"),abs=Math.abs,floor=Math.floor;module.exports=function(value){if(isNaN(value))return 0;value=Number(value);if(value===0||!isFinite(value))return value;return sign(value)*floor(abs(value))}},{"../math/sign":18}],22:[function(require,module,exports){"use strict";var toInteger=require("./to-integer"),max=Math.max;module.exports=function(value){return max(0,toInteger(value))}},{"./to-integer":21}],23:[function(require,module,exports){"use strict";var isCallable=require("./is-callable"),callable=require("./valid-callable"),value=require("./valid-value"),call=Function.prototype.call,keys=Object.keys,propertyIsEnumerable=Object.prototype.propertyIsEnumerable;module.exports=function(method,defVal){return function(obj,cb){var list,thisArg=arguments[2],compareFn=arguments[3];obj=Object(value(obj));callable(cb);list=keys(obj);if(compareFn){list.sort(isCallable(compareFn)?compareFn.bind(obj):undefined)}return list[method](function(key,index){if(!propertyIsEnumerable.call(obj,key))return defVal;return call.call(cb,thisArg,obj[key],key,obj,index)})}}},{"./is-callable":30,"./valid-callable":41,"./valid-value":42}],24:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":25,"./shim":26}],25:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],26:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i-1}},{}],46:[function(require,module,exports){"use strict";var toString=Object.prototype.toString,id=toString.call("");module.exports=function(x){return typeof x==="string"||x&&typeof x==="object"&&(x instanceof String||toString.call(x)===id)||false}},{}],47:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),contains=require("es5-ext/string/#/contains"),d=require("d"),Iterator=require("./"),defineProperty=Object.defineProperty,ArrayIterator;ArrayIterator=module.exports=function(arr,kind){if(!(this instanceof ArrayIterator))return new ArrayIterator(arr,kind);Iterator.call(this,arr);if(!kind)kind="value";else if(contains.call(kind,"key+value"))kind="key+value";else if(contains.call(kind,"key"))kind="key";else kind="value";defineProperty(this,"__kind__",d("",kind))};if(setPrototypeOf)setPrototypeOf(ArrayIterator,Iterator);ArrayIterator.prototype=Object.create(Iterator.prototype,{constructor:d(ArrayIterator),_resolve:d(function(i){if(this.__kind__==="value")return this.__list__[i];if(this.__kind__==="key+value")return[i,this.__list__[i]];return i}),toString:d(function(){return"[object Array Iterator]"})})},{"./":50,d:15,"es5-ext/object/set-prototype-of":38,"es5-ext/string/#/contains":43}],48:[function(require,module,exports){"use strict";var callable=require("es5-ext/object/valid-callable"),isString=require("es5-ext/string/is-string"),get=require("./get"),isArray=Array.isArray,call=Function.prototype.call;module.exports=function(iterable,cb){var mode,thisArg=arguments[2],result,doBreak,broken,i,l,char,code;if(isArray(iterable))mode="array";else if(isString(iterable))mode="string";else iterable=get(iterable);callable(cb);doBreak=function(){broken=true};if(mode==="array"){iterable.some(function(value){call.call(cb,thisArg,value,doBreak);if(broken)return true});return}if(mode==="string"){l=iterable.length;for(i=0;i=55296&&code<=56319)char+=iterable[++i]}call.call(cb,thisArg,char,doBreak);if(broken)break}return}result=iterable.next();while(!result.done){call.call(cb,thisArg,result.value,doBreak);if(broken)return;result=iterable.next()}}},{"./get":49,"es5-ext/object/valid-callable":41,"es5-ext/string/is-string":46}],49:[function(require,module,exports){"use strict";var isString=require("es5-ext/string/is-string"),ArrayIterator=require("./array"),StringIterator=require("./string"),iterable=require("./valid-iterable"),iteratorSymbol=require("es6-symbol").iterator;module.exports=function(obj){if(typeof iterable(obj)[iteratorSymbol]==="function")return obj[iteratorSymbol]();if(isString(obj))return new StringIterator(obj);return new ArrayIterator(obj)}},{"./array":47,"./string":57,"./valid-iterable":58,"es5-ext/string/is-string":46,"es6-symbol":52}],50:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),assign=require("es5-ext/object/assign"),callable=require("es5-ext/object/valid-callable"),value=require("es5-ext/object/valid-value"),d=require("d"),autoBind=require("d/auto-bind"),Symbol=require("es6-symbol"),defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,Iterator;module.exports=Iterator=function(list,context){if(!(this instanceof Iterator))return new Iterator(list,context);defineProperties(this,{__list__:d("w",value(list)),__context__:d("w",context),__nextIndex__:d("w",0)});if(!context)return;callable(context.on);context.on("_add",this._onAdd);context.on("_delete",this._onDelete);context.on("_clear",this._onClear)};defineProperties(Iterator.prototype,assign({constructor:d(Iterator),_next:d(function(){var i;if(!this.__list__)return;if(this.__redo__){i=this.__redo__.shift();if(i!==undefined)return i}if(this.__nextIndex__=this.__nextIndex__)return;++this.__nextIndex__;if(!this.__redo__){defineProperty(this,"__redo__",d("c",[index]));return}this.__redo__.forEach(function(redo,i){if(redo>=index)this.__redo__[i]=++redo},this);this.__redo__.push(index)}),_onDelete:d(function(index){var i;if(index>=this.__nextIndex__)return;--this.__nextIndex__;if(!this.__redo__)return;i=this.__redo__.indexOf(index);if(i!==-1)this.__redo__.splice(i,1);this.__redo__.forEach(function(redo,i){if(redo>index)this.__redo__[i]=--redo},this)}),_onClear:d(function(){if(this.__redo__)clear.call(this.__redo__);this.__nextIndex__=0})})));defineProperty(Iterator.prototype,Symbol.iterator,d(function(){return this}));defineProperty(Iterator.prototype,Symbol.toStringTag,d("","Iterator"))},{d:15,"d/auto-bind":14,"es5-ext/array/#/clear":16,"es5-ext/object/assign":24,"es5-ext/object/valid-callable":41,"es5-ext/object/valid-value":42,"es6-symbol":52}],51:[function(require,module,exports){"use strict";var isString=require("es5-ext/string/is-string"),iteratorSymbol=require("es6-symbol").iterator,isArray=Array.isArray;module.exports=function(value){if(value==null)return false;if(isArray(value))return true;if(isString(value))return true;return typeof value[iteratorSymbol]==="function"}},{"es5-ext/string/is-string":46,"es6-symbol":52}],52:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Symbol:require("./polyfill")},{"./is-implemented":53,"./polyfill":55}],53:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],54:[function(require,module,exports){"use strict";module.exports=function(x){return x&&(typeof x==="symbol"||x["@@toStringTag"]==="Symbol")||false}},{}],55:[function(require,module,exports){"use strict";var d=require("d"),validateSymbol=require("./validate-symbol"),create=Object.create,defineProperties=Object.defineProperties,defineProperty=Object.defineProperty,objPrototype=Object.prototype,Symbol,HiddenSymbol,globalSymbols=create(null);var generateName=function(){var created=create(null);return function(desc){var postfix=0,name;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;name="@@"+desc;defineProperty(objPrototype,name,d.gs(null,function(value){defineProperty(this,name,d(value))}));return name}}();HiddenSymbol=function Symbol(description){if(this instanceof HiddenSymbol)throw new TypeError("TypeError: Symbol is not a constructor");return Symbol(description)};module.exports=Symbol=function Symbol(description){var symbol;if(this instanceof Symbol)throw new TypeError("TypeError: Symbol is not a constructor");symbol=create(HiddenSymbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};defineProperties(Symbol,{"for":d(function(key){if(globalSymbols[key])return globalSymbols[key];return globalSymbols[key]=Symbol(String(key))}),keyFor:d(function(s){var key;validateSymbol(s);for(key in globalSymbols)if(globalSymbols[key]===s)return key}),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),iterator:d("",Symbol("iterator")),match:d("",Symbol("match")),replace:d("",Symbol("replace")),search:d("",Symbol("search")),species:d("",Symbol("species")),split:d("",Symbol("split")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(HiddenSymbol.prototype,{constructor:d(Symbol),toString:d("",function(){return this.__name__})});defineProperties(Symbol.prototype,{toString:d(function(){return"Symbol ("+validateSymbol(this).__description__+")"}),valueOf:d(function(){return validateSymbol(this)})});defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(){return validateSymbol(this)}));defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"));defineProperty(HiddenSymbol.prototype,Symbol.toPrimitive,d("c",Symbol.prototype[Symbol.toPrimitive]));defineProperty(HiddenSymbol.prototype,Symbol.toStringTag,d("c",Symbol.prototype[Symbol.toStringTag]))},{"./validate-symbol":56,d:15}],56:[function(require,module,exports){"use strict";var isSymbol=require("./is-symbol");module.exports=function(value){if(!isSymbol(value))throw new TypeError(value+" is not a symbol");return value}},{"./is-symbol":54}],57:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Iterator=require("./"),defineProperty=Object.defineProperty,StringIterator;StringIterator=module.exports=function(str){if(!(this instanceof StringIterator))return new StringIterator(str);str=String(str);Iterator.call(this,str);defineProperty(this,"__length__",d("",str.length))};if(setPrototypeOf)setPrototypeOf(StringIterator,Iterator);StringIterator.prototype=Object.create(Iterator.prototype,{constructor:d(StringIterator),_next:d(function(){if(!this.__list__)return;if(this.__nextIndex__=55296&&code<=56319)return char+this.__list__[this.__nextIndex__++];return char}),toString:d(function(){return"[object String Iterator]"})})},{"./":50,d:15,"es5-ext/object/set-prototype-of":38}],58:[function(require,module,exports){"use strict";var isIterable=require("./is-iterable");module.exports=function(value){if(!isIterable(value))throw new TypeError(value+" is not iterable");return value}},{"./is-iterable":51}],59:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{"./is-implemented":60,"./polyfill":61,dup:52}],60:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],61:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:15}],62:[function(require,module,exports){"use strict";var d=require("d"),callable=require("es5-ext/object/valid-callable"),apply=Function.prototype.apply,call=Function.prototype.call,create=Object.create,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,hasOwnProperty=Object.prototype.hasOwnProperty,descriptor={configurable:true,enumerable:false,writable:true},on,once,off,emit,methods,descriptors,base;on=function(type,listener){var data;callable(listener);if(!hasOwnProperty.call(this,"__ee__")){data=descriptor.value=create(null);defineProperty(this,"__ee__",descriptor);descriptor.value=null}else{data=this.__ee__}if(!data[type])data[type]=listener;else if(typeof data[type]==="object")data[type].push(listener);else data[type]=[data[type],listener];return this};once=function(type,listener){var once,self;callable(listener);self=this;on.call(this,type,once=function(){off.call(self,type,once);apply.call(listener,this,arguments)});once.__eeOnceListener__=listener;return this};off=function(type,listener){var data,listeners,candidate,i;callable(listener);if(!hasOwnProperty.call(this,"__ee__"))return this;data=this.__ee__;if(!data[type])return this;listeners=data[type];if(typeof listeners==="object"){for(i=0;candidate=listeners[i];++i){if(candidate===listener||candidate.__eeOnceListener__===listener){if(listeners.length===2)data[type]=listeners[i?0:1];else listeners.splice(i,1)}}}else{if(listeners===listener||listeners.__eeOnceListener__===listener){delete data[type]}}return this};emit=function(type){var i,l,listener,listeners,args;if(!hasOwnProperty.call(this,"__ee__"))return;listeners=this.__ee__[type];if(!listeners)return;if(typeof listeners==="object"){l=arguments.length;args=new Array(l-1);for(i=1;i"}function tagContent(node){var innerHTML=node.properties.innerHTML;if(innerHTML!=null)return innerHTML;else{var ret="";if(node.children&&node.children.length){for(var i=0,l=node.children.length;i"}},{"./create-attribute":67,"./void-elements":78,"escape-html":69,"param-case":75,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":97,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":99,"virtual-dom/vnode/is-thunk":105,"virtual-dom/vnode/is-vnode":107,"virtual-dom/vnode/is-vtext":108,"virtual-dom/vnode/is-widget":109,xtend:76}],69:[function(require,module,exports){module.exports=escapeHtml;function escapeHtml(html){return String(html).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}},{}],70:[function(require,module,exports){var LANGUAGES={tr:{regexp:/\u0130|\u0049|\u0049\u0307/g,map:{"İ":"i",I:"ı","İ":"i"}},az:{regexp:/[\u0130]/g,map:{"İ":"i",I:"ı","İ":"i"}},lt:{regexp:/[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g,map:{I:"i̇",J:"j̇","Į":"į̇","Ì":"i̇̀","Í":"i̇́","Ĩ":"i̇̃"}}};module.exports=function(str,locale){var lang=LANGUAGES[locale];str=str==null?"":String(str);if(lang){str=str.replace(lang.regexp,function(m){return lang.map[m]})}return str.toLowerCase()}},{}],71:[function(require,module,exports){var lowerCase=require("lower-case");var NON_WORD_REGEXP=require("./vendor/non-word-regexp");var CAMEL_CASE_REGEXP=require("./vendor/camel-case-regexp");var TRAILING_DIGIT_REGEXP=require("./vendor/trailing-digit-regexp");module.exports=function(str,locale,replacement){if(str==null){return""}replacement=replacement||" ";function replace(match,index,string){if(index===0||index===string.length-match.length){return""}return replacement}str=String(str).replace(CAMEL_CASE_REGEXP,"$1 $2").replace(TRAILING_DIGIT_REGEXP,"$1 $2").replace(NON_WORD_REGEXP,replace);return lowerCase(str,locale)}},{"./vendor/camel-case-regexp":72,"./vendor/non-word-regexp":73,"./vendor/trailing-digit-regexp":74,"lower-case":70}],72:[function(require,module,exports){module.exports=/([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g},{}],73:[function(require,module,exports){module.exports=/[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g},{}],74:[function(require,module,exports){module.exports=/([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g},{}],75:[function(require,module,exports){var sentenceCase=require("sentence-case");module.exports=function(string,locale){return sentenceCase(string,locale,"-")}},{"sentence-case":71}],76:[function(require,module,exports){module.exports=extend;function extend(){var target={};for(var i=0;i>>0:limit>>>0;while(match=separator.exec(str)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(str.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i1&&match.index=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===str.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(str.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output};return self}()},{}],84:[function(require,module,exports){"use strict";var OneVersionConstraint=require("individual/one-version");var MY_VERSION="7";OneVersionConstraint("ev-store",MY_VERSION);var hashKey="__EV_STORE_KEY@"+MY_VERSION;module.exports=EvStore;function EvStore(elem){var hash=elem[hashKey];if(!hash){hash=elem[hashKey]={}}return hash}},{"individual/one-version":86}],85:[function(require,module,exports){(function(global){"use strict";var root=typeof window!=="undefined"?window:typeof global!=="undefined"?global:{};module.exports=Individual;function Individual(key,value){if(key in root){return root[key]}root[key]=value;return value}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],86:[function(require,module,exports){"use strict";var Individual=require("./index.js");module.exports=OneVersion;function OneVersion(moduleName,version,defaultValue){var key="__INDIVIDUAL_ONE_VERSION_"+moduleName;var enforceKey=key+"_ENFORCE_SINGLETON";var versionValue=Individual(enforceKey,version);if(versionValue!==version){throw new Error("Can only have one copy of "+moduleName+".\n"+"You already have version "+versionValue+" installed.\n"+"This means you cannot install version "+version)}return Individual(key,defaultValue)}},{"./index.js":85}],87:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":116}],88:[function(require,module,exports){"use strict";module.exports=function isObject(x){return typeof x==="object"&&x!==null; -}},{}],89:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],90:[function(require,module,exports){var patch=require("./vdom/patch.js");module.exports=patch},{"./vdom/patch.js":95}],91:[function(require,module,exports){var isObject=require("is-object");var isHook=require("../vnode/is-vhook.js");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,propName,propValue,previous)}else if(isHook(propValue)){removeProperty(node,propName,propValue,previous);if(propValue.hook){propValue.hook(node,propName,previous?previous[propName]:undefined)}}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else{node[propName]=propValue}}}}function removeProperty(node,propName,propValue,previous){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}else if(previousValue.unhook){previousValue.unhook(node,propName,propValue)}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"../vnode/is-vhook.js":106,"is-object":88}],92:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("../vnode/is-vnode.js");var isVText=require("../vnode/is-vtext.js");var isWidget=require("../vnode/is-widget.js");var handleThunk=require("../vnode/handle-thunk.js");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i>0;currentItem=indices[currentIndex];if(minIndex===maxIndex){return currentItem>=left&¤tItem<=right}else if(currentItemright){maxIndex=currentIndex-1}else{return true}}return false}function ascending(a,b){return a>b?1:-1}},{}],94:[function(require,module,exports){var applyProperties=require("./apply-properties");var isWidget=require("../vnode/is-widget.js");var VPatch=require("../vnode/vpatch.js");var updateWidget=require("./update-widget");module.exports=applyPatch;function applyPatch(vpatch,domNode,renderOptions){var type=vpatch.type;var vNode=vpatch.vNode;var patch=vpatch.patch;switch(type){case VPatch.REMOVE:return removeNode(domNode,vNode);case VPatch.INSERT:return insertNode(domNode,patch,renderOptions);case VPatch.VTEXT:return stringPatch(domNode,vNode,patch,renderOptions);case VPatch.WIDGET:return widgetPatch(domNode,vNode,patch,renderOptions);case VPatch.VNODE:return vNodePatch(domNode,vNode,patch,renderOptions);case VPatch.ORDER:reorderChildren(domNode,patch);return domNode;case VPatch.PROPS:applyProperties(domNode,patch,vNode.properties);return domNode;case VPatch.THUNK:return replaceRoot(domNode,renderOptions.patch(domNode,patch,renderOptions));default:return domNode}}function removeNode(domNode,vNode){var parentNode=domNode.parentNode;if(parentNode){parentNode.removeChild(domNode)}destroyWidget(domNode,vNode);return null}function insertNode(parentNode,vNode,renderOptions){var newNode=renderOptions.render(vNode,renderOptions);if(parentNode){parentNode.appendChild(newNode)}return parentNode}function stringPatch(domNode,leftVNode,vText,renderOptions){var newNode;if(domNode.nodeType===3){domNode.replaceData(0,domNode.length,vText.text);newNode=domNode}else{var parentNode=domNode.parentNode;newNode=renderOptions.render(vText,renderOptions);if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}}return newNode}function widgetPatch(domNode,leftVNode,widget,renderOptions){var updating=updateWidget(leftVNode,widget);var newNode;if(updating){newNode=widget.update(leftVNode,domNode)||domNode}else{newNode=renderOptions.render(widget,renderOptions)}var parentNode=domNode.parentNode;if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}if(!updating){destroyWidget(domNode,leftVNode)}return newNode}function vNodePatch(domNode,leftVNode,vNode,renderOptions){var parentNode=domNode.parentNode;var newNode=renderOptions.render(vNode,renderOptions);if(parentNode&&newNode!==domNode){parentNode.replaceChild(newNode,domNode)}return newNode}function destroyWidget(domNode,w){if(typeof w.destroy==="function"&&isWidget(w)){w.destroy(domNode)}}function reorderChildren(domNode,moves){var childNodes=domNode.childNodes;var keyMap={};var node;var remove;var insert;for(var i=0;i=length++?null:childNodes[insert.to])}}function replaceRoot(oldRoot,newRoot){if(oldRoot&&newRoot&&oldRoot!==newRoot&&oldRoot.parentNode){oldRoot.parentNode.replaceChild(newRoot,oldRoot)}return newRoot}},{"../vnode/is-widget.js":109,"../vnode/vpatch.js":112,"./apply-properties":91,"./update-widget":96}],95:[function(require,module,exports){var document=require("global/document");var isArray=require("x-is-array");var render=require("./create-element");var domIndex=require("./dom-index");var patchOp=require("./patch-op");module.exports=patch;function patch(rootNode,patches,renderOptions){renderOptions=renderOptions||{};renderOptions.patch=renderOptions.patch||patchRecursive;renderOptions.render=renderOptions.render||render;return renderOptions.patch(rootNode,patches,renderOptions)}function patchRecursive(rootNode,patches,renderOptions){var indices=patchIndices(patches);if(indices.length===0){return rootNode}var index=domIndex(rootNode,patches.a,indices);var ownerDocument=rootNode.ownerDocument;if(!renderOptions.document&&ownerDocument!==document){renderOptions.document=ownerDocument}for(var i=0;i-1?prop.substr(colonPosition+1):prop;node.removeAttributeNS(this.namespace,localName)};AttributeHook.prototype.type="AttributeHook"},{}],98:[function(require,module,exports){"use strict";var EvStore=require("ev-store");module.exports=EvHook;function EvHook(value){if(!(this instanceof EvHook)){return new EvHook(value)}this.value=value}EvHook.prototype.hook=function(node,propertyName){var es=EvStore(node);var propName=propertyName.substr(3);es[propName]=this.value};EvHook.prototype.unhook=function(node,propertyName){var es=EvStore(node);var propName=propertyName.substr(3);es[propName]=undefined}},{"ev-store":84}],99:[function(require,module,exports){"use strict";module.exports=SoftSetHook;function SoftSetHook(value){if(!(this instanceof SoftSetHook)){return new SoftSetHook(value)}this.value=value}SoftSetHook.prototype.hook=function(node,propertyName){if(node[propertyName]!==this.value){node[propertyName]=this.value}}},{}],100:[function(require,module,exports){"use strict";var isArray=require("x-is-array");var VNode=require("../vnode/vnode.js");var VText=require("../vnode/vtext.js");var isVNode=require("../vnode/is-vnode");var isVText=require("../vnode/is-vtext");var isWidget=require("../vnode/is-widget");var isHook=require("../vnode/is-vhook");var isVThunk=require("../vnode/is-thunk");var parseTag=require("./parse-tag.js");var softSetHook=require("./hooks/soft-set-hook.js");var evHook=require("./hooks/ev-hook.js");module.exports=h;function h(tagName,properties,children){var childNodes=[];var tag,props,key,namespace;if(!children&&isChildren(properties)){children=properties;props={}}props=props||properties||{};tag=parseTag(tagName,props);if(props.hasOwnProperty("key")){key=props.key;props.key=undefined}if(props.hasOwnProperty("namespace")){namespace=props.namespace;props.namespace=undefined}if(tag==="INPUT"&&!namespace&&props.hasOwnProperty("value")&&props.value!==undefined&&!isHook(props.value)){props.value=softSetHook(props.value)}transformProperties(props);if(children!==undefined&&children!==null){addChild(children,childNodes,tag,props)}return new VNode(tag,props,childNodes,key,namespace)}function addChild(c,childNodes,tag,props){if(typeof c==="string"){childNodes.push(new VText(c))}else if(typeof c==="number"){childNodes.push(new VText(String(c)))}else if(isChild(c)){childNodes.push(c)}else if(isArray(c)){for(var i=0;ibLen?aLen:bLen;for(var i=0;i=bFree.length?bChildren.length:bFree[freeIndex];for(var j=0;j=lastFreeIndex){newChildren.push(newItem)}}var simulate=newChildren.slice();var simulateIndex=0;var removes=[];var inserts=[];var simulateItem;for(var k=0;k1){for(var i=1;i=0?+index:ensureSize(iter)+ +index}function returnTrue(){return true}function wholeSlice(begin,end,size){return(begin===0||size!==undefined&&begin<=-size)&&(end===undefined||size!==undefined&&end>=size)}function resolveBegin(begin,size){return resolveIndex(begin,size,0)}function resolveEnd(end,size){return resolveIndex(end,size,size)}function resolveIndex(index,size,defaultIndex){return index===undefined?defaultIndex:index<0?Math.max(0,size+index):size===undefined?index:Math.min(size,index)}function Iterable(value){return isIterable(value)?value:Seq(value)}createClass(KeyedIterable,Iterable);function KeyedIterable(value){return isKeyed(value)?value:KeyedSeq(value)}createClass(IndexedIterable,Iterable);function IndexedIterable(value){return isIndexed(value)?value:IndexedSeq(value)}createClass(SetIterable,Iterable);function SetIterable(value){return isIterable(value)&&!isAssociative(value)?value:SetSeq(value)}function isIterable(maybeIterable){return!!(maybeIterable&&maybeIterable[IS_ITERABLE_SENTINEL])}function isKeyed(maybeKeyed){return!!(maybeKeyed&&maybeKeyed[IS_KEYED_SENTINEL])}function isIndexed(maybeIndexed){return!!(maybeIndexed&&maybeIndexed[IS_INDEXED_SENTINEL])}function isAssociative(maybeAssociative){return isKeyed(maybeAssociative)||isIndexed(maybeAssociative)}function isOrdered(maybeOrdered){return!!(maybeOrdered&&maybeOrdered[IS_ORDERED_SENTINEL])}Iterable.isIterable=isIterable;Iterable.isKeyed=isKeyed;Iterable.isIndexed=isIndexed;Iterable.isAssociative=isAssociative;Iterable.isOrdered=isOrdered;Iterable.Keyed=KeyedIterable;Iterable.Indexed=IndexedIterable;Iterable.Set=SetIterable;var IS_ITERABLE_SENTINEL="@@__IMMUTABLE_ITERABLE__@@";var IS_KEYED_SENTINEL="@@__IMMUTABLE_KEYED__@@";var IS_INDEXED_SENTINEL="@@__IMMUTABLE_INDEXED__@@";var IS_ORDERED_SENTINEL="@@__IMMUTABLE_ORDERED__@@";var ITERATE_KEYS=0;var ITERATE_VALUES=1;var ITERATE_ENTRIES=2;var REAL_ITERATOR_SYMBOL=typeof Symbol==="function"&&Symbol.iterator;var FAUX_ITERATOR_SYMBOL="@@iterator";var ITERATOR_SYMBOL=REAL_ITERATOR_SYMBOL||FAUX_ITERATOR_SYMBOL;function src_Iterator__Iterator(next){this.next=next}src_Iterator__Iterator.prototype.toString=function(){return"[Iterator]"};src_Iterator__Iterator.KEYS=ITERATE_KEYS;src_Iterator__Iterator.VALUES=ITERATE_VALUES;src_Iterator__Iterator.ENTRIES=ITERATE_ENTRIES;src_Iterator__Iterator.prototype.inspect=src_Iterator__Iterator.prototype.toSource=function(){return this.toString()};src_Iterator__Iterator.prototype[ITERATOR_SYMBOL]=function(){return this};function iteratorValue(type,k,v,iteratorResult){var value=type===0?k:type===1?v:[k,v];iteratorResult?iteratorResult.value=value:iteratorResult={value:value,done:false};return iteratorResult}function iteratorDone(){return{value:undefined,done:true}}function hasIterator(maybeIterable){return!!getIteratorFn(maybeIterable)}function isIterator(maybeIterator){return maybeIterator&&typeof maybeIterator.next==="function"}function getIterator(iterable){var iteratorFn=getIteratorFn(iterable);return iteratorFn&&iteratorFn.call(iterable)}function getIteratorFn(iterable){var iteratorFn=iterable&&(REAL_ITERATOR_SYMBOL&&iterable[REAL_ITERATOR_SYMBOL]||iterable[FAUX_ITERATOR_SYMBOL]);if(typeof iteratorFn==="function"){return iteratorFn}}function isArrayLike(value){return value&&typeof value.length==="number"}createClass(Seq,Iterable);function Seq(value){return value===null||value===undefined?emptySequence():isIterable(value)?value.toSeq():seqFromValue(value)}Seq.of=function(){return Seq(arguments)};Seq.prototype.toSeq=function(){return this};Seq.prototype.toString=function(){return this.__toString("Seq {","}")};Seq.prototype.cacheResult=function(){if(!this._cache&&this.__iterateUncached){this._cache=this.entrySeq().toArray();this.size=this._cache.length}return this};Seq.prototype.__iterate=function(fn,reverse){return seqIterate(this,fn,reverse,true)};Seq.prototype.__iterator=function(type,reverse){return seqIterator(this,type,reverse,true)};createClass(KeyedSeq,Seq);function KeyedSeq(value){return value===null||value===undefined?emptySequence().toKeyedSeq():isIterable(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():keyedSeqFromValue(value)}KeyedSeq.prototype.toKeyedSeq=function(){return this};createClass(IndexedSeq,Seq);function IndexedSeq(value){return value===null||value===undefined?emptySequence():!isIterable(value)?indexedSeqFromValue(value):isKeyed(value)?value.entrySeq():value.toIndexedSeq()}IndexedSeq.of=function(){return IndexedSeq(arguments)};IndexedSeq.prototype.toIndexedSeq=function(){return this};IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")};IndexedSeq.prototype.__iterate=function(fn,reverse){return seqIterate(this,fn,reverse,false)};IndexedSeq.prototype.__iterator=function(type,reverse){return seqIterator(this,type,reverse,false)};createClass(SetSeq,Seq);function SetSeq(value){return(value===null||value===undefined?emptySequence():!isIterable(value)?indexedSeqFromValue(value):isKeyed(value)?value.entrySeq():value).toSetSeq()}SetSeq.of=function(){return SetSeq(arguments)};SetSeq.prototype.toSetSeq=function(){return this};Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;var IS_SEQ_SENTINEL="@@__IMMUTABLE_SEQ__@@";Seq.prototype[IS_SEQ_SENTINEL]=true;createClass(ArraySeq,IndexedSeq);function ArraySeq(array){this._array=array;this.size=array.length}ArraySeq.prototype.get=function(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue};ArraySeq.prototype.__iterate=function(fn,reverse){var array=this._array;var maxIndex=array.length-1;for(var ii=0;ii<=maxIndex;ii++){if(fn(array[reverse?maxIndex-ii:ii],ii,this)===false){return ii+1}}return ii};ArraySeq.prototype.__iterator=function(type,reverse){var array=this._array;var maxIndex=array.length-1;var ii=0;return new src_Iterator__Iterator(function(){return ii>maxIndex?iteratorDone():iteratorValue(type,ii,array[reverse?maxIndex-ii++:ii++])})};createClass(ObjectSeq,KeyedSeq);function ObjectSeq(object){var keys=Object.keys(object);this._object=object;this._keys=keys;this.size=keys.length}ObjectSeq.prototype.get=function(key,notSetValue){if(notSetValue!==undefined&&!this.has(key)){return notSetValue}return this._object[key]};ObjectSeq.prototype.has=function(key){return this._object.hasOwnProperty(key)};ObjectSeq.prototype.__iterate=function(fn,reverse){var object=this._object;var keys=this._keys;var maxIndex=keys.length-1;for(var ii=0;ii<=maxIndex;ii++){var key=keys[reverse?maxIndex-ii:ii];if(fn(object[key],key,this)===false){return ii+1}}return ii};ObjectSeq.prototype.__iterator=function(type,reverse){var object=this._object;var keys=this._keys;var maxIndex=keys.length-1;var ii=0;return new src_Iterator__Iterator(function(){var key=keys[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,key,object[key])})};ObjectSeq.prototype[IS_ORDERED_SENTINEL]=true;createClass(IterableSeq,IndexedSeq);function IterableSeq(iterable){this._iterable=iterable;this.size=iterable.length||iterable.size}IterableSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterable=this._iterable;var iterator=getIterator(iterable);var iterations=0;if(isIterator(iterator)){var step;while(!(step=iterator.next()).done){if(fn(step.value,iterations++,this)===false){break}}}return iterations};IterableSeq.prototype.__iteratorUncached=function(type,reverse){if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterable=this._iterable;var iterator=getIterator(iterable);if(!isIterator(iterator)){return new src_Iterator__Iterator(iteratorDone)}var iterations=0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value)})};createClass(IteratorSeq,IndexedSeq);function IteratorSeq(iterator){this._iterator=iterator;this._iteratorCache=[]}IteratorSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterator=this._iterator;var cache=this._iteratorCache;var iterations=0;while(iterations=cache.length){var step=iterator.next();if(step.done){return step}cache[iterations]=step.value}return iteratorValue(type,iterations,cache[iterations++])})};function isSeq(maybeSeq){return!!(maybeSeq&&maybeSeq[IS_SEQ_SENTINEL])}var EMPTY_SEQ;function emptySequence(){return EMPTY_SEQ||(EMPTY_SEQ=new ArraySeq([]))}function keyedSeqFromValue(value){var seq=Array.isArray(value)?new ArraySeq(value).fromEntrySeq():isIterator(value)?new IteratorSeq(value).fromEntrySeq():hasIterator(value)?new IterableSeq(value).fromEntrySeq():typeof value==="object"?new ObjectSeq(value):undefined;if(!seq){throw new TypeError("Expected Array or iterable object of [k, v] entries, "+"or keyed object: "+value)}return seq}function indexedSeqFromValue(value){var seq=maybeIndexedSeqFromValue(value);if(!seq){throw new TypeError("Expected Array or iterable object of values: "+value)}return seq}function seqFromValue(value){var seq=maybeIndexedSeqFromValue(value)||typeof value==="object"&&new ObjectSeq(value);if(!seq){throw new TypeError("Expected Array or iterable object of values, or keyed object: "+value)}return seq}function maybeIndexedSeqFromValue(value){return isArrayLike(value)?new ArraySeq(value):isIterator(value)?new IteratorSeq(value):hasIterator(value)?new IterableSeq(value):undefined}function seqIterate(seq,fn,reverse,useKeys){var cache=seq._cache;if(cache){var maxIndex=cache.length-1;for(var ii=0;ii<=maxIndex;ii++){var entry=cache[reverse?maxIndex-ii:ii];if(fn(entry[1],useKeys?entry[0]:ii,seq)===false){return ii+1}}return ii}return seq.__iterateUncached(fn,reverse)}function seqIterator(seq,type,reverse,useKeys){var cache=seq._cache;if(cache){var maxIndex=cache.length-1;var ii=0;return new src_Iterator__Iterator(function(){var entry=cache[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,useKeys?entry[0]:ii-1,entry[1])})}return seq.__iteratorUncached(type,reverse)}createClass(Collection,Iterable);function Collection(){throw TypeError("Abstract")}createClass(KeyedCollection,Collection);function KeyedCollection(){}createClass(IndexedCollection,Collection);function IndexedCollection(){}createClass(SetCollection,Collection);function SetCollection(){}Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;function is(valueA,valueB){if(valueA===valueB||valueA!==valueA&&valueB!==valueB){return true}if(!valueA||!valueB){return false}if(typeof valueA.valueOf==="function"&&typeof valueB.valueOf==="function"){valueA=valueA.valueOf();valueB=valueB.valueOf();if(valueA===valueB||valueA!==valueA&&valueB!==valueB){return true}if(!valueA||!valueB){return false}}if(typeof valueA.equals==="function"&&typeof valueB.equals==="function"&&valueA.equals(valueB)){return true}return false}function fromJS(json,converter){return converter?fromJSWith(converter,json,"",{"":json}):fromJSDefault(json)}function fromJSWith(converter,json,key,parentJSON){if(Array.isArray(json)){return converter.call(parentJSON,key,IndexedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)}))}if(isPlainObj(json)){return converter.call(parentJSON,key,KeyedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)}))}return json}function fromJSDefault(json){if(Array.isArray(json)){return IndexedSeq(json).map(fromJSDefault).toList()}if(isPlainObj(json)){return KeyedSeq(json).map(fromJSDefault).toMap()}return json}function isPlainObj(value){return value&&(value.constructor===Object||value.constructor===undefined)}var src_Math__imul=typeof Math.imul==="function"&&Math.imul(4294967295,2)===-2?Math.imul:function src_Math__imul(a,b){a=a|0;b=b|0;var c=a&65535;var d=b&65535;return c*d+((a>>>16)*d+c*(b>>>16)<<16>>>0)|0};function smi(i32){return i32>>>1&1073741824|i32&3221225471}function hash(o){if(o===false||o===null||o===undefined){return 0}if(typeof o.valueOf==="function"){o=o.valueOf();if(o===false||o===null||o===undefined){return 0}}if(o===true){return 1}var type=typeof o;if(type==="number"){var h=o|0;if(h!==o){h^=o*4294967295}while(o>4294967295){o/=4294967295;h^=o}return smi(h)}if(type==="string"){return o.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(o):hashString(o)}if(typeof o.hashCode==="function"){return o.hashCode()}return hashJSObj(o)}function cachedHashString(string){var hash=stringHashCache[string];if(hash===undefined){hash=hashString(string);if(STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE){STRING_HASH_CACHE_SIZE=0;stringHashCache={}}STRING_HASH_CACHE_SIZE++;stringHashCache[string]=hash}return hash}function hashString(string){var hash=0;for(var ii=0;ii0){switch(node.nodeType){case 1:return node.uniqueID;case 9:return node.documentElement&&node.documentElement.uniqueID}}}var usingWeakMap=typeof WeakMap==="function";var weakMap;if(usingWeakMap){weakMap=new WeakMap}var objHashUID=0;var UID_HASH_KEY="__immutablehash__";if(typeof Symbol==="function"){UID_HASH_KEY=Symbol(UID_HASH_KEY)}var STRING_HASH_CACHE_MIN_STRLEN=16;var STRING_HASH_CACHE_MAX_SIZE=255;var STRING_HASH_CACHE_SIZE=0;var stringHashCache={};function invariant(condition,error){if(!condition)throw new Error(error)}function assertNotInfinite(size){invariant(size!==Infinity,"Cannot perform this action with an infinite size.")}createClass(ToKeyedSequence,KeyedSeq);function ToKeyedSequence(indexed,useKeys){this._iter=indexed;this._useKeys=useKeys;this.size=indexed.size}ToKeyedSequence.prototype.get=function(key,notSetValue){return this._iter.get(key,notSetValue)};ToKeyedSequence.prototype.has=function(key){return this._iter.has(key)};ToKeyedSequence.prototype.valueSeq=function(){return this._iter.valueSeq()};ToKeyedSequence.prototype.reverse=function(){var this$0=this;var reversedSequence=reverseFactory(this,true);if(!this._useKeys){reversedSequence.valueSeq=function(){return this$0._iter.toSeq().reverse()}}return reversedSequence};ToKeyedSequence.prototype.map=function(mapper,context){var this$0=this;var mappedSequence=mapFactory(this,mapper,context);if(!this._useKeys){mappedSequence.valueSeq=function(){return this$0._iter.toSeq().map(mapper,context)}}return mappedSequence};ToKeyedSequence.prototype.__iterate=function(fn,reverse){var this$0=this;var ii;return this._iter.__iterate(this._useKeys?function(v,k){return fn(v,k,this$0)}:(ii=reverse?resolveSize(this):0,function(v){return fn(v,reverse?--ii:ii++,this$0)}),reverse)};ToKeyedSequence.prototype.__iterator=function(type,reverse){if(this._useKeys){return this._iter.__iterator(type,reverse)}var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);var ii=reverse?resolveSize(this):0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,reverse?--ii:ii++,step.value,step)})};ToKeyedSequence.prototype[IS_ORDERED_SENTINEL]=true;createClass(ToIndexedSequence,IndexedSeq);function ToIndexedSequence(iter){this._iter=iter;this.size=iter.size}ToIndexedSequence.prototype.includes=function(value){return this._iter.includes(value)};ToIndexedSequence.prototype.__iterate=function(fn,reverse){var this$0=this;var iterations=0;return this._iter.__iterate(function(v){return fn(v,iterations++,this$0)},reverse)};ToIndexedSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);var iterations=0;return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value,step)})};createClass(ToSetSequence,SetSeq);function ToSetSequence(iter){this._iter=iter;this.size=iter.size}ToSetSequence.prototype.has=function(key){return this._iter.includes(key)};ToSetSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(v){return fn(v,v,this$0)},reverse)};ToSetSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,step.value,step.value,step)})};createClass(FromEntriesSequence,KeyedSeq);function FromEntriesSequence(entries){this._iter=entries;this.size=entries.size}FromEntriesSequence.prototype.entrySeq=function(){return this._iter.toSeq()};FromEntriesSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(entry){if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return fn(indexedIterable?entry.get(1):entry[1],indexedIterable?entry.get(0):entry[0],this$0)}},reverse)};FromEntriesSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new src_Iterator__Iterator(function(){while(true){var step=iterator.next();if(step.done){return step}var entry=step.value;if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return iteratorValue(type,indexedIterable?entry.get(0):entry[0],indexedIterable?entry.get(1):entry[1],step)}}})};ToIndexedSequence.prototype.cacheResult=ToKeyedSequence.prototype.cacheResult=ToSetSequence.prototype.cacheResult=FromEntriesSequence.prototype.cacheResult=cacheResultThrough;function flipFactory(iterable){var flipSequence=makeSequence(iterable);flipSequence._iter=iterable;flipSequence.size=iterable.size;flipSequence.flip=function(){return iterable};flipSequence.reverse=function(){var reversedSequence=iterable.reverse.apply(this);reversedSequence.flip=function(){return iterable.reverse()};return reversedSequence};flipSequence.has=function(key){return iterable.includes(key)};flipSequence.includes=function(key){return iterable.has(key)};flipSequence.cacheResult=cacheResultThrough;flipSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(k,v,this$0)!==false},reverse)};flipSequence.__iteratorUncached=function(type,reverse){if(type===ITERATE_ENTRIES){var iterator=iterable.__iterator(type,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();if(!step.done){var k=step.value[0];step.value[0]=step.value[1];step.value[1]=k}return step})}return iterable.__iterator(type===ITERATE_VALUES?ITERATE_KEYS:ITERATE_VALUES,reverse)};return flipSequence}function mapFactory(iterable,mapper,context){var mappedSequence=makeSequence(iterable);mappedSequence.size=iterable.size;mappedSequence.has=function(key){return iterable.has(key)};mappedSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,iterable)};mappedSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k,c){return fn(mapper.call(context,v,k,c),k,this$0)!==false},reverse)};mappedSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);return new src_Iterator__Iterator(function(){var step=iterator.next();if(step.done){return step}var entry=step.value;var key=entry[0];return iteratorValue(type,key,mapper.call(context,entry[1],key,iterable),step)})};return mappedSequence}function reverseFactory(iterable,useKeys){var reversedSequence=makeSequence(iterable);reversedSequence._iter=iterable;reversedSequence.size=iterable.size;reversedSequence.reverse=function(){return iterable};if(iterable.flip){reversedSequence.flip=function(){var flipSequence=flipFactory(iterable);flipSequence.reverse=function(){return iterable.flip()};return flipSequence}}reversedSequence.get=function(key,notSetValue){return iterable.get(useKeys?key:-1-key,notSetValue)};reversedSequence.has=function(key){return iterable.has(useKeys?key:-1-key)};reversedSequence.includes=function(value){return iterable.includes(value)};reversedSequence.cacheResult=cacheResultThrough;reversedSequence.__iterate=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(v,k,this$0)},!reverse)};reversedSequence.__iterator=function(type,reverse){return iterable.__iterator(type,!reverse)};return reversedSequence}function filterFactory(iterable,predicate,context,useKeys){var filterSequence=makeSequence(iterable);if(useKeys){filterSequence.has=function(key){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,iterable)};filterSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,iterable)?v:notSetValue}}filterSequence.__iterateUncached=function(fn,reverse){var this$0=this;var iterations=0;iterable.__iterate(function(v,k,c){if(predicate.call(context,v,k,c)){iterations++;return fn(v,useKeys?k:iterations-1,this$0)}},reverse);return iterations};filterSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var iterations=0;return new src_Iterator__Iterator(function(){while(true){var step=iterator.next();if(step.done){return step}var entry=step.value;var key=entry[0];var value=entry[1];if(predicate.call(context,value,key,iterable)){return iteratorValue(type,useKeys?key:iterations++,value,step)}}})};return filterSequence}function countByFactory(iterable,grouper,context){var groups=src_Map__Map().asMutable();iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),0,function(a){return a+1})});return groups.asImmutable()}function groupByFactory(iterable,grouper,context){var isKeyedIter=isKeyed(iterable);var groups=(isOrdered(iterable)?OrderedMap():src_Map__Map()).asMutable();iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),function(a){return a=a||[],a.push(isKeyedIter?[k,v]:v),a})});var coerce=iterableClass(iterable);return groups.map(function(arr){return reify(iterable,coerce(arr))})}function sliceFactory(iterable,begin,end,useKeys){var originalSize=iterable.size;if(wholeSlice(begin,end,originalSize)){return iterable}var resolvedBegin=resolveBegin(begin,originalSize);var resolvedEnd=resolveEnd(end,originalSize);if(resolvedBegin!==resolvedBegin||resolvedEnd!==resolvedEnd){return sliceFactory(iterable.toSeq().cacheResult(),begin,end,useKeys)}var resolvedSize=resolvedEnd-resolvedBegin;var sliceSize;if(resolvedSize===resolvedSize){sliceSize=resolvedSize<0?0:resolvedSize}var sliceSeq=makeSequence(iterable);sliceSeq.size=sliceSize;if(!useKeys&&isSeq(iterable)&&sliceSize>=0){sliceSeq.get=function(index,notSetValue){index=wrapIndex(this,index);return index>=0&&indexsliceSize){ -return iteratorDone()}var step=iterator.next();if(useKeys||type===ITERATE_VALUES){return step}else if(type===ITERATE_KEYS){return iteratorValue(type,iterations-1,undefined,step)}else{return iteratorValue(type,iterations-1,step.value[1],step)}})};return sliceSeq}function takeWhileFactory(iterable,predicate,context){var takeSequence=makeSequence(iterable);takeSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterations=0;iterable.__iterate(function(v,k,c){return predicate.call(context,v,k,c)&&++iterations&&fn(v,k,this$0)});return iterations};takeSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var iterating=true;return new src_Iterator__Iterator(function(){if(!iterating){return iteratorDone()}var step=iterator.next();if(step.done){return step}var entry=step.value;var k=entry[0];var v=entry[1];if(!predicate.call(context,v,k,this$0)){iterating=false;return iteratorDone()}return type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step)})};return takeSequence}function skipWhileFactory(iterable,predicate,context,useKeys){var skipSequence=makeSequence(iterable);skipSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterate(fn,reverse)}var isSkipping=true;var iterations=0;iterable.__iterate(function(v,k,c){if(!(isSkipping&&(isSkipping=predicate.call(context,v,k,c)))){iterations++;return fn(v,useKeys?k:iterations-1,this$0)}});return iterations};skipSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var skipping=true;var iterations=0;return new src_Iterator__Iterator(function(){var step,k,v;do{step=iterator.next();if(step.done){if(useKeys||type===ITERATE_VALUES){return step}else if(type===ITERATE_KEYS){return iteratorValue(type,iterations++,undefined,step)}else{return iteratorValue(type,iterations++,step.value[1],step)}}var entry=step.value;k=entry[0];v=entry[1];skipping&&(skipping=predicate.call(context,v,k,this$0))}while(skipping);return type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step)})};return skipSequence}function concatFactory(iterable,values){var isKeyedIterable=isKeyed(iterable);var iters=[iterable].concat(values).map(function(v){if(!isIterable(v)){v=isKeyedIterable?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v])}else if(isKeyedIterable){v=KeyedIterable(v)}return v}).filter(function(v){return v.size!==0});if(iters.length===0){return iterable}if(iters.length===1){var singleton=iters[0];if(singleton===iterable||isKeyedIterable&&isKeyed(singleton)||isIndexed(iterable)&&isIndexed(singleton)){return singleton}}var concatSeq=new ArraySeq(iters);if(isKeyedIterable){concatSeq=concatSeq.toKeyedSeq()}else if(!isIndexed(iterable)){concatSeq=concatSeq.toSetSeq()}concatSeq=concatSeq.flatten(true);concatSeq.size=iters.reduce(function(sum,seq){if(sum!==undefined){var size=seq.size;if(size!==undefined){return sum+size}}},0);return concatSeq}function flattenFactory(iterable,depth,useKeys){var flatSequence=makeSequence(iterable);flatSequence.__iterateUncached=function(fn,reverse){var iterations=0;var stopped=false;function flatDeep(iter,currentDepth){var this$0=this;iter.__iterate(function(v,k){if((!depth||currentDepth0}function zipWithFactory(keyIter,zipper,iters){var zipSequence=makeSequence(keyIter);zipSequence.size=new ArraySeq(iters).map(function(i){return i.size}).min();zipSequence.__iterate=function(fn,reverse){var iterator=this.__iterator(ITERATE_VALUES,reverse);var step;var iterations=0;while(!(step=iterator.next()).done){if(fn(step.value,iterations++,this)===false){break}}return iterations};zipSequence.__iteratorUncached=function(type,reverse){var iterators=iters.map(function(i){return i=Iterable(i),getIterator(reverse?i.reverse():i)});var iterations=0;var isDone=false;return new src_Iterator__Iterator(function(){var steps;if(!isDone){steps=iterators.map(function(i){return i.next()});isDone=steps.some(function(s){return s.done})}if(isDone){return iteratorDone()}return iteratorValue(type,iterations++,zipper.apply(null,steps.map(function(s){return s.value})))})};return zipSequence}function reify(iter,seq){return isSeq(iter)?seq:iter.constructor(seq)}function validateEntry(entry){if(entry!==Object(entry)){throw new TypeError("Expected [K, V] tuple: "+entry)}}function resolveSize(iter){assertNotInfinite(iter.size);return ensureSize(iter)}function iterableClass(iterable){return isKeyed(iterable)?KeyedIterable:isIndexed(iterable)?IndexedIterable:SetIterable}function makeSequence(iterable){return Object.create((isKeyed(iterable)?KeyedSeq:isIndexed(iterable)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){if(this._iter.cacheResult){this._iter.cacheResult();this.size=this._iter.size;return this}else{return Seq.prototype.cacheResult.call(this)}}function defaultComparator(a,b){return a>b?1:a=MAX_ARRAY_MAP_SIZE){return createNodes(ownerID,entries,key,value)}var isEditable=ownerID&&ownerID===this.ownerID;var newEntries=isEditable?entries:arrCopy(entries);if(exists){if(removed){idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop()}else{newEntries[idx]=[key,value]}}else{newEntries.push([key,value])}if(isEditable){this.entries=newEntries;return this}return new ArrayMapNode(ownerID,newEntries)};function BitmapIndexedNode(ownerID,bitmap,nodes){this.ownerID=ownerID;this.bitmap=bitmap;this.nodes=nodes}BitmapIndexedNode.prototype.get=function(shift,keyHash,key,notSetValue){if(keyHash===undefined){keyHash=hash(key)}var bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK);var bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)};BitmapIndexedNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash===undefined){keyHash=hash(key)}var keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK;var bit=1<=MAX_BITMAP_INDEXED_SIZE){return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode)}if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1])){return nodes[idx^1]}if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode)){return newNode}var isEditable=ownerID&&ownerID===this.ownerID;var newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit;var newNodes=exists?newNode?setIn(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);if(isEditable){this.bitmap=newBitmap;this.nodes=newNodes;return this}return new BitmapIndexedNode(ownerID,newBitmap,newNodes)};function HashArrayMapNode(ownerID,count,nodes){this.ownerID=ownerID;this.count=count;this.nodes=nodes}HashArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){if(keyHash===undefined){keyHash=hash(key)}var idx=(shift===0?keyHash:keyHash>>>shift)&MASK;var node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue};HashArrayMapNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash===undefined){keyHash=hash(key)}var idx=(shift===0?keyHash:keyHash>>>shift)&MASK;var removed=value===NOT_SET;var nodes=this.nodes;var node=nodes[idx];if(removed&&!node){return this}var newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node){return this}var newCount=this.count;if(!node){newCount++}else if(!newNode){newCount--;if(newCount>>shift)&MASK;var idx2=(shift===0?keyHash:keyHash>>>shift)&MASK;var newNode;var nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:(newNode=new ValueNode(ownerID,keyHash,entry),idx1>>=1){expandedNodes[ii]=bitmap&1?nodes[count++]:undefined}expandedNodes[including]=node;return new HashArrayMapNode(ownerID,count+1,expandedNodes)}function mergeIntoMapWith(map,merger,iterables){var iters=[];for(var ii=0;ii>1&1431655765);x=(x&858993459)+(x>>2&858993459);x=x+(x>>4)&252645135;x=x+(x>>8);x=x+(x>>16);return x&127}function setIn(array,idx,val,canEdit){var newArray=canEdit?array:arrCopy(array);newArray[idx]=val;return newArray}function spliceIn(array,idx,val,canEdit){var newLen=array.length+1;if(canEdit&&idx+1===newLen){array[idx]=val;return array}var newArray=new Array(newLen);var after=0;for(var ii=0;ii0&&size=this.size){return notSetValue}index+=this._origin;var node=listNodeFor(this,index);return node&&node.array[index&MASK]};List.prototype.set=function(index,value){return updateList(this,index,value)};List.prototype.remove=function(index){return!this.has(index)?this:index===0?this.shift():index===this.size-1?this.pop():this.splice(index,1)};List.prototype.clear=function(){if(this.size===0){return this}if(this.__ownerID){this.size=this._origin=this._capacity=0;this._level=SHIFT;this._root=this._tail=null;this.__hash=undefined;this.__altered=true;return this}return emptyList()};List.prototype.push=function(){var values=arguments;var oldSize=this.size;return this.withMutations(function(list){setListBounds(list,0,oldSize+values.length);for(var ii=0;ii>>level&MASK;if(originIndex>=this.array.length){return new VNode([],ownerID)}var removingFirst=originIndex===0;var newChild;if(level>0){var oldChild=this.array[originIndex];newChild=oldChild&&oldChild.removeBefore(ownerID,level-SHIFT,index);if(newChild===oldChild&&removingFirst){return this}}if(removingFirst&&!newChild){return this}var editable=editableVNode(this,ownerID);if(!removingFirst){for(var ii=0;ii>>level&MASK;if(sizeIndex>=this.array.length){return this}var removingLast=sizeIndex===this.array.length-1;var newChild;if(level>0){var oldChild=this.array[sizeIndex];newChild=oldChild&&oldChild.removeAfter(ownerID,level-SHIFT,index);if(newChild===oldChild&&removingLast){return this}}if(removingLast&&!newChild){return this}var editable=editableVNode(this,ownerID);if(!removingLast){editable.array.pop()}if(newChild){editable.array[sizeIndex]=newChild}return editable};var DONE={};function iterateList(list,reverse){var left=list._origin;var right=list._capacity;var tailPos=getTailOffset(right);var tail=list._tail;return iterateNodeOrLeaf(list._root,list._level,0);function iterateNodeOrLeaf(node,level,offset){return level===0?iterateLeaf(node,offset):iterateNode(node,level,offset)}function iterateLeaf(node,offset){var array=offset===tailPos?tail&&tail.array:node&&node.array;var from=offset>left?0:left-offset;var to=right-offset;if(to>SIZE){to=SIZE}return function(){if(from===to){return DONE}var idx=reverse?--to:from++;return array&&array[idx]}}function iterateNode(node,level,offset){var values;var array=node&&node.array;var from=offset>left?0:left-offset>>level;var to=(right-offset>>level)+1;if(to>SIZE){to=SIZE}return function(){do{if(values){var value=values();if(value!==DONE){return value}values=null}if(from===to){return DONE}var idx=reverse?--to:from++;values=iterateNodeOrLeaf(array&&array[idx],level-SHIFT,offset+(idx<=list.size||index<0){return list.withMutations(function(list){index<0?setListBounds(list,index).set(0,value):setListBounds(list,0,index+1).set(index,value)})}index+=list._origin;var newTail=list._tail;var newRoot=list._root;var didAlter=MakeRef(DID_ALTER);if(index>=getTailOffset(list._capacity)){newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter)}else{newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter)}if(!didAlter.value){return list}if(list.__ownerID){list._root=newRoot;list._tail=newTail;list.__hash=undefined;list.__altered=true;return list}return makeList(list._origin,list._capacity,list._level,newRoot,newTail)}function updateVNode(node,ownerID,level,index,value,didAlter){var idx=index>>>level&MASK;var nodeHas=node&&idx0){var lowerNode=node&&node.array[idx];var newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);if(newLowerNode===lowerNode){return node}newNode=editableVNode(node,ownerID);newNode.array[idx]=newLowerNode;return newNode}if(nodeHas&&node.array[idx]===value){return node}SetRef(didAlter);newNode=editableVNode(node,ownerID);if(value===undefined&&idx===newNode.array.length-1){newNode.array.pop()}else{newNode.array[idx]=value}return newNode}function editableVNode(node,ownerID){if(ownerID&&node&&ownerID===node.ownerID){return node}return new VNode(node?node.array.slice():[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity)){return list._tail}if(rawIndex<1<0){node=node.array[rawIndex>>>level&MASK];level-=SHIFT}return node}}function setListBounds(list,begin,end){var owner=list.__ownerID||new OwnerID;var oldOrigin=list._origin;var oldCapacity=list._capacity;var newOrigin=oldOrigin+begin;var newCapacity=end===undefined?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity){return list}if(newOrigin>=newCapacity){return list.clear()}var newLevel=list._level;var newRoot=list._root;var offsetShift=0;while(newOrigin+offsetShift<0){newRoot=new VNode(newRoot&&newRoot.array.length?[undefined,newRoot]:[],owner);newLevel+=SHIFT;offsetShift+=1<=1<oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOriginSHIFT;level-=SHIFT){var idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity=newTailOffset){newOrigin-=newTailOffset;newCapacity-=newTailOffset;newLevel=SHIFT;newRoot=null;newTail=newTail&&newTail.removeBefore(owner,0,newOrigin)}else if(newOrigin>oldOrigin||newTailOffset>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK){break}if(beginIndex){offsetShift+=(1<oldOrigin){newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift)}if(newRoot&&newTailOffsetmaxSize){maxSize=iter.size}if(!isIterable(value)){iter=iter.map(function(v){return fromJS(v)})}iters.push(iter)}if(maxSize>list.size){list=list.setSize(maxSize)}return mergeIntoCollectionWith(list,merger,iters)}function getTailOffset(size){return size>>SHIFT<=SIZE&&list.size>=map.size*2){newList=list.filter(function(entry,idx){return entry!==undefined&&i!==idx});newMap=newList.toKeyedSeq().map(function(entry){return entry[0]}).flip().toMap();if(omap.__ownerID){newMap.__ownerID=newList.__ownerID=omap.__ownerID}}else{newMap=map.remove(k);newList=i===list.size-1?list.pop():list.set(i,undefined)}}else{if(has){if(v===list.get(i)[1]){return omap}newMap=map;newList=list.set(i,[k,v])}else{newMap=map.set(k,list.size);newList=list.set(list.size,[k,v])}}if(omap.__ownerID){omap.size=newMap.size;omap._map=newMap;omap._list=newList;omap.__hash=undefined;return omap}return makeOrderedMap(newMap,newList)}createClass(Stack,IndexedCollection);function Stack(value){return value===null||value===undefined?emptyStack():isStack(value)?value:emptyStack().unshiftAll(value)}Stack.of=function(){return this(arguments)};Stack.prototype.toString=function(){return this.__toString("Stack [","]")};Stack.prototype.get=function(index,notSetValue){var head=this._head;index=wrapIndex(this,index);while(head&&index--){head=head.next}return head?head.value:notSetValue};Stack.prototype.peek=function(){return this._head&&this._head.value};Stack.prototype.push=function(){if(arguments.length===0){return this}var newSize=this.size+arguments.length;var head=this._head;for(var ii=arguments.length-1;ii>=0;ii--){head={value:arguments[ii],next:head}}if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.pushAll=function(iter){iter=IndexedIterable(iter);if(iter.size===0){return this}assertNotInfinite(iter.size);var newSize=this.size;var head=this._head;iter.reverse().forEach(function(value){newSize++;head={value:value,next:head}});if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.pop=function(){return this.slice(1)};Stack.prototype.unshift=function(){return this.push.apply(this,arguments)};Stack.prototype.unshiftAll=function(iter){return this.pushAll(iter)};Stack.prototype.shift=function(){return this.pop.apply(this,arguments)};Stack.prototype.clear=function(){if(this.size===0){return this}if(this.__ownerID){this.size=0;this._head=undefined;this.__hash=undefined;this.__altered=true;return this}return emptyStack()};Stack.prototype.slice=function(begin,end){if(wholeSlice(begin,end,this.size)){return this}var resolvedBegin=resolveBegin(begin,this.size);var resolvedEnd=resolveEnd(end,this.size);if(resolvedEnd!==this.size){return IndexedCollection.prototype.slice.call(this,begin,end)}var newSize=this.size-resolvedBegin;var head=this._head;while(resolvedBegin--){head=head.next}if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.__ensureOwner=function(ownerID){if(ownerID===this.__ownerID){return this}if(!ownerID){this.__ownerID=ownerID;this.__altered=false;return this}return makeStack(this.size,this._head,ownerID,this.__hash)};Stack.prototype.__iterate=function(fn,reverse){if(reverse){return this.reverse().__iterate(fn)}var iterations=0;var node=this._head;while(node){if(fn(node.value,iterations++,this)===false){break}node=node.next}return iterations};Stack.prototype.__iterator=function(type,reverse){if(reverse){return this.reverse().__iterator(type)}var iterations=0;var node=this._head;return new src_Iterator__Iterator(function(){if(node){var value=node.value;node=node.next;return iteratorValue(type,iterations++,value)}return iteratorDone()})};function isStack(maybeStack){return!!(maybeStack&&maybeStack[IS_STACK_SENTINEL])}Stack.isStack=isStack;var IS_STACK_SENTINEL="@@__IMMUTABLE_STACK__@@";var StackPrototype=Stack.prototype;StackPrototype[IS_STACK_SENTINEL]=true;StackPrototype.withMutations=MapPrototype.withMutations;StackPrototype.asMutable=MapPrototype.asMutable;StackPrototype.asImmutable=MapPrototype.asImmutable;StackPrototype.wasAltered=MapPrototype.wasAltered;function makeStack(size,head,ownerID,hash){var map=Object.create(StackPrototype);map.size=size;map._head=head;map.__ownerID=ownerID;map.__hash=hash;map.__altered=false;return map}var EMPTY_STACK;function emptyStack(){return EMPTY_STACK||(EMPTY_STACK=makeStack(0))}createClass(src_Set__Set,SetCollection);function src_Set__Set(value){return value===null||value===undefined?emptySet():isSet(value)?value:emptySet().withMutations(function(set){var iter=SetIterable(value);assertNotInfinite(iter.size);iter.forEach(function(v){return set.add(v)})})}src_Set__Set.of=function(){return this(arguments)};src_Set__Set.fromKeys=function(value){return this(KeyedIterable(value).keySeq())};src_Set__Set.prototype.toString=function(){return this.__toString("Set {","}")};src_Set__Set.prototype.has=function(value){return this._map.has(value)};src_Set__Set.prototype.add=function(value){return updateSet(this,this._map.set(value,true))};src_Set__Set.prototype.remove=function(value){return updateSet(this,this._map.remove(value))};src_Set__Set.prototype.clear=function(){return updateSet(this,this._map.clear())};src_Set__Set.prototype.union=function(){var iters=SLICE$0.call(arguments,0);iters=iters.filter(function(x){return x.size!==0});if(iters.length===0){return this}if(this.size===0&&!this.__ownerID&&iters.length===1){return this.constructor(iters[0])}return this.withMutations(function(set){for(var ii=0;ii1?" by "+this._step:"")+" ]"};Range.prototype.get=function(index,notSetValue){return this.has(index)?this._start+wrapIndex(this,index)*this._step:notSetValue};Range.prototype.includes=function(searchValue){var possibleIndex=(searchValue-this._start)/this._step;return possibleIndex>=0&&possibleIndex=0&&indexmaxIndex?iteratorDone():iteratorValue(type,ii++,v)})};Range.prototype.equals=function(other){return other instanceof Range?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual(this,other)};var EMPTY_RANGE;createClass(Repeat,IndexedSeq);function Repeat(value,times){if(!(this instanceof Repeat)){return new Repeat(value,times)}this._value=value;this.size=times===undefined?Infinity:Math.max(0,times);if(this.size===0){if(EMPTY_REPEAT){return EMPTY_REPEAT}EMPTY_REPEAT=this}}Repeat.prototype.toString=function(){if(this.size===0){return"Repeat []"}return"Repeat [ "+this._value+" "+this.size+" times ]"};Repeat.prototype.get=function(index,notSetValue){return this.has(index)?this._value:notSetValue};Repeat.prototype.includes=function(searchValue){return is(this._value,searchValue)};Repeat.prototype.slice=function(begin,end){var size=this.size;return wholeSlice(begin,end,size)?this:new Repeat(this._value,resolveEnd(end,size)-resolveBegin(begin,size))};Repeat.prototype.reverse=function(){return this};Repeat.prototype.indexOf=function(searchValue){if(is(this._value,searchValue)){return 0}return-1};Repeat.prototype.lastIndexOf=function(searchValue){if(is(this._value,searchValue)){return this.size}return-1};Repeat.prototype.__iterate=function(fn,reverse){for(var ii=0;iithis.size)?notSetValue:this.find(function(_,key){return key===index},undefined,notSetValue)},has:function(index){index=wrapIndex(this,index);return index>=0&&(this.size!==undefined?this.size===Infinity||indexb?-1:0}function hashIterable(iterable){if(iterable.size===Infinity){return 0}var ordered=isOrdered(iterable);var keyed=isKeyed(iterable);var h=ordered?1:0;var size=iterable.__iterate(keyed?ordered?function(v,k){h=31*h+hashMerge(hash(v),hash(k))|0}:function(v,k){h=h+hashMerge(hash(v),hash(k))|0}:ordered?function(v){h=31*h+hash(v)|0}:function(v){h=h+hash(v)|0});return murmurHashOfSize(size,h)}function murmurHashOfSize(size,h){h=src_Math__imul(h,3432918353);h=src_Math__imul(h<<15|h>>>-15,461845907);h=src_Math__imul(h<<13|h>>>-13,5);h=(h+3864292196|0)^size;h=src_Math__imul(h^h>>>16,2246822507);h=src_Math__imul(h^h>>>13,3266489909);h=smi(h^h>>>16);return h}function hashMerge(a,b){return a^b+2654435769+(a<<6)+(a>>2)|0}var Immutable={Iterable:Iterable,Seq:Seq,Collection:Collection,Map:src_Map__Map,OrderedMap:OrderedMap,List:List,Stack:Stack,Set:src_Set__Set,OrderedSet:OrderedSet,Record:Record,Range:Range,Repeat:Repeat,is:is,fromJS:fromJS};return Immutable})},{}],119:[function(require,module,exports){module.exports={name:"rxmarbles",version:"1.4.1",author:"Andre Staltz",repository:{type:"git",url:"git@github.com:staltz/rxmarbles.git"},license:"BSD 3-Clause","private":true,main:"js/app.js",dependencies:{"@cycle/core":"1.0.x","@cycle/dom":"3.1.x",immutable:"^3.7.2",rxtween:"0.3.3"},devDependencies:{browserify:"10.1.3",less:"^2.5.0","uglify-js":"~2.4.21",watchify:"~3.2.1",babel:"^5.2.7"},scripts:{preinstall:"rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src",postinstall:"ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json",less:"lessc styles/main.less dist/css/main.css",babel:"mkdir -p ignore/es5src && babel src --out-dir ignore/es5src",browserify:"browserify -e ignore/es5src/app.js --outfile dist/js/app.js","browserify-element":"browserify -e ignore/es5src/element.js --outfile dist/js/element.js",build:"npm run less && npm run babel && npm run browserify","build-production":"npm run less && npm run babel && npm run browserify && npm run uglify","build-element":"npm run less && npm run babel && npm run browserify-element","build-element-production":"npm run less && npm run babel && npm run browserify-element && npm run uglify-element",uglify:"uglifyjs dist/js/app.js -o dist/js/app.js","uglify-element":"uglifyjs dist/js/element.js -o dist/js/element.js","update-gh-pages":"git checkout gh-pages && git merge --no-ff -X theirs master && git push origin gh-pages && git checkout master",release:"npm run release-patch","release-patch":"git checkout master && npm version patch && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages","release-minor":"git checkout master && npm version minor && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages","release-major":"git checkout master && npm version major && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages"}}},{}],120:[function(require,module,exports){arguments[4][2][0].apply(exports,arguments)},{_process:117,dup:2}],121:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");var packageJson=require("package");var RxPackageJson=require("@cycle/core/node_modules/rx/package.json");var DEFAULT_EXAMPLE="merge";module.exports=function appModel(){var route$=_cycleCore.Rx.Observable.fromEvent(window,"hashchange").map(function(hashEvent){return hashEvent.target.location.hash.replace("#","")}).startWith(window.location.hash.replace("#","")||DEFAULT_EXAMPLE);var appVersion$=_cycleCore.Rx.Observable.just(packageJson.version);var rxVersion$=_cycleCore.Rx.Observable.just(RxPackageJson.version);return _cycleCore.Rx.Observable.combineLatest(route$,appVersion$,rxVersion$,function(route,appVersion,rxVersion){return{route:route,appVersion:appVersion,rxVersion:rxVersion}})}},{"@cycle/core":1,"@cycle/core/node_modules/rx/package.json":3,"package":119}],122:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleDom=require("@cycle/dom");var _rxmarblesStylesColors=require("rxmarbles/styles/colors");var _rxmarblesStylesColors2=_interopRequireDefault(_rxmarblesStylesColors);var _rxmarblesStylesDimens=require("rxmarbles/styles/dimens");var _rxmarblesStylesDimens2=_interopRequireDefault(_rxmarblesStylesDimens);var _rxmarblesStylesFonts=require("rxmarbles/styles/fonts");var _rxmarblesStylesFonts2=_interopRequireDefault(_rxmarblesStylesFonts);var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");var rxmarblesGithubUrl="https://github.com/staltz/rxmarbles";var rxjsGithubUrl="https://github.com/Reactive-Extensions/RxJS";var pageRowWidth="1060px";var sandboxWidth="820px";var pageRowStyle={position:"relative",width:pageRowWidth,margin:"0 auto"};var pageRowChildStyle={display:"inline-block"};var pageRowFirstChildStyle=(0,_rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle,{width:"calc("+pageRowWidth+" - "+sandboxWidth+" - "+_rxmarblesStylesDimens2["default"].spaceMedium+")"});var pageRowLastChildStyle=(0,_rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle,{width:sandboxWidth});function renderHeader(){return(0,_cycleDom.h)("div",{style:pageRowStyle},[(0,_cycleDom.h)("h1",{style:(0,_rxmarblesStylesUtils.mergeStyles)({fontFamily:_rxmarblesStylesFonts2["default"].fontSpecial,color:_rxmarblesStylesColors2["default"].greyDark},pageRowFirstChildStyle)},"RxMarbles"),(0,_cycleDom.h)("h3",{style:(0,_rxmarblesStylesUtils.mergeStyles)({color:_rxmarblesStylesColors2["default"].greyDark},pageRowLastChildStyle)},"Interactive diagrams of Rx Observables")])}function renderContent(route){var style=(0,_rxmarblesStylesUtils.mergeStyles)(pageRowStyle,{marginTop:_rxmarblesStylesDimens2["default"].spaceSmall});return(0,_cycleDom.h)("div",{style:style},[(0,_cycleDom.h)("div",{style:pageRowFirstChildStyle},(0,_cycleDom.h)("x-operators-menu",{key:"operatorsMenu"})),(0,_cycleDom.h)("div",{style:(0,_rxmarblesStylesUtils.mergeStyles)({position:"absolute",top:"0"},pageRowLastChildStyle)},(0,_cycleDom.h)("x-sandbox",{key:"sandbox",route:route,width:"820px"}))])}function renderFooter(appVersion,rxVersion){var style={position:"fixed",bottom:"2px",right:_rxmarblesStylesDimens2["default"].spaceMedium,color:_rxmarblesStylesColors2["default"].greyDark};return(0,_cycleDom.h)("section",{style:style},[(0,_cycleDom.h)("a",{href:rxmarblesGithubUrl+"/releases/tag/v"+appVersion},"v"+appVersion)," built on ",(0,_cycleDom.h)("a",{href:rxjsGithubUrl+"/tree/v"+rxVersion},"RxJS v"+rxVersion)," by ",(0,_cycleDom.h)("a",{href:"https://twitter.com/andrestaltz"},"@andrestaltz")])}module.exports=function appView(state$){var wrapperStyle={paddingLeft:_rxmarblesStylesDimens2["default"].spaceSmall,paddingRight:"calc("+_rxmarblesStylesDimens2["default"].spaceHuge+" + "+_rxmarblesStylesDimens2["default"].spaceSmall+")"};return state$.map(function(_ref){var route=_ref.route;var appVersion=_ref.appVersion;var rxVersion=_ref.rxVersion;return(0,_cycleDom.h)("div",{style:wrapperStyle},[(0,_rxmarblesStylesUtils.renderSvgDropshadow)(),renderHeader(),renderContent(route),renderFooter(appVersion,rxVersion)])})}},{"@cycle/dom":6,"rxmarbles/styles/colors":142,"rxmarbles/styles/dimens":143,"rxmarbles/styles/fonts":144,"rxmarbles/styles/utils":145}],123:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");var _cycleDom=require("@cycle/dom");var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");function createContainerStyle(inputStyle){return{display:"inline-block",position:"relative",width:"calc(8 * "+inputStyle.thickness+")",height:inputStyle.height,margin:"0 calc(-4 * "+inputStyle.thickness+")"}}function createInnerStyle(inputStyle){return{width:inputStyle.thickness,height:"50%",marginLeft:"calc(3.5 * "+inputStyle.thickness+")",marginTop:"calc("+inputStyle.height+" / 4.0)",backgroundColor:inputStyle.color}}function render(time,isDraggable,isTall,inputStyle,isHighlighted){var draggableContainerStyle={cursor:"ew-resize"};var innerTallStyle={height:"100%",marginTop:0};var containerStyle=createContainerStyle(inputStyle);var innerStyle=createInnerStyle(inputStyle);return(0,_cycleDom.h)("div.completionRoot",{style:(0,_rxmarblesStylesUtils.mergeStyles)({left:time+"%"},containerStyle,isDraggable?draggableContainerStyle:{})},[(0,_cycleDom.h)("div.completionInner",{style:(0,_rxmarblesStylesUtils.mergeStyles)(innerStyle,isDraggable&&isHighlighted?_rxmarblesStylesUtils.elevation1Style:null,isTall?innerTallStyle:null)})])}function diagramCompletionComponent(_ref){var DOM=_ref.DOM;var props=_ref.props;var startHighlight$=DOM.get(".completionRoot","mouseenter");var stopHighlight$=DOM.get(".completionRoot","mouseleave");var time$=props.get("time").startWith(100);var isDraggable$=props.get("isDraggable").startWith(false);var isTall$=props.get("isTall").startWith(false);var style$=props.get("style").startWith({thickness:"2px",height:"10px",color:"black"});var isHighlighted$=_cycleCore.Rx.Observable.merge(startHighlight$.map(function(){return true}),stopHighlight$.map(function(){return false})).startWith(false);var vtree$=_cycleCore.Rx.Observable.combineLatest(time$,isDraggable$,isTall$,style$,isHighlighted$,render);return{DOM:vtree$}}module.exports=diagramCompletionComponent},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/utils":145}],124:[function(require,module,exports){"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break}}catch(err){_d=true;_e=err}finally{try{if(!_n&&_i["return"])_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr)){return arr}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i)}else{throw new TypeError("Invalid attempt to destructure non-iterable instance")}}}();function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _immutable=require("immutable");var _immutable2=_interopRequireDefault(_immutable);var mouseMove$=_cycleCore.Rx.Observable.fromEvent(document,"mousemove");var mouseUp$=_cycleCore.Rx.Observable.fromEvent(document,"mouseup");function getPxToPercentageRatio(element){var pxToPercentage=undefined;try{if(element&&element.parentElement&&element.parentElement.clientWidth){pxToPercentage=100/element.parentElement.clientWidth}else{throw new Error("Invalid marble parent or parent width.")}}catch(err){console.warn(err);pxToPercentage=.15}return pxToPercentage}function makeDeltaTime$(mouseDown$,resultFn){return mouseDown$.map(function(downevent){var target=downevent.currentTarget;var pxToPercentage=getPxToPercentageRatio(target);return mouseMove$.takeUntil(mouseUp$).pairwise().map(function(_ref){var _ref2=_slicedToArray(_ref,2);var ev1=_ref2[0];var ev2=_ref2[1];var dx=ev2.pageX-ev1.pageX;var deltaTime=dx*pxToPercentage;if(!!resultFn){return resultFn(deltaTime,target)}else{return deltaTime}}).filter(function(x){return x!==0})}).concatAll()}function diagramIntent(DOM){var marbleMouseDown$=DOM.get(".diagramMarble","mousedown");var completionMouseDown$=DOM.get(".diagramCompletion","mousedown");return{changeMarbleTime$:makeDeltaTime$(marbleMouseDown$,function(deltaTime,target){return _immutable2["default"].Map({deltaTime:deltaTime,id:target.attributes["data-marble-id"].value})}),changeEndTime$:makeDeltaTime$(completionMouseDown$)}}module.exports=diagramIntent},{"@cycle/core":1,immutable:118}],125:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");function findLargestMarbleTime(diagramData){return diagramData.get("notifications").max(function(notifA,notifB){if(notifA.get("time")notifB.get("time")){return 1}return 0}).get("time")}function applyChangeMarbleTime(diagramData,marbleDelta){return diagramData.set("notifications",diagramData.get("notifications").map(function(notif){if(String(notif.get("id"))===String(marbleDelta.get("id"))){var newTime=notif.get("time")+marbleDelta.get("deltaTime");return notif.set("time",newTime)}else{return notif}}))}function applyChangeEndTime(diagramData,endDelta){return diagramData.set("end",diagramData.get("end")+endDelta)}function applyMarbleDataConstraints(marbleData){var newTime=marbleData.get("time");newTime=Math.round(newTime);newTime=Math.min(newTime,100);newTime=Math.max(0,newTime);return marbleData.set("time",newTime)}function applyEndTimeConstraint(diagramData){var largestMarbleTime=findLargestMarbleTime(diagramData);var newEndTime=diagramData.get("end");newEndTime=Math.max(newEndTime,largestMarbleTime);newEndTime=Math.round(newEndTime);newEndTime=Math.min(newEndTime,100);newEndTime=Math.max(0,newEndTime);return diagramData.set("end",newEndTime)}function applyDiagramDataConstraints(diagramData){var newDiagramData=diagramData.set("notifications",diagramData.get("notifications").map(applyMarbleDataConstraints));newDiagramData=applyEndTimeConstraint(newDiagramData);return newDiagramData}function makeNewDiagramData$(data$,changeMarbleTime$,changeEndTime$,interactive$){var mod$=_cycleCore.Rx.Observable.merge(changeMarbleTime$.map(function(x){return function(data){return applyChangeMarbleTime(data,x)}}),changeEndTime$.map(function(x){return function(data){return applyChangeEndTime(data,x)}})).pausable(interactive$);return data$.flatMapLatest(function(data){return mod$.scan(data,function(acc,mod){return mod(acc)})}).map(applyDiagramDataConstraints)}function diagramModel(props,intent){var data$=props.get("data").distinctUntilChanged().shareReplay(1);return{data$:data$,newData$:makeNewDiagramData$(data$,intent.changeMarbleTime$,intent.changeEndTime$,props.get("interactive")),isInteractive$:props.get("interactive").startWith(false)}}module.exports=diagramModel},{"@cycle/core":1}],126:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _cycleDom=require("@cycle/dom");var _rxmarblesStylesColors=require("rxmarbles/styles/colors");var _rxmarblesStylesColors2=_interopRequireDefault(_rxmarblesStylesColors);var _rxmarblesStylesDimens=require("rxmarbles/styles/dimens");var _rxmarblesStylesDimens2=_interopRequireDefault(_rxmarblesStylesDimens);var _rxmarblesStylesFonts=require("rxmarbles/styles/fonts");var _rxmarblesStylesFonts2=_interopRequireDefault(_rxmarblesStylesFonts);var _rxtween=require("rxtween");var _rxtween2=_interopRequireDefault(_rxtween);var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");var MARBLE_WIDTH=5;var diagramSidePadding=_rxmarblesStylesDimens2["default"].spaceMedium;var diagramVerticalMargin=_rxmarblesStylesDimens2["default"].spaceLarge;var diagramArrowThickness="2px";var diagramArrowSidePadding=_rxmarblesStylesDimens2["default"].spaceLarge;var diagramArrowHeadSize="8px";var diagramArrowColor=_rxmarblesStylesColors2["default"].black;var diagramMarbleSize=_rxmarblesStylesDimens2["default"].spaceLarge;var diagramCompletionHeight="44px";var diagramStyle=(0,_rxmarblesStylesUtils.mergeStyles)({position:"relative",display:"block",width:"100%",height:"calc("+diagramMarbleSize+" + 2 * "+diagramVerticalMargin+")",overflow:"visible",cursor:"default"},_rxmarblesStylesUtils.textUnselectable);var diagramBodyStyle={position:"absolute",left:"calc("+diagramArrowSidePadding+" + "+diagramSidePadding+"\n + ("+diagramMarbleSize+" / 2))",right:"calc("+diagramArrowSidePadding+" + "+diagramSidePadding+"\n + ("+diagramMarbleSize+" / 2))",top:"calc("+diagramVerticalMargin+" + ("+diagramMarbleSize+" / 2))",height:diagramCompletionHeight,marginTop:"calc(0px - ("+diagramCompletionHeight+" / 2))"};function renderMarble(marbleData){var isDraggable=arguments.length<=1||arguments[1]===undefined?false:arguments[1];return(0,_cycleDom.h)("x-marble.diagramMarble",{key:"marble"+marbleData.get("id"),data:marbleData,isDraggable:isDraggable,style:{size:diagramMarbleSize}})}function renderCompletion(diagramData){var isDraggable=arguments.length<=1||arguments[1]===undefined?false:arguments[1];var endTime=diagramData.get("end");var isTall=diagramData.get("notifications").some(function(marbleData){return Math.abs(marbleData.get("time")-diagramData.get("end"))<=MARBLE_WIDTH*.5});return(0,_cycleDom.h)("x-diagram-completion.diagramCompletion",{key:"completion",time:endTime,isDraggable:isDraggable,isTall:isTall,style:{thickness:diagramArrowThickness,color:diagramArrowColor,height:diagramCompletionHeight}})}function renderDiagramArrow(){return(0,_cycleDom.h)("div.diagramArrow",{style:{backgroundColor:diagramArrowColor,height:diagramArrowThickness,position:"absolute",top:"calc("+diagramVerticalMargin+" + ("+diagramMarbleSize+" / 2))",left:diagramSidePadding,right:diagramSidePadding}})}function renderDiagramArrowHead(){return(0,_cycleDom.h)("div.diagramArrowHead",{style:{width:0,height:0,borderTop:diagramArrowHeadSize+" solid transparent",borderBottom:diagramArrowHeadSize+" solid transparent",borderLeft:"calc(2 * "+diagramArrowHeadSize+") solid "+diagramArrowColor,display:"inline-block",right:"calc("+diagramSidePadding+" - 1px)",position:"absolute",top:"calc("+diagramVerticalMargin+" + ("+diagramMarbleSize+" / 2)\n - "+diagramArrowHeadSize+" + ("+diagramArrowThickness+" / 2))"}})}function renderDiagram(data,isInteractive){var marblesVTree=data.get("notifications").map(function(notification){return renderMarble(notification,isInteractive)}).toArray();var completionVTree=renderCompletion(data,isInteractive);return(0,_cycleDom.h)("div",{style:diagramStyle},[renderDiagramArrow(),renderDiagramArrowHead(),(0,_cycleDom.h)("div",{style:diagramBodyStyle},[completionVTree].concat(marblesVTree))])}function sanitizeDiagramItem(x){return Math.max(0,Math.min(100,x))}function interpolate(from,to,x){return from*(1-x)+to*x}function animateData$(data$){var animConf={from:0,to:1,ease:_rxtween2["default"].Power3.easeOut,duration:600};return data$.flatMapLatest(function(data){if(!data.get("isFirst")){return _cycleCore.Rx.Observable.just(data)}else{var _ret=function(){var randomizedNotifs=data.get("notifications").map(function(notif){return notif.update("time",function(time){return time-10+20*Math.random()})});return{v:(0,_rxtween2["default"])(animConf).map(function(x){return data.update("notifications",function(notifications){return notifications.zipWith(function(n1,n2){return n1.update("time",function(t1){var t2=n2.get("time");return interpolate(t2,t1,x)})},randomizedNotifs)})})}}();if(typeof _ret==="object")return _ret.v}})}function diagramView(model){return{vtree$:_cycleCore.Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$),model.isInteractive$,renderDiagram)}}module.exports=diagramView},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":142,"rxmarbles/styles/dimens":143,"rxmarbles/styles/fonts":144,"rxmarbles/styles/utils":145,rxtween:154}],127:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _rxmarblesComponentsDiagramDiagramModel=require("rxmarbles/components/diagram/diagram-model");var _rxmarblesComponentsDiagramDiagramModel2=_interopRequireDefault(_rxmarblesComponentsDiagramDiagramModel);var _rxmarblesComponentsDiagramDiagramView=require("rxmarbles/components/diagram/diagram-view");var _rxmarblesComponentsDiagramDiagramView2=_interopRequireDefault(_rxmarblesComponentsDiagramDiagramView);var _rxmarblesComponentsDiagramDiagramIntent=require("rxmarbles/components/diagram/diagram-intent");var _rxmarblesComponentsDiagramDiagramIntent2=_interopRequireDefault(_rxmarblesComponentsDiagramDiagramIntent);function DiagramComponent(_ref){var DOM=_ref.DOM;var props=_ref.props;var intent=(0,_rxmarblesComponentsDiagramDiagramIntent2["default"])(DOM);var model=(0,_rxmarblesComponentsDiagramDiagramModel2["default"])(props,intent);var view=(0,_rxmarblesComponentsDiagramDiagramView2["default"])(model);return{DOM:view.vtree$,events:{newdata:model.newData$}}}module.exports=DiagramComponent},{"rxmarbles/components/diagram/diagram-intent":124,"rxmarbles/components/diagram/diagram-model":125,"rxmarbles/components/diagram/diagram-view":126}],128:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _cycleDom=require("@cycle/dom");var _rxmarblesStylesColors=require("rxmarbles/styles/colors");var _rxmarblesStylesColors2=_interopRequireDefault(_rxmarblesStylesColors);var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");function createContainerStyle(inputStyle){return{width:inputStyle.size,height:inputStyle.size,position:"relative",display:"inline-block",margin:"calc(0px - ("+inputStyle.size+" / 2))",bottom:"calc((100% - "+inputStyle.size+") / 2)",cursor:"default"}}function renderSvg(data,isDraggable,inputStyle,isHighlighted){var POSSIBLE_COLORS=[_rxmarblesStylesColors2["default"].blue,_rxmarblesStylesColors2["default"].green,_rxmarblesStylesColors2["default"].yellow,_rxmarblesStylesColors2["default"].red];var color=POSSIBLE_COLORS[data.get("id")%POSSIBLE_COLORS.length];return(0,_cycleDom.svg)("svg.marbleShape",{style:{overflow:"visible",width:inputStyle.size,height:inputStyle.size},attributes:{viewBox:"0 0 1 1"}},[(0,_cycleDom.svg)("circle",{style:(0,_rxmarblesStylesUtils.mergeStyles)({stroke:_rxmarblesStylesColors2["default"].black,fill:color},isDraggable&&isHighlighted?_rxmarblesStylesUtils.marbleElevation1Style:{}),attributes:{cx:.5,cy:.5,r:.47,"stroke-width":"0.06px"}})])}function renderInnerContent(data,inputStyle){return(0,_cycleDom.h)("p.marbleContent",{style:(0,_rxmarblesStylesUtils.mergeStyles)({position:"absolute",width:"100%",height:"100%",top:"0",margin:"0",textAlign:"center",lineHeight:inputStyle.size},_rxmarblesStylesUtils.textUnselectable)},""+data.get("content"))}function render(data,isDraggable,inputStyle,isHighlighted){var draggableContainerStyle={cursor:"ew-resize"};return(0,_cycleDom.h)("div.marbleRoot",{style:(0,_rxmarblesStylesUtils.mergeStyles)({left:data.get("time")+"%",zIndex:data.get("time")},createContainerStyle(inputStyle),isDraggable?draggableContainerStyle:null),attributes:{"data-marble-id":data.get("id")}},[renderSvg(data,isDraggable,inputStyle,isHighlighted),renderInnerContent(data,inputStyle)])}function marbleComponent(_ref){var DOM=_ref.DOM;var props=_ref.props;var startHighlight$=DOM.get(".marbleRoot","mouseenter");var stopHighlight$=DOM.get(".marbleRoot","mouseleave");var data$=props.get("data");var isDraggable$=props.get("isDraggable").startWith(false);var style$=props.get("style").startWith({});var isHighlighted$=_cycleCore.Rx.Observable.merge(startHighlight$.map(function(){return true}),stopHighlight$.map(function(){return false})).startWith(false);var vtree$=_cycleCore.Rx.Observable.combineLatest(data$,isDraggable$,style$,isHighlighted$,render);return{DOM:vtree$}}module.exports=marbleComponent},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":142,"rxmarbles/styles/utils":145}],129:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _cycleDom=require("@cycle/dom");var _rxmarblesStylesColors=require("rxmarbles/styles/colors");var _rxmarblesStylesColors2=_interopRequireDefault(_rxmarblesStylesColors);var _rxmarblesStylesDimens=require("rxmarbles/styles/dimens");var _rxmarblesStylesDimens2=_interopRequireDefault(_rxmarblesStylesDimens);var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");function operatorsMenuLink(_ref){var DOM=_ref.DOM;var props=_ref.props;var startHighlight$=DOM.get(".link","mouseenter").map(function(){return 1});var stopHighlight$=DOM.get(".link","mouseleave").map(function(){return 1});var href$=props.get("href");var content$=props.get("content").startWith("");var isHighlighted$=_cycleCore.Rx.Observable.merge(startHighlight$.map(function(){return true}),stopHighlight$.map(function(){return false})).startWith(false);var highlightingArrow=(0,_cycleDom.h)("span",{style:{display:"inline-block",position:"absolute",right:_rxmarblesStylesDimens2["default"].spaceTiny}},"❯");var vtree$=_cycleCore.Rx.Observable.combineLatest(href$,content$,isHighlighted$,function(href,content,isHighlighted){return(0,_cycleDom.h)("a.link",{style:(0,_rxmarblesStylesUtils.mergeStyles)({position:"relative",display:"block",color:_rxmarblesStylesColors2["default"].greyDark},isHighlighted?{color:_rxmarblesStylesColors2["default"].black}:null),href:href},[content,isHighlighted?highlightingArrow:null])});return{DOM:vtree$}}module.exports=operatorsMenuLink},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":142,"rxmarbles/styles/dimens":143,"rxmarbles/styles/utils":145}],130:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _cycleDom=require("@cycle/dom");var _rxmarblesStylesColors=require("rxmarbles/styles/colors");var _rxmarblesStylesColors2=_interopRequireDefault(_rxmarblesStylesColors);var _rxmarblesStylesDimens=require("rxmarbles/styles/dimens");var _rxmarblesStylesDimens2=_interopRequireDefault(_rxmarblesStylesDimens);var _rxmarblesDataExamples=require("rxmarbles/data/examples");var _rxmarblesDataExamples2=_interopRequireDefault(_rxmarblesDataExamples);var _rxmarblesStylesUtils=require("rxmarbles/styles/utils");function organizeExamplesByCategory(examples){var categoryMap={};for(var key in examples){if(!examples.hasOwnProperty(key))continue;var value=examples[key];value.key=key;if(categoryMap.hasOwnProperty(value.category)){categoryMap[value.category].push(value)}else{categoryMap[value.category]=[value]}}return categoryMap}var operatorsMenuCategoryStyle={textTransform:"uppercase",fontSize:"0.7em",color:_rxmarblesStylesColors2["default"].grey,marginTop:_rxmarblesStylesDimens2["default"].spaceMedium};var operatorsMenuItemStyle={color:_rxmarblesStylesColors2["default"].greyDark,fontSize:"1rem",lineHeight:"1.6rem"};function renderExampleItem(example){return(0,_cycleDom.h)("li",{style:operatorsMenuItemStyle},(0,_cycleDom.h)("x-operators-menu-link",{key:"operatorsMenuLink"+example.key,href:"#"+example.key,content:example.key}))}function renderExampleItems(examples){var items=[];for(var i=0;iy){return 1}if(x=45?1.3:label.length>=30?1.5:2;var style={fontFamily:_rxmarblesStylesFonts2["default"].fontCode,fontWeight:"400",fontSize:fontSize+"rem"};return(0,_cycleDom.h)("span.operatorLabel",{style:style},label)}function renderOperator(label){var style=(0,_rxmarblesStylesUtils.mergeStyles)({border:"1px solid rgba(0,0,0,0.06)",padding:_rxmarblesStylesDimens2["default"].spaceMedium,textAlign:"center"},_rxmarblesStylesUtils.elevation2Style);return(0,_cycleDom.h)("div.operatorBox",{style:style},[_rxmarblesStylesUtils.elevation2Before,renderOperatorLabel(label),_rxmarblesStylesUtils.elevation2After])}function getSandboxStyle(width){return(0,_rxmarblesStylesUtils.mergeStyles)({background:_rxmarblesStylesColors2["default"].white,width:width,borderRadius:"2px"},_rxmarblesStylesUtils.elevation1Style)}function renderSandbox(inputDiagrams,operatorLabel,outputDiagram,width){return(0,_cycleDom.h)("div.sandboxRoot",{style:getSandboxStyle(width)},[inputDiagrams.get("diagrams").map(function(diagram,index){return(0,_cycleDom.h)("x-diagram.sandboxInputDiagram",{key:"inputDiagram"+index,data:diagram,interactive:true})}),renderOperator(operatorLabel),(0,_cycleDom.h)("x-diagram.sandboxOutputDiagram",{key:"outputDiagram",data:outputDiagram,interactive:false})])}function makeInputDiagrams(example){return _immutable2["default"].Map({diagrams:example.get("inputs").map(_rxmarblesComponentsSandboxSandboxInput.prepareInputDiagram).map(function(diag){return(0,_rxmarblesComponentsSandboxSandboxInput.augmentWithExampleKey)(diag,example.get("key"))})})}function markAsFirstDiagram(diagram){return diagram.set("isFirst",true)}function markAllDiagramsAsFirst(diagramsData){return diagramsData.update("diagrams",function(diagrams){return diagrams.map(markAsFirstDiagram)})}var isTruthy=function isTruthy(x){return!!x};function sandboxComponent(_ref){var DOM=_ref.DOM;var props=_ref.props;var changeInputDiagram$=DOM.get(".sandboxInputDiagram","newdata").map(function(ev){return ev.detail});var width$=props.get("width").startWith("100%");var example$=props.get("route").filter(isTruthy).map(function(key){return _immutable2["default"].Map(_rxmarblesDataExamples2["default"][key]).set("key",key)}).shareReplay(1);var inputDiagrams$=example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1);var newInputDiagrams$=(0,_rxmarblesComponentsSandboxSandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$,inputDiagrams$);var operatorLabel$=example$.map(function(example){return example.get("label")});var firstOutputDiagram$=(0,_rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$,inputDiagrams$).map(markAsFirstDiagram);var newOutputDiagram$=(0,_rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$,newInputDiagrams$);var outputDiagram$=firstOutputDiagram$.merge(newOutputDiagram$);var vtree$=_cycleCore.Rx.Observable.combineLatest(inputDiagrams$,operatorLabel$,outputDiagram$,width$,renderSandbox);return{DOM:vtree$}}module.exports=sandboxComponent},{"@cycle/core":1,"@cycle/dom":6,immutable:118,"rxmarbles/components/sandbox/sandbox-input":131,"rxmarbles/components/sandbox/sandbox-output":132,"rxmarbles/data/examples":138,"rxmarbles/styles/colors":142,"rxmarbles/styles/dimens":143,"rxmarbles/styles/fonts":144,"rxmarbles/styles/utils":145,rxtween:154}],134:[function(require,module,exports){"use strict";function calculateNotificationContentHash(content){var SMALL_PRIME_1=59;var SMALL_PRIME_2=97;var SOME_PRIME_NUMBER=877;if(typeof content==="string"){return content.split("").map(function(x){return x.charCodeAt(0)}).reduce(function(x,y){return x*SMALL_PRIME_1+y*SMALL_PRIME_2})}else if(typeof content==="number"){return parseInt(content)*SOME_PRIME_NUMBER}else if(typeof content==="boolean"){return content?SOME_PRIME_NUMBER:SOME_PRIME_NUMBER*3}}function calculateNotificationHash(marbleData){var SMALL_PRIME=7;var LARGE_PRIME=1046527;var MAX=1e5;var contentHash=calculateNotificationContentHash(marbleData.content);return(marbleData.time+contentHash+SMALL_PRIME)*LARGE_PRIME%MAX}module.exports={calculateNotificationHash:calculateNotificationHash,calculateNotificationContentHash:calculateNotificationContentHash}},{}],135:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");module.exports={every:{label:"every(x => x < 10)",inputs:[[{t:5,d:1},{t:15,d:2},{t:25,d:3},{t:35,d:4},{t:65,d:5},80]],apply:function apply(inputs){return inputs[0].every(function(x){return x.get("content")<10})}},some:{label:"some(x => x > 10)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1}]],apply:function apply(inputs){return inputs[0].some(function(x){return x.get("content")>10})}},includes:{label:"includes(22)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1}]],apply:function apply(inputs){return inputs[0].map(function(x){return x.get("content")}).includes(22)}},sequenceEqual:{label:"sequenceEqual",inputs:[[{t:5,d:1},{t:15,d:2},{t:25,d:3},{t:35,d:4},{t:65,d:5},85],[{t:2,d:1},{t:20,d:2},{t:40,d:3},{t:70,d:4},{t:77,d:5},85]],apply:function apply(inputs){return inputs[0].sequenceEqual(inputs[1],function(x,y){return x.get("content")===y.get("content")})}}}},{"@cycle/core":1}],136:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");module.exports={combineLatest:{label:'combineLatest((x, y) => "" + x + y)',inputs:[[{t:0,d:1},{t:20,d:2},{t:65,d:3},{t:75,d:4},{t:92,d:5}],[{t:10,d:"A"},{t:25,d:"B"},{t:50,d:"C"},{t:57,d:"D"}]],apply:function apply(inputs){return _cycleCore.Rx.Observable.combineLatest(inputs[0],inputs[1],function(x,y){return""+x.get("content")+y.get("content")})}},concat:{label:"concat",inputs:[[{t:0,d:1},{t:15,d:1},{t:50,d:1},57],[{t:0,d:2},{t:8,d:2},12]],apply:function apply(inputs){return _cycleCore.Rx.Observable.concat(inputs)}},merge:{label:"merge",inputs:[[{t:0,d:20},{t:15,d:40},{t:30,d:60},{t:45,d:80},{t:60,d:100}],[{t:37,d:1},{t:68,d:1}]],apply:function apply(inputs){return _cycleCore.Rx.Observable.merge(inputs)}},sample:{label:"sample",inputs:[[{t:0,d:1},{t:20,d:2},{t:40,d:3},{t:60,d:4},{t:80,d:5}],[{t:10,d:"A"},{t:25,d:"B"},{t:33,d:"C"},{t:70,d:"D"},90]],apply:function apply(inputs){return inputs[0].sample(inputs[1])}},startWith:{label:"startWith(1)",inputs:[[{t:30,d:2},{t:40,d:3}]],apply:function apply(inputs,scheduler){return inputs[0].startWith(scheduler,1)}},withLatestFrom:{label:'withLatestFrom((x, y) => "" + x + y)',inputs:[[{t:0,d:1},{t:20,d:2},{t:65,d:3},{t:75,d:4},{t:92,d:5}],[{t:10,d:"A"},{t:25,d:"B"},{t:50,d:"C"},{t:57,d:"D"}]],apply:function apply(inputs){return inputs[0].withLatestFrom(inputs[1],function(x,y){return""+x.get("content")+y.get("content")})}},zip:{label:"zip",inputs:[[{t:0,d:1},{t:20,d:2},{t:65,d:3},{t:75,d:4},{t:92,d:5}],[{t:10,d:"A"},{t:25,d:"B"},{t:50,d:"C"},{t:57,d:"D"}]],apply:function apply(inputs){return _cycleCore.Rx.Observable.zip(inputs[0],inputs[1],function(x,y){return""+x.get("content")+y.get("content")})}}}},{"@cycle/core":1}],137:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");module.exports={amb:{label:"amb",inputs:[[{t:10,d:20},{t:20,d:40},{t:30,d:60}],[{t:5,d:1},{t:15,d:2},{t:25,d:3}],[{t:20,d:0},{t:32,d:0},{t:44,d:0}]],apply:function apply(inputs){return _cycleCore.Rx.Observable.amb(inputs)}}}},{"@cycle/core":1}],138:[function(require,module,exports){"use strict";var transformExamples=require("rxmarbles/data/transform-examples");var combineExamples=require("rxmarbles/data/combine-examples");var filterExamples=require("rxmarbles/data/filter-examples");var mathExamples=require("rxmarbles/data/math-examples");var booleanExamples=require("rxmarbles/data/boolean-examples");var conditionalExamples=require("rxmarbles/data/conditional-examples");function merge(){var args=1<=arguments.length?Array.prototype.slice.call(arguments):[];var result={};for(var i=0;i x > 10)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1}]],apply:function apply(inputs){return inputs[0].filter(function(x){return x.get("content")>10})}},find:{label:"find(x => x > 10)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1}]],apply:function apply(inputs,scheduler){return inputs[0].find(function(x){return x.get("content")>10})}},first:{label:"first",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4},85]],apply:function apply(inputs){return inputs[0].first()}},last:{label:"last",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4},85]],apply:function apply(inputs){return inputs[0].last()}},pausable:{label:"pausable",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:3},{t:30,d:4},{t:40,d:5},{t:50,d:6},{t:60,d:7},{t:70,d:8},{t:80,d:9}],[{t:15,d:true},{t:35,d:false},{t:55,d:true}]],apply:function apply(inputs){inputs[0].subscribe(function(){return 0});var subject=new _cycleCore.Rx.Subject;inputs[1].subscribe(function(x){return subject.onNext(x.get("content"))});return inputs[0].pausable(subject)}},pausableBuffered:{label:"pausableBuffered",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:3},{t:30,d:4},{t:40,d:5},{t:50,d:6},{t:60,d:7},{t:70,d:8},{t:80,d:9}],[{t:15,d:true},{t:35,d:false},{t:55,d:true}]],apply:function apply(inputs){inputs[0].subscribe(function(){return 0});var subject=new _cycleCore.Rx.Subject;inputs[1].subscribe(function(x){return subject.onNext(x.get("content"))});return inputs[0].pausableBuffered(subject)}},skip:{label:"skip(2)",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4}]],apply:function apply(inputs){return inputs[0].skip(2)}},skipLast:{label:"skipLast(2)",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4}]],apply:function apply(inputs){return inputs[0].skipLast(2)}},skipUntil:{label:"skipUntil",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:3},{t:30,d:4},{t:40,d:5},{t:50,d:6},{t:60,d:7},{t:70,d:8},{t:80,d:9}],[{t:45,d:0},{t:73,d:0}]],apply:function apply(inputs){return inputs[0].skipUntil(inputs[1])}},take:{label:"take(2)",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4},85]],apply:function apply(inputs,scheduler){return inputs[0].take(2,scheduler)}},takeLast:{label:"takeLast(1)",inputs:[[{t:30,d:1},{t:40,d:2},{t:65,d:3},{t:75,d:4},85]],apply:function apply(inputs){return inputs[0].takeLast(1)}},takeUntil:{label:"takeUntil",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:3},{t:30,d:4},{t:40,d:5},{t:50,d:6},{t:60,d:7},{t:70,d:8},{t:80,d:9}],[{t:45,d:0},{t:73,d:0}]],apply:function apply(inputs){return inputs[0].takeUntil(inputs[1])}}}},{"@cycle/core":1}],140:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");module.exports={average:{label:"average",inputs:[[{t:5,d:1},{t:15,d:2},{t:30,d:2},{t:50,d:2},{t:65,d:5},80]],apply:function apply(inputs){return inputs[0].average(function(x){return x.get("content")})}},count:{label:"count(x => x > 10)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1},80]],apply:function apply(inputs){return inputs[0].count(function(x){return x.get("content")>10})}},max:{label:"max",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1},80]],apply:function apply(inputs){return inputs[0].max(function(x,y){if(x.get("content")>y.get("content")){return 1}if(x.get("content")y.get("content")){return 1}if(x.get("content") x + y)",inputs:[[{t:5,d:1},{t:15,d:2},{t:25,d:3},{t:35,d:4},{t:65,d:5},80]],apply:function apply(inputs){return inputs[0].reduce(function(x,y){return y.set("content",x.get("content")+y.get("content")).set("id",x.get("id")+y.get("id"))})}},sum:{label:"sum",inputs:[[{t:5,d:1},{t:15,d:2},{t:25,d:3},{t:35,d:4},{t:65,d:5},80]],apply:function apply(inputs){return inputs[0].sum(function(x){return x.get("content")})}}}},{"@cycle/core":1}],141:[function(require,module,exports){"use strict";var _cycleCore=require("@cycle/core");module.exports={delay:{label:"delay",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:1}]],apply:function apply(inputs,scheduler){return inputs[0].delay(20,scheduler)}},delayWithSelector:{label:"delayWithSelector(x => Rx.Observable.timer(20 * x))",inputs:[[{t:0,d:1},{t:10,d:2},{t:20,d:1}]],apply:function apply(inputs,scheduler){return inputs[0].delayWithSelector(function(x){return _cycleCore.Rx.Observable.timer(Number(x.get("content"))*20,1e3,scheduler)})}},findIndex:{label:"findIndex(x => x > 10)",inputs:[[{t:5,d:2},{t:15,d:30},{t:25,d:22},{t:35,d:5},{t:45,d:60},{t:55,d:1}]],apply:function apply(inputs,scheduler){return inputs[0].findIndex(function(x){return x.get("content")>10})}},map:{label:"map(x => 10 * x)",inputs:[[{t:10,d:1},{t:20,d:2},{t:50,d:3}]],apply:function apply(inputs){return inputs[0].map(function(x){return x.set("content",x.get("content")*10)})}},scan:{label:"scan((x, y) => x + y)",inputs:[[{t:5,d:1},{t:15,d:2},{t:25,d:3},{t:35,d:4},{t:65,d:5}]],apply:function apply(inputs){return inputs[0].scan(function(x,y){return y.set("content",x.get("content")+y.get("content")).set("id",x.get("id")+y.get("id"))})}},debounce:{label:"debounce",inputs:[[{t:0,d:1},{t:26,d:2},{t:34,d:3},{t:40,d:4},{t:45,d:5},{t:79,d:6}]],apply:function apply(inputs,scheduler){return inputs[0].debounce(10,scheduler)}},debounceWithSelector:{label:"debounceWithSelector(x => Rx.Observable.timer(10 * x))",inputs:[[{t:0,d:1},{t:26,d:2},{t:34,d:1},{t:40,d:1},{t:45,d:2},{t:79,d:1}]],apply:function apply(inputs,scheduler){return inputs[0].debounceWithSelector(function(x){return _cycleCore.Rx.Observable.timer(Number(x.get("content"))*10,1e3,scheduler)})}}}},{"@cycle/core":1}],142:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]={white:"#FFFFFF",almostWhite:"#ECECEC",greyLight:"#D4D4D4",grey:"#A7A7A7",greyDark:"#7C7C7C",black:"#323232",blue:"#3EA1CB",yellow:"#FFCB46",red:"#FF6946",green:"#82D736"};module.exports=exports["default"]},{}],143:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]={spaceTiny:"5px",spaceSmall:"10px",spaceMedium:"22px",spaceLarge:"32px",spaceHuge:"42px",animationDurationQuick:"100ms",animationDurationNormal:"200ms",animationDurationSlow:"400ms"};module.exports=exports["default"]},{}],144:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]={fontBase:"'Source Sans Pro', sans-serif",fontSpecial:"'Signika', Helvetica, serif",fontCode:"'Source Code Pro', monospace"};module.exports=exports["default"]},{}],145:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _immutable=require("immutable");var _immutable2=_interopRequireDefault(_immutable);var _cycleDom=require("@cycle/dom");var isTruthy=function isTruthy(x){return!!x};function mergeStyles(){for(var _len=arguments.length,styleObjects=Array(_len),_key=0;_key<_len;_key++){styleObjects[_key]=arguments[_key]}return styleObjects.filter(isTruthy).reduce(function(styleA,styleB){var mapA=_immutable2["default"].Map(styleA);var mapB=_immutable2["default"].Map(styleB);return mapA.merge(mapB).toObject()},{})}var DROPSHADOW_FILTER_ID="dropshadow";function renderSvgDropshadow(){return(0,_cycleDom.svg)("svg",{attributes:{height:"0"}},[(0,_cycleDom.svg)("filter#"+DROPSHADOW_FILTER_ID,{attributes:{height:"130%"}},[(0,_cycleDom.svg)("feGaussianBlur",{attributes:{"in":"SourceAlpha",stdDeviation:"0.05"}}),(0,_cycleDom.svg)("feOffset",{attributes:{dx:"0",dy:"0.05",result:"offsetblur"}}),(0,_cycleDom.svg)("feFlood",{attributes:{"flood-color":"rgba(0,0,0,0.4)"}}),(0,_cycleDom.svg)("feComposite",{attributes:{in2:"offsetblur",operator:"in"}}),(0,_cycleDom.svg)("feMerge",[(0,_cycleDom.svg)("feMergeNode"),(0,_cycleDom.svg)("feMergeNode",{attributes:{"in":"SourceGraphic"}})])])])}var marbleElevation1Style={filter:"url(#"+DROPSHADOW_FILTER_ID+")"};var elevation1Style={"-webkit-box-shadow":"0px 1px 2px 1px rgba(0,0,0,0.17)","-moz-box-shadow":"0px 1px 2px 1px rgba(0,0,0,0.17)","box-shadow":"0px 1px 2px 1px rgba(0,0,0,0.17)"};var elevation2Style={position:"relative"};function getElevationPseudoElementStyle(dy,blur,opacity){return{display:"block",position:"absolute",left:"0",top:"0",right:"0",bottom:"0","-webkit-box-shadow":"0 "+dy+" "+blur+" 0 rgba(0,0,0,"+opacity+")","-moz-box-shadow":"0 "+dy+" "+blur+" 0 rgba(0,0,0,"+opacity+")","box-shadow":"0 "+dy+" "+blur+" 0 rgba(0,0,0,"+opacity+")"}}var elevation2Before=(0,_cycleDom.h)("div",{style:getElevationPseudoElementStyle("2px","10px","0.17")},"");var elevation2After=(0,_cycleDom.h)("div",{style:getElevationPseudoElementStyle("2px","5px","0.26")},"");var elevation3Before=(0,_cycleDom.h)("div",{style:getElevationPseudoElementStyle("6px","20px","0.19")},"");var elevation3After=(0,_cycleDom.h)("div",{style:getElevationPseudoElementStyle("6px","17px","0.2")},"");var textUnselectable={"-webkit-user-select":"none","-khtml-user-select":"none","-moz-user-select":"none","-o-user-select":"none","user-select":"none"};exports["default"]={mergeStyles:mergeStyles,elevation1Style:elevation1Style,elevation2Style:elevation2Style,elevation2Before:elevation2Before,elevation2After:elevation2After,elevation3Before:elevation3Before,elevation3After:elevation3After,marbleElevation1Style:marbleElevation1Style,renderSvgDropshadow:renderSvgDropshadow,textUnselectable:textUnselectable};module.exports=exports["default"]},{"@cycle/dom":6,immutable:118}],146:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var OVERSHOOT=1.70158;exports["default"]={EasingBack:createEasing(function(x){return x*x*((OVERSHOOT+1)*x-OVERSHOOT)})};module.exports=exports["default"]},{"./ease-common":149}],147:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var PARAM1=7.5625;var PARAM2=2.75;function easeOutFn(x){var z=x;if(z<1/PARAM2){return PARAM1*z*z}else if(z<2/PARAM2){return PARAM1*(z-=1.5/PARAM2)*z+.75}else if(z<2.5/PARAM2){return PARAM1*(z-=2.25/PARAM2)*z+.9375}else{return PARAM1*(z-=2.625/PARAM2)*z+.984375}}exports["default"]={EasingBounce:createEasing(function(x){return 1-easeOutFn(1-x)})};module.exports=exports["default"]},{"./ease-common":149}],148:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;exports["default"]={EasingCirc:createEasing(function(x){return-(Math.sqrt(1-x*x)-1)})};module.exports=exports["default"]},{"./ease-common":149}],149:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";function interpolate(y,from,to){return from*(1-y)+to*y}function flip(fn){return function(x){return 1-fn(1-x)}}exports["default"]={interpolate:interpolate,flip:flip,createEasing:function createEasing(fn){var fnFlipped=flip(fn);return{easeIn:function easeIn(x,from,to){return interpolate(fn(x),from,to)},easeOut:function easeOut(x,from,to){return interpolate(fnFlipped(x),from,to)},easeInOut:function easeInOut(x,from,to){var y=x<.5?fn(2*x)*.5:.5+fnFlipped(2*(x-.5))*.5;return interpolate(y,from,to)}}}};module.exports=exports["default"]},{}],150:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var PERIOD=.3;var OVERSHOOT=PERIOD/4;var AMPLITUDE=1;function elasticIn(x){var z=x;if(z<=0){return 0}else if(z>=1){return 1}else{z-=1;return-(AMPLITUDE*Math.pow(2,10*z))*Math.sin((z-OVERSHOOT)*(2*Math.PI)/PERIOD)}}exports["default"]={EasingElastic:createEasing(elasticIn)};module.exports=exports["default"]},{"./ease-common":149}],151:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var EXP_WEIGHT=6;var EXP_MAX=Math.exp(EXP_WEIGHT)-1;function expFn(x){return(Math.exp(x*EXP_WEIGHT)-1)/EXP_MAX}var EasingExponential=createEasing(expFn);exports["default"]={EasingExponential:EasingExponential};module.exports=exports["default"]},{"./ease-common":149}],152:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var EasingPower2=createEasing(function(x){return x*x});var EasingPower3=createEasing(function(x){return x*x*x});var EasingPower4=createEasing(function(x){var xx=x*x;return xx*xx});exports["default"]={EasingPower2:EasingPower2,EasingPower3:EasingPower3,EasingPower4:EasingPower4};module.exports=exports["default"]},{"./ease-common":149}],153:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var _require=require("./ease-common");var createEasing=_require.createEasing;var HALF_PI=Math.PI*.5;exports["default"]={EasingSine:createEasing(function(x){return 1-Math.cos(x*HALF_PI)})};module.exports=exports["default"]},{"./ease-common":149}],154:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});"use strict";var Rx=require("rx");var _require=require("./ease-common");var interpolate=_require.interpolate;var _require2=require("./ease-powers");var EasingPower2=_require2.EasingPower2;var EasingPower3=_require2.EasingPower3;var EasingPower4=_require2.EasingPower4;var _require3=require("./ease-exponential");var EasingExponential=_require3.EasingExponential;var _require4=require("./ease-back");var EasingBack=_require4.EasingBack;var _require5=require("./ease-bounce");var EasingBounce=_require5.EasingBounce;var _require6=require("./ease-circ");var EasingCirc=_require6.EasingCirc;var _require7=require("./ease-elastic");var EasingElastic=_require7.EasingElastic;var _require8=require("./ease-sine");var EasingSine=_require8.EasingSine;var DEFAULT_INTERVAL=15;function sanitizeInterval(interval){if(interval==="auto"){return DEFAULT_INTERVAL}else if(typeof interval!=="number"||interval<=0){console.warn("RxTween cannot use invalid given interval: "+interval);return DEFAULT_INTERVAL}return interval}function RxTween(_ref){var from=_ref.from;var to=_ref.to;var duration=_ref.duration;var _ref$ease=_ref.ease;var ease=_ref$ease===undefined?RxTween.Linear.ease:_ref$ease;var _ref$interval=_ref.interval;var interval=_ref$interval===undefined?"auto":_ref$interval;var sanitizedInterval=sanitizeInterval(interval);var totalTicks=Math.round(duration/sanitizedInterval);return Rx.Observable.interval(sanitizedInterval).take(totalTicks).map(function(tick){return ease(tick/totalTicks,from,to)}).concat(Rx.Observable.just(to))}RxTween.Linear={ease:interpolate};RxTween.Power2=EasingPower2;RxTween.Power3=EasingPower3; -RxTween.Power4=EasingPower4;RxTween.Exp=EasingExponential;RxTween.Back=EasingBack;RxTween.Bounce=EasingBounce;RxTween.Circ=EasingCirc;RxTween.Elastic=EasingElastic;RxTween.Sine=EasingSine;exports["default"]=RxTween;module.exports=exports["default"]},{"./ease-back":146,"./ease-bounce":147,"./ease-circ":148,"./ease-common":149,"./ease-elastic":150,"./ease-exponential":151,"./ease-powers":152,"./ease-sine":153,rx:120}],155:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var _cycleCore=require("@cycle/core");var _cycleCore2=_interopRequireDefault(_cycleCore);var _cycleDom=require("@cycle/dom");var _rxmarblesAppModel=require("rxmarbles/app-model");var _rxmarblesAppModel2=_interopRequireDefault(_rxmarblesAppModel);var _rxmarblesAppView=require("rxmarbles/app-view");var _rxmarblesAppView2=_interopRequireDefault(_rxmarblesAppView);var _rxmarblesComponentsOperatorsMenuLink=require("rxmarbles/components/operators-menu-link");var _rxmarblesComponentsOperatorsMenuLink2=_interopRequireDefault(_rxmarblesComponentsOperatorsMenuLink);var _rxmarblesComponentsOperatorsMenu=require("rxmarbles/components/operators-menu");var _rxmarblesComponentsOperatorsMenu2=_interopRequireDefault(_rxmarblesComponentsOperatorsMenu);var _rxmarblesComponentsSandboxSandbox=require("rxmarbles/components/sandbox/sandbox");var _rxmarblesComponentsSandboxSandbox2=_interopRequireDefault(_rxmarblesComponentsSandboxSandbox);var _rxmarblesComponentsDiagramDiagram=require("rxmarbles/components/diagram/diagram");var _rxmarblesComponentsDiagramDiagram2=_interopRequireDefault(_rxmarblesComponentsDiagramDiagram);var _rxmarblesComponentsMarble=require("rxmarbles/components/marble");var _rxmarblesComponentsMarble2=_interopRequireDefault(_rxmarblesComponentsMarble);var _rxmarblesComponentsDiagramCompletion=require("rxmarbles/components/diagram-completion");var _rxmarblesComponentsDiagramCompletion2=_interopRequireDefault(_rxmarblesComponentsDiagramCompletion);function main(){return{DOM:(0,_rxmarblesAppView2["default"])((0,_rxmarblesAppModel2["default"])())}}_cycleCore2["default"].run(main,{DOM:(0,_cycleDom.makeDOMDriver)(".js-appContainer",{"x-operators-menu-link":_rxmarblesComponentsOperatorsMenuLink2["default"],"x-operators-menu":_rxmarblesComponentsOperatorsMenu2["default"],"x-sandbox":_rxmarblesComponentsSandboxSandbox2["default"],"x-marble":_rxmarblesComponentsMarble2["default"],"x-diagram-completion":_rxmarblesComponentsDiagramCompletion2["default"],"x-diagram":_rxmarblesComponentsDiagramDiagram2["default"]})})},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/app-model":121,"rxmarbles/app-view":122,"rxmarbles/components/diagram-completion":123,"rxmarbles/components/diagram/diagram":127,"rxmarbles/components/marble":128,"rxmarbles/components/operators-menu":130,"rxmarbles/components/operators-menu-link":129,"rxmarbles/components/sandbox/sandbox":133}]},{},[155]); \ No newline at end of file +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o y ? 1 : (x < y ? -1 : 0); }, + defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, + defaultError = Rx.helpers.defaultError = function (err) { throw err; }, + isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, + asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, + not = Rx.helpers.not = function (a) { return !a; }, + isFunction = Rx.helpers.isFunction = (function () { + + var isFn = function (value) { + return typeof value == 'function' || false; + } + + // fallback for older versions of Chrome and Safari + if (isFn(/x/)) { + isFn = function(value) { + return typeof value == 'function' && toString.call(value) == '[object Function]'; + }; + } + + return isFn; + }()); + + function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} + + Rx.config.longStackSupport = false; + var hasStacks = false; + try { + throw new Error(); + } catch (e) { + hasStacks = !!e.stack; + } + + // All code after this point will be filtered from stack traces reported by RxJS + var rStartingLine = captureLine(), rFileName; + + var STACK_JUMP_SEPARATOR = "From previous event:"; + + function makeStackTraceLong(error, observable) { + // If possible, transform the error stack trace by removing Node and RxJS + // cruft, then concatenating with the stack trace of `observable`. + if (hasStacks && + observable.stack && + typeof error === "object" && + error !== null && + error.stack && + error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 + ) { + var stacks = []; + for (var o = observable; !!o; o = o.source) { + if (o.stack) { + stacks.unshift(o.stack); + } + } + stacks.unshift(error.stack); + + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + error.stack = filterStackString(concatedStacks); + } + } + + function filterStackString(stackString) { + var lines = stackString.split("\n"), + desiredLines = []; + for (var i = 0, len = lines.length; i < len; i++) { + var line = lines[i]; + + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); + } + + function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + if (!fileNameAndLineNumber) { + return false; + } + var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; + + return fileName === rFileName && + lineNumber >= rStartingLine && + lineNumber <= rEndingLine; + } + + function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; + } + + function captureLine() { + if (!hasStacks) { return; } + + try { + throw new Error(); + } catch (e) { + var lines = e.stack.split("\n"); + var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); + if (!fileNameAndLineNumber) { return; } + + rFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; + } + } + + function getFileNameAndLineNumber(stackLine) { + // Named functions: "at functionName (filename:lineNumber:columnNumber)" + var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); + if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } + + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } + + // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); + if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } + } + + var EmptyError = Rx.EmptyError = function() { + this.message = 'Sequence contains no elements.'; + Error.call(this); + }; + EmptyError.prototype = Error.prototype; + + var ObjectDisposedError = Rx.ObjectDisposedError = function() { + this.message = 'Object has been disposed'; + Error.call(this); + }; + ObjectDisposedError.prototype = Error.prototype; + + var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { + this.message = 'Argument out of range'; + Error.call(this); + }; + ArgumentOutOfRangeError.prototype = Error.prototype; + + var NotSupportedError = Rx.NotSupportedError = function (message) { + this.message = message || 'This operation is not supported'; + Error.call(this); + }; + NotSupportedError.prototype = Error.prototype; + + var NotImplementedError = Rx.NotImplementedError = function (message) { + this.message = message || 'This operation is not implemented'; + Error.call(this); + }; + NotImplementedError.prototype = Error.prototype; + + var notImplemented = Rx.helpers.notImplemented = function () { + throw new NotImplementedError(); + }; + + var notSupported = Rx.helpers.notSupported = function () { + throw new NotSupportedError(); + }; + + // Shim in iterator support + var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || + '_es6shim_iterator_'; + // Bug for mozilla version + if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + $iterator$ = '@@iterator'; + } + + var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; + + var isIterable = Rx.helpers.isIterable = function (o) { + return o[$iterator$] !== undefined; + } + + var isArrayLike = Rx.helpers.isArrayLike = function (o) { + return o && o.length !== undefined; + } + + Rx.helpers.iterator = $iterator$; + + var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { + if (typeof thisArg === 'undefined') { return func; } + switch(argCount) { + case 0: + return function() { + return func.call(thisArg) + }; + case 1: + return function(arg) { + return func.call(thisArg, arg); + } + case 2: + return function(value, index) { + return func.call(thisArg, value, index); + }; + case 3: + return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + } + + return function() { + return func.apply(thisArg, arguments); + }; + }; + + /** Used to determine if values are of the language type Object */ + var dontEnums = ['toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor'], + dontEnumsLength = dontEnums.length; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + errorClass = '[object Error]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + return result; + } + + var hasProp = {}.hasOwnProperty, + slice = Array.prototype.slice; + + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; + + var addProperties = Rx.internals.addProperties = function (obj) { + for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + for (var idx = 0, ln = sources.length; idx < ln; idx++) { + var source = sources[idx]; + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }; + + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; + + function arrayInitialize(count, factory) { + var a = new Array(count); + for (var i = 0; i < count; i++) { + a[i] = factory(); + } + return a; + } + + var errorObj = {e: {}}; + var tryCatchTarget; + function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } + } + function tryCatch(fn) { + if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } + tryCatchTarget = fn; + return tryCatcher; + } + function thrower(e) { + throw e; + } + + // Collections + function IndexedItem(id, value) { + this.id = id; + this.value = value; + } + + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + c === 0 && (c = this.id - other.id); + return c; + }; + + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; + + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; + + priorityProto.percolate = function (index) { + if (index >= this.length || index < 0) { return; } + var parent = index - 1 >> 1; + if (parent < 0 || parent === index) { return; } + if (this.isHigherPriority(index, parent)) { + var temp = this.items[index]; + this.items[index] = this.items[parent]; + this.items[parent] = temp; + this.percolate(parent); + } + }; + + priorityProto.heapify = function (index) { + +index || (index = 0); + if (index >= this.length || index < 0) { return; } + var left = 2 * index + 1, + right = 2 * index + 2, + first = index; + if (left < this.length && this.isHigherPriority(left, first)) { + first = left; + } + if (right < this.length && this.isHigherPriority(right, first)) { + first = right; + } + if (first !== index) { + var temp = this.items[index]; + this.items[index] = this.items[first]; + this.items[first] = temp; + this.heapify(first); + } + }; + + priorityProto.peek = function () { return this.items[0].value; }; + + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + this.items[this.length] = undefined; + this.heapify(); + }; + + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; + + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; + + priorityProto.remove = function (item) { + for (var i = 0; i < this.length; i++) { + if (this.items[i].value === item) { + this.removeAt(i); + return true; + } + } + return false; + }; + PriorityQueue.count = 0; + + /** + * Represents a group of disposable resources that are disposed together. + * @constructor + */ + var CompositeDisposable = Rx.CompositeDisposable = function () { + var args = [], i, len; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + len = args.length; + } else { + len = arguments.length; + args = new Array(len); + for(i = 0; i < len; i++) { args[i] = arguments[i]; } + } + for(i = 0; i < len; i++) { + if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } + } + this.disposables = args; + this.isDisposed = false; + this.length = args.length; + }; + + var CompositeDisposablePrototype = CompositeDisposable.prototype; + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Mixed} item Disposable to add. + */ + CompositeDisposablePrototype.add = function (item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + this.length++; + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Mixed} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + CompositeDisposablePrototype.remove = function (item) { + var shouldDispose = false; + if (!this.isDisposed) { + var idx = this.disposables.indexOf(item); + if (idx !== -1) { + shouldDispose = true; + this.disposables.splice(idx, 1); + this.length--; + item.dispose(); + } + } + return shouldDispose; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + CompositeDisposablePrototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var len = this.disposables.length, currentDisposables = new Array(len); + for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } + this.disposables = []; + this.length = 0; + + for (i = 0; i < len; i++) { + currentDisposables[i].dispose(); + } + } + }; + + /** + * Provides a set of static methods for creating Disposables. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + */ + var Disposable = Rx.Disposable = function (action) { + this.isDisposed = false; + this.action = action || noop; + }; + + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; + + /** + * Creates a disposable object that invokes the specified action when disposed. + * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. + * @return {Disposable} The disposable object that runs the given action upon disposal. + */ + var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; + + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; + + /** + * Validates whether the given object is a disposable + * @param {Object} Object to test whether it has a dispose method + * @returns {Boolean} true if a disposable object, else false. + */ + var isDisposable = Disposable.isDisposable = function (d) { + return d && isFunction(d.dispose); + }; + + var checkDisposed = Disposable.checkDisposed = function (disposable) { + if (disposable.isDisposed) { throw new ObjectDisposedError(); } + }; + + // Single assignment + var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SingleAssignmentDisposable.prototype.getDisposable = function () { + return this.current; + }; + SingleAssignmentDisposable.prototype.setDisposable = function (value) { + if (this.current) { throw new Error('Disposable has already been assigned'); } + var shouldDispose = this.isDisposed; + !shouldDispose && (this.current = value); + shouldDispose && value && value.dispose(); + }; + SingleAssignmentDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + // Multiple assignment disposable + var SerialDisposable = Rx.SerialDisposable = function () { + this.isDisposed = false; + this.current = null; + }; + SerialDisposable.prototype.getDisposable = function () { + return this.current; + }; + SerialDisposable.prototype.setDisposable = function (value) { + var shouldDispose = this.isDisposed; + if (!shouldDispose) { + var old = this.current; + this.current = value; + } + old && old.dispose(); + shouldDispose && value && value.dispose(); + }; + SerialDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + var old = this.current; + this.current = null; + } + old && old.dispose(); + }; + + /** + * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + */ + var RefCountDisposable = Rx.RefCountDisposable = (function () { + + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } + + InnerDisposable.prototype.dispose = function () { + if (!this.disposable.isDisposed && !this.isInnerDisposed) { + this.isInnerDisposed = true; + this.disposable.count--; + if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { + this.disposable.isDisposed = true; + this.disposable.underlyingDisposable.dispose(); + } + } + }; + + /** + * Initializes a new instance of the RefCountDisposable with the specified disposable. + * @constructor + * @param {Disposable} disposable Underlying disposable. + */ + function RefCountDisposable(disposable) { + this.underlyingDisposable = disposable; + this.isDisposed = false; + this.isPrimaryDisposed = false; + this.count = 0; + } + + /** + * Disposes the underlying disposable only when all dependent disposables have been disposed + */ + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed && !this.isPrimaryDisposed) { + this.isPrimaryDisposed = true; + if (this.count === 0) { + this.isDisposed = true; + this.underlyingDisposable.dispose(); + } + } + }; + + /** + * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. + * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. + */ + RefCountDisposable.prototype.getDisposable = function () { + return this.isDisposed ? disposableEmpty : new InnerDisposable(this); + }; + + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } + + function scheduleItem(s, self) { + if (!self.isDisposed) { + self.isDisposed = true; + self.disposable.dispose(); + } + } + + ScheduledDisposable.prototype.dispose = function () { + this.scheduler.scheduleWithState(this, scheduleItem); + }; + + var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { + this.scheduler = scheduler; + this.state = state; + this.action = action; + this.dueTime = dueTime; + this.comparer = comparer || defaultSubComparer; + this.disposable = new SingleAssignmentDisposable(); + } + + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; + + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; + + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; + + ScheduledItem.prototype.invokeCore = function () { + return this.action(this.scheduler, this.state); + }; + + /** Provides a set of static properties to access commonly used schedulers. */ + var Scheduler = Rx.Scheduler = (function () { + + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } + + /** Determines whether the given object is a scheduler */ + Scheduler.isScheduler = function (s) { + return s instanceof Scheduler; + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + var schedulerProto = Scheduler.prototype; + + /** + * Schedules an action to be executed. + * @param {Function} action Action to execute. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.schedule = function (action) { + return this._schedule(action, invokeAction); + }; + + /** + * Schedules an action to be executed. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithState = function (state, action) { + return this._schedule(state, action); + }; + + /** + * Schedules an action to be executed after the specified relative due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelative = function (dueTime, action) { + return this._scheduleRelative(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative(state, dueTime, action); + }; + + /** + * Schedules an action to be executed at the specified absolute due time. + * @param {Function} action Action to execute. + * @param {Number} dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsolute = function (dueTime, action) { + return this._scheduleAbsolute(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to be executed. + * @param {Number}dueTime Absolute time at which to execute the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute(state, dueTime, action); + }; + + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; + + /** + * Normalizes the specified TimeSpan value to a positive value. + * @param {Number} timeSpan The time span value to normalize. + * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 + */ + Scheduler.normalize = function (timeSpan) { + timeSpan < 0 && (timeSpan = 0); + return timeSpan; + }; + + return Scheduler; + }()); + + var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; + + (function (schedulerProto) { + + function invokeRecImmediate(scheduler, pair) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + + function recursiveAction(state1) { + action(state1, function (state2) { + var isAdded = false, isDone = false, + d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + } + recursiveAction(state); + return group; + } + + function invokeRecDate(scheduler, pair, method) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); + function recursiveAction(state1) { + action(state1, function (state2, dueTime1) { + var isAdded = false, isDone = false, + d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { + if (isAdded) { + group.remove(d); + } else { + isDone = true; + } + recursiveAction(state3); + return disposableEmpty; + }); + if (!isDone) { + group.add(d); + isAdded = true; + } + }); + }; + recursiveAction(state); + return group; + } + + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } + + /** + * Schedules an action to be executed recursively. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursive = function (action) { + return this.scheduleRecursiveWithState(action, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithState = function (state, action) { + return this.scheduleWithState([state, action], invokeRecImmediate); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { + return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively after a specified relative due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Relative time after which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { + return this._scheduleRelative([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); + }); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { + return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); + }; + + /** + * Schedules an action to be executed recursively at a specified absolute due time. + * @param {Mixed} state State passed to the action to be executed. + * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. + * @param {Number}dueTime Absolute time at which to execute the action for the first time. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { + return this._scheduleAbsolute([state, action], dueTime, function (s, p) { + return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); + }); + }; + }(Scheduler.prototype)); + + (function (schedulerProto) { + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodic = function (period, action) { + return this.schedulePeriodicWithState(null, period, action); + }; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { + if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } + period = normalizeTime(period); + var s = state, id = root.setInterval(function () { s = action(s); }, period); + return disposableCreate(function () { root.clearInterval(id); }); + }; + + }(Scheduler.prototype)); + + (function (schedulerProto) { + /** + * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. + * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. + * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. + */ + schedulerProto.catchError = schedulerProto['catch'] = function (handler) { + return new CatchScheduler(this, handler); + }; + }(Scheduler.prototype)); + + var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { + function tick(command, recurse) { + recurse(0, this._period); + try { + this._state = this._action(this._state); + } catch (e) { + this._cancel.dispose(); + throw e; + } + } + + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } + + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + + return d; + }; + + return SchedulePeriodicRecursive; + }()); + + /** Gets a scheduler that schedules work immediately on the current thread. */ + var immediateScheduler = Scheduler.immediate = (function () { + function scheduleNow(state, action) { return action(this, state); } + return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + }()); + + /** + * Gets a scheduler that schedules work as soon as possible on the current thread. + */ + var currentThreadScheduler = Scheduler.currentThread = (function () { + var queue; + + function runTrampoline () { + while (queue.length > 0) { + var item = queue.dequeue(); + !item.isCancelled() && item.invoke(); + } + } + + function scheduleNow(state, action) { + var si = new ScheduledItem(this, state, action, this.now()); + + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); + + var result = tryCatch(runTrampoline)(); + queue = null; + if (result === errorObj) { return thrower(result.e); } + } else { + queue.enqueue(si); + } + return si.disposable; + } + + var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + currentScheduler.scheduleRequired = function () { return !queue; }; + + return currentScheduler; + }()); + + var scheduleMethod, clearMethod; + + var localTimer = (function () { + var localSetTimeout, localClearTimeout = noop; + if (!!root.setTimeout) { + localSetTimeout = root.setTimeout; + localClearTimeout = root.clearTimeout; + } else if (!!root.WScript) { + localSetTimeout = function (fn, time) { + root.WScript.Sleep(time); + fn(); + }; + } else { + throw new NotSupportedError(); + } + + return { + setTimeout: localSetTimeout, + clearTimeout: localClearTimeout + }; + }()); + var localSetTimeout = localTimer.setTimeout, + localClearTimeout = localTimer.clearTimeout; + + (function () { + + var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; + + clearMethod = function (handle) { + delete tasksByHandle[handle]; + }; + + function runTask(handle) { + if (currentlyRunning) { + localSetTimeout(function () { runTask(handle) }, 0); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunning = true; + var result = tryCatch(task)(); + clearMethod(handle); + currentlyRunning = false; + if (result === errorObj) { return thrower(result.e); } + } + } + } + + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate; + + function postMessageSupported () { + // Ensure not in a worker + if (!root.postMessage || root.importScripts) { return false; } + var isAsync = false, oldHandler = root.onmessage; + // Test for async + root.onmessage = function () { isAsync = true; }; + root.postMessage('', '*'); + root.onmessage = oldHandler; + + return isAsync; + } + + // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout + if (isFunction(setImmediate)) { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + setImmediate(function () { runTask(id); }); + + return id; + }; + } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + process.nextTick(function () { runTask(id); }); + + return id; + }; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); + + function onGlobalPostMessage(event) { + // Only if we're a match to avoid any other global events + if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { + runTask(event.data.substring(MSG_PREFIX.length)); + } + } + + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else if (root.attachEvent) { + root.attachEvent('onmessage', onGlobalPostMessage); + } else { + root.onmessage = onGlobalPostMessage; + } + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + root.postMessage(MSG_PREFIX + currentId, '*'); + return id; + }; + } else if (!!root.MessageChannel) { + var channel = new root.MessageChannel(); + + channel.port1.onmessage = function (e) { runTask(e.data); }; + + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + channel.port2.postMessage(id); + return id; + }; + } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { + + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + var id = nextHandle++; + tasksByHandle[id] = action; + + scriptElement.onreadystatechange = function () { + runTask(id); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + return id; + }; + + } else { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + localSetTimeout(function () { + runTask(id); + }, 0); + + return id; + }; + } + }()); + + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { + + function scheduleNow(state, action) { + var scheduler = this, disposable = new SingleAssignmentDisposable(); + var id = scheduleMethod(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }); + return new CompositeDisposable(disposable, disposableCreate(function () { + clearMethod(id); + })); + } + + function scheduleRelative(state, dueTime, action) { + var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); + if (dt === 0) { return scheduler.scheduleWithState(state, action); } + var id = localSetTimeout(function () { + !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); + }, dt); + return new CompositeDisposable(disposable, disposableCreate(function () { + localClearTimeout(id); + })); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } + + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + var CatchScheduler = (function (__super__) { + + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } + + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } + + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } + + inherits(CatchScheduler, __super__); + + function CatchScheduler(scheduler, handler) { + this._scheduler = scheduler; + this._handler = handler; + this._recursiveOriginal = null; + this._recursiveWrapper = null; + __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); + } + + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; + + CatchScheduler.prototype._wrap = function (action) { + var parent = this; + return function (self, state) { + try { + return action(parent._getRecursiveWrapper(self), state); + } catch (e) { + if (!parent._handler(e)) { throw e; } + return disposableEmpty; + } + }; + }; + + CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { + if (this._recursiveOriginal !== scheduler) { + this._recursiveOriginal = scheduler; + var wrapper = this._clone(scheduler); + wrapper._recursiveOriginal = scheduler; + wrapper._recursiveWrapper = wrapper; + this._recursiveWrapper = wrapper; + } + return this._recursiveWrapper; + }; + + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); + + d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { + if (failed) { return null; } + try { + return action(state1); + } catch (e) { + failed = true; + if (!self._handler(e)) { throw e; } + d.dispose(); + return null; + } + })); + + return d; + }; + + return CatchScheduler; + }(Scheduler)); + + /** + * Represents a notification to an observer. + */ + var Notification = Rx.Notification = (function () { + function Notification(kind, value, exception, accept, acceptObservable, toString) { + this.kind = kind; + this.value = value; + this.exception = exception; + this._accept = accept; + this._acceptObservable = acceptObservable; + this.toString = toString; + } + + /** + * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. + * + * @memberOf Notification + * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. + * @param {Function} onError Delegate to invoke for an OnError notification. + * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. + * @returns {Any} Result produced by the observation. + */ + Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { + return observerOrOnNext && typeof observerOrOnNext === 'object' ? + this._acceptObservable(observerOrOnNext) : + this._accept(observerOrOnNext, onError, onCompleted); + }; + + /** + * Returns an observable sequence with a single notification. + * + * @memberOf Notifications + * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. + * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. + */ + Notification.prototype.toObservable = function (scheduler) { + var self = this; + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithState(self, function (_, notification) { + notification._acceptObservable(observer); + notification.kind === 'N' && observer.onCompleted(); + }); + }); + }; + + return Notification; + })(); + + /** + * Creates an object that represents an OnNext notification to an observer. + * @param {Any} value The value contained in the notification. + * @returns {Notification} The OnNext notification containing the value. + */ + var notificationCreateOnNext = Notification.createOnNext = (function () { + function _accept(onNext) { return onNext(this.value); } + function _acceptObservable(observer) { return observer.onNext(this.value); } + function toString() { return 'OnNext(' + this.value + ')'; } + + return function (value) { + return new Notification('N', value, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnError notification to an observer. + * @param {Any} error The exception contained in the notification. + * @returns {Notification} The OnError notification containing the exception. + */ + var notificationCreateOnError = Notification.createOnError = (function () { + function _accept (onNext, onError) { return onError(this.exception); } + function _acceptObservable(observer) { return observer.onError(this.exception); } + function toString () { return 'OnError(' + this.exception + ')'; } + + return function (e) { + return new Notification('E', null, e, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Creates an object that represents an OnCompleted notification to an observer. + * @returns {Notification} The OnCompleted notification. + */ + var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { + function _accept (onNext, onError, onCompleted) { return onCompleted(); } + function _acceptObservable(observer) { return observer.onCompleted(); } + function toString () { return 'OnCompleted()'; } + + return function () { + return new Notification('C', null, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; + + /** + * Creates a notification callback from an observer. + * @returns The action that forwards its input notification to the underlying observer. + */ + Observer.prototype.toNotifier = function () { + var observer = this; + return function (n) { return n.accept(observer); }; + }; + + /** + * Hides the identity of an observer. + * @returns An observer that hides the identity of the specified observer. + */ + Observer.prototype.asObserver = function () { + return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); + }; + + /** + * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. + * If a violation is detected, an Error is thrown from the offending observer method call. + * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. + */ + Observer.prototype.checked = function () { return new CheckedObserver(this); }; + + /** + * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. + * @param {Function} [onNext] Observer's OnNext action implementation. + * @param {Function} [onError] Observer's OnError action implementation. + * @param {Function} [onCompleted] Observer's OnCompleted action implementation. + * @returns {Observer} The observer object implemented using the given actions. + */ + var observerCreate = Observer.create = function (onNext, onError, onCompleted) { + onNext || (onNext = noop); + onError || (onError = defaultError); + onCompleted || (onCompleted = noop); + return new AnonymousObserver(onNext, onError, onCompleted); + }; + + /** + * Creates an observer from a notification callback. + * + * @static + * @memberOf Observer + * @param {Function} handler Action that handles a notification. + * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. + */ + Observer.fromNotifier = function (handler, thisArg) { + return new AnonymousObserver(function (x) { + return handler.call(thisArg, notificationCreateOnNext(x)); + }, function (e) { + return handler.call(thisArg, notificationCreateOnError(e)); + }, function () { + return handler.call(thisArg, notificationCreateOnCompleted()); + }); + }; + + /** + * Schedules the invocation of observer methods on the given scheduler. + * @param {Scheduler} scheduler Scheduler to schedule observer messages on. + * @returns {Observer} Observer whose messages are scheduled on the given scheduler. + */ + Observer.prototype.notifyOn = function (scheduler) { + return new ObserveOnObserver(scheduler, this); + }; + + Observer.prototype.makeSafe = function(disposable) { + return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); + }; + + /** + * Abstract base class for implementations of the Observer class. + * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + */ + var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { + inherits(AbstractObserver, __super__); + + /** + * Creates a new observer in a non-stopped state. + */ + function AbstractObserver() { + this.isStopped = false; + __super__.call(this); + } + + // Must be implemented by other observers + AbstractObserver.prototype.next = notImplemented; + AbstractObserver.prototype.error = notImplemented; + AbstractObserver.prototype.completed = notImplemented; + + /** + * Notifies the observer of a new element in the sequence. + * @param {Any} value Next element in the sequence. + */ + AbstractObserver.prototype.onNext = function (value) { + if (!this.isStopped) { this.next(value); } + }; + + /** + * Notifies the observer that an exception has occurred. + * @param {Any} error The error that has occurred. + */ + AbstractObserver.prototype.onError = function (error) { + if (!this.isStopped) { + this.isStopped = true; + this.error(error); + } + }; + + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; + + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; + + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } + + return false; + }; + + return AbstractObserver; + }(Observer)); + + /** + * Class to create an Observer instance from delegate-based implementations of the on* methods. + */ + var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { + inherits(AnonymousObserver, __super__); + + /** + * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. + * @param {Any} onNext Observer's OnNext action implementation. + * @param {Any} onError Observer's OnError action implementation. + * @param {Any} onCompleted Observer's OnCompleted action implementation. + */ + function AnonymousObserver(onNext, onError, onCompleted) { + __super__.call(this); + this._onNext = onNext; + this._onError = onError; + this._onCompleted = onCompleted; + } + + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; + + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (error) { + this._onError(error); + }; + + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; + + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (__super__) { + inherits(CheckedObserver, __super__); + + function CheckedObserver(observer) { + __super__.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } + + var CheckedObserverPrototype = CheckedObserver.prototype; + + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + var res = tryCatch(this._observer.onNext).call(this._observer, value); + this._state = 0; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + var res = tryCatch(this._observer.onError).call(this._observer, err); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + var res = tryCatch(this._observer.onCompleted).call(this._observer); + this._state = 2; + res === errorObj && thrower(res.e); + }; + + CheckedObserverPrototype.checkAccess = function () { + if (this._state === 1) { throw new Error('Re-entrancy detected'); } + if (this._state === 2) { throw new Error('Observer completed'); } + if (this._state === 0) { this._state = 1; } + }; + + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { + inherits(ScheduledObserver, __super__); + + function ScheduledObserver(scheduler, observer) { + __super__.call(this); + this.scheduler = scheduler; + this.observer = observer; + this.isAcquired = false; + this.hasFaulted = false; + this.queue = []; + this.disposable = new SerialDisposable(); + } + + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { self.observer.onNext(value); }); + }; + + ScheduledObserver.prototype.error = function (e) { + var self = this; + this.queue.push(function () { self.observer.onError(e); }); + }; + + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { self.observer.onCompleted(); }); + }; + + ScheduledObserver.prototype.ensureActive = function () { + var isOwner = false, parent = this; + if (!this.hasFaulted && this.queue.length > 0) { + isOwner = !this.isAcquired; + this.isAcquired = true; + } + if (isOwner) { + this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { + var work; + if (parent.queue.length > 0) { + work = parent.queue.shift(); + } else { + parent.isAcquired = false; + return; + } + try { + work(); + } catch (ex) { + parent.queue = []; + parent.hasFaulted = true; + throw ex; + } + self(); + })); + } + }; + + ScheduledObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.disposable.dispose(); + }; + + return ScheduledObserver; + }(AbstractObserver)); + + var ObserveOnObserver = (function (__super__) { + inherits(ObserveOnObserver, __super__); + + function ObserveOnObserver(scheduler, observer, cancel) { + __super__.call(this, scheduler, observer); + this._cancel = cancel; + } + + ObserveOnObserver.prototype.next = function (value) { + __super__.prototype.next.call(this, value); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.error = function (e) { + __super__.prototype.error.call(this, e); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.completed = function () { + __super__.prototype.completed.call(this); + this.ensureActive(); + }; + + ObserveOnObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this._cancel && this._cancel.dispose(); + this._cancel = null; + }; + + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; + + /** + * Represents a push-style collection. + */ + var Observable = Rx.Observable = (function () { + + function Observable(subscribe) { + if (Rx.config.longStackSupport && hasStacks) { + try { + throw new Error(); + } catch (e) { + this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); + } + + var self = this; + this._subscribe = function (observer) { + var oldOnError = observer.onError.bind(observer); + + observer.onError = function (err) { + makeStackTraceLong(err, self); + oldOnError(err); + }; + + return subscribe.call(self, observer); + }; + } else { + this._subscribe = subscribe; + } + } + + observableProto = Observable.prototype; + + /** + * Subscribes an observer to the observable sequence. + * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. + * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { + return this._subscribe(typeof observerOrOnNext === 'object' ? + observerOrOnNext : + observerCreate(observerOrOnNext, onError, onCompleted)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onNext The function to invoke on each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnNext = function (onNext, thisArg) { + return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); + }; + + /** + * Subscribes to an exceptional condition in the sequence with an optional "this" argument. + * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnError = function (onError, thisArg) { + return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); + }; + + /** + * Subscribes to the next value in the sequence with an optional "this" argument. + * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. + */ + observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { + return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); + }; + + return Observable; + })(); + + var ObservableBase = Rx.ObservableBase = (function (__super__) { + inherits(ObservableBase, __super__); + + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], self = state[1]; + var sub = tryCatch(self.subscribeCore).call(self, ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function subscribe(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, this]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + function ObservableBase() { + __super__.call(this, subscribe); + } + + ObservableBase.prototype.subscribeCore = notImplemented; + + return ObservableBase; + }(Observable)); + + var Enumerable = Rx.internals.Enumerable = function () { }; + + var ConcatEnumerableObservable = (function(__super__) { + inherits(ConcatEnumerableObservable, __super__); + function ConcatEnumerableObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + ConcatEnumerableObservable.prototype.subscribeCore = function (o) { + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + function InnerObserver(o, s, e) { + this.o = o; + this.s = s; + this.e = e; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.s(this.e); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; }; + InnerObserver.prototype.fail = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + return true; + } + return false; + }; + + return ConcatEnumerableObservable; + }(ObservableBase)); + + Enumerable.prototype.concat = function () { + return new ConcatEnumerableObservable(this); + }; + + var CatchErrorObservable = (function(__super__) { + inherits(CatchErrorObservable, __super__); + function CatchErrorObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + CatchErrorObservable.prototype.subscribeCore = function (o) { + var e = this.sources[$iterator$](); + + var isDisposed, subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + return lastException !== null ? o.onError(lastException) : o.onCompleted(); + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + self, + function() { o.onCompleted(); })); + }); + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + return CatchErrorObservable; + }(ObservableBase)); + + Enumerable.prototype.catchError = function () { + return new CatchErrorObservable(this); + }; + + Enumerable.prototype.catchErrorWhen = function (notificationHandler) { + var sources = this; + return new AnonymousObservable(function (o) { + var exceptions = new Subject(), + notifier = new Subject(), + handled = notificationHandler(exceptions), + notificationDisposable = handled.subscribe(notifier); + + var e = sources[$iterator$](); + + var isDisposed, + lastException, + subscription = new SerialDisposable(); + var cancelable = immediateScheduler.scheduleRecursive(function (self) { + if (isDisposed) { return; } + var currentItem = tryCatch(e.next).call(e); + if (currentItem === errorObj) { return o.onError(currentItem.e); } + + if (currentItem.done) { + if (lastException) { + o.onError(lastException); + } else { + o.onCompleted(); + } + return; + } + + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var outer = new SingleAssignmentDisposable(); + var inner = new SingleAssignmentDisposable(); + subscription.setDisposable(new CompositeDisposable(inner, outer)); + outer.setDisposable(currentValue.subscribe( + function(x) { o.onNext(x); }, + function (exn) { + inner.setDisposable(notifier.subscribe(self, function(ex) { + o.onError(ex); + }, function() { + o.onCompleted(); + })); + + exceptions.onNext(exn); + }, + function() { o.onCompleted(); })); + }); + + return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }); + }; + + var RepeatEnumerable = (function (__super__) { + inherits(RepeatEnumerable, __super__); + + function RepeatEnumerable(v, c) { + this.v = v; + this.c = c == null ? -1 : c; + } + RepeatEnumerable.prototype[$iterator$] = function () { + return new RepeatEnumerator(this); + }; + + function RepeatEnumerator(p) { + this.v = p.v; + this.l = p.c; + } + RepeatEnumerator.prototype.next = function () { + if (this.l === 0) { return doneEnumerator; } + if (this.l > 0) { this.l--; } + return { done: false, value: this.v }; + }; + + return RepeatEnumerable; + }(Enumerable)); + + var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { + return new RepeatEnumerable(value, repeatCount); + }; + + var OfEnumerable = (function(__super__) { + inherits(OfEnumerable, __super__); + function OfEnumerable(s, fn, thisArg) { + this.s = s; + this.fn = fn ? bindCallback(fn, thisArg, 3) : null; + } + OfEnumerable.prototype[$iterator$] = function () { + return new OfEnumerator(this); + }; + + function OfEnumerator(p) { + this.i = -1; + this.s = p.s; + this.l = this.s.length; + this.fn = p.fn; + } + OfEnumerator.prototype.next = function () { + return ++this.i < this.l ? + { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : + doneEnumerator; + }; + + return OfEnumerable; + }(Enumerable)); + + var enumerableOf = Enumerable.of = function (source, selector, thisArg) { + return new OfEnumerable(source, selector, thisArg); + }; + + /** + * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + * + * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects + * that require to be run on a scheduler, use subscribeOn. + * + * @param {Scheduler} scheduler Scheduler to notify observers on. + * @returns {Observable} The source sequence whose observations happen on the specified scheduler. + */ + observableProto.observeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(new ObserveOnObserver(scheduler, observer)); + }, source); + }; + + /** + * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; + * see the remarks section for more information on the distinction between subscribeOn and observeOn. + + * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer + * callbacks on a scheduler, use observeOn. + + * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. + * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + observableProto.subscribeOn = function (scheduler) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); + d.setDisposable(m); + m.setDisposable(scheduler.schedule(function () { + d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); + })); + return d; + }, source); + }; + + var FromPromiseObservable = (function(__super__) { + inherits(FromPromiseObservable, __super__); + function FromPromiseObservable(p) { + this.p = p; + __super__.call(this); + } + + FromPromiseObservable.prototype.subscribeCore = function(o) { + this.p.then(function (data) { + o.onNext(data); + o.onCompleted(); + }, function (err) { o.onError(err); }); + return disposableEmpty; + }; + + return FromPromiseObservable; + }(ObservableBase)); + + /** + * Converts a Promise to an Observable sequence + * @param {Promise} An ES6 Compliant promise. + * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. + */ + var observableFromPromise = Observable.fromPromise = function (promise) { + return new FromPromiseObservable(promise); + }; + /* + * Converts an existing observable sequence to an ES6 Compatible Promise + * @example + * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); + * + * // With config + * Rx.config.Promise = RSVP.Promise; + * var promise = Rx.Observable.return(42).toPromise(); + * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. + * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. + */ + observableProto.toPromise = function (promiseCtor) { + promiseCtor || (promiseCtor = Rx.config.Promise); + if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } + var source = this; + return new promiseCtor(function (resolve, reject) { + // No cancellation can be done + var value, hasValue = false; + source.subscribe(function (v) { + value = v; + hasValue = true; + }, reject, function () { + hasValue && resolve(value); + }); + }); + }; + + var ToArrayObservable = (function(__super__) { + inherits(ToArrayObservable, __super__); + function ToArrayObservable(source) { + this.source = source; + __super__.call(this); + } + + ToArrayObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.a = []; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.o.onNext(this.a); + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return ToArrayObservable; + }(ObservableBase)); + + /** + * Creates an array from an observable sequence. + * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. + */ + observableProto.toArray = function () { + return new ToArrayObservable(this); + }; + + /** + * Creates an observable sequence from a specified subscribe method implementation. + * @example + * var res = Rx.Observable.create(function (observer) { return function () { } ); + * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); + * var res = Rx.Observable.create(function (observer) { } ); + * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. + * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. + */ + Observable.create = Observable.createWithDisposable = function (subscribe, parent) { + return new AnonymousObservable(subscribe, parent); + }; + + /** + * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + * + * @example + * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); + * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. + * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + var observableDefer = Observable.defer = function (observableFactory) { + return new AnonymousObservable(function (observer) { + var result; + try { + result = observableFactory(); + } catch (e) { + return observableThrow(e).subscribe(observer); + } + isPromise(result) && (result = observableFromPromise(result)); + return result.subscribe(observer); + }); + }; + + var EmptyObservable = (function(__super__) { + inherits(EmptyObservable, __super__); + function EmptyObservable(scheduler) { + this.scheduler = scheduler; + __super__.call(this); + } + + EmptyObservable.prototype.subscribeCore = function (observer) { + var sink = new EmptySink(observer, this); + return sink.run(); + }; + + function EmptySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + state.onCompleted(); + } + + EmptySink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); + }; + + return EmptyObservable; + }(ObservableBase)); + + /** + * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. + * + * @example + * var res = Rx.Observable.empty(); + * var res = Rx.Observable.empty(Rx.Scheduler.timeout); + * @param {Scheduler} [scheduler] Scheduler to send the termination call on. + * @returns {Observable} An observable sequence with no elements. + */ + var observableEmpty = Observable.empty = function (scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + return new EmptyObservable(scheduler); + }; + + var FromObservable = (function(__super__) { + inherits(FromObservable, __super__); + function FromObservable(iterable, mapper, scheduler) { + this.iterable = iterable; + this.mapper = mapper; + this.scheduler = scheduler; + __super__.call(this); + } + + FromObservable.prototype.subscribeCore = function (observer) { + var sink = new FromSink(observer, this); + return sink.run(); + }; + + return FromObservable; + }(ObservableBase)); + + var FromSink = (function () { + function FromSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromSink.prototype.run = function () { + var list = Object(this.parent.iterable), + it = getIterable(list), + observer = this.observer, + mapper = this.parent.mapper; + + function loopRecursive(i, recurse) { + try { + var next = it.next(); + } catch (e) { + return observer.onError(e); + } + if (next.done) { + return observer.onCompleted(); + } + + var result = next.value; + + if (mapper) { + try { + result = mapper(result, i); + } catch (e) { + return observer.onError(e); + } + } + + observer.onNext(result); + recurse(i + 1); + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return FromSink; + }()); + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function StringIterable(str) { + this._s = s; + } + + StringIterable.prototype[$iterator$] = function () { + return new StringIterator(this._s); + }; + + function StringIterator(str) { + this._s = s; + this._l = s.length; + this._i = 0; + } + + StringIterator.prototype[$iterator$] = function () { + return this; + }; + + StringIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; + }; + + function ArrayIterable(a) { + this._a = a; + } + + ArrayIterable.prototype[$iterator$] = function () { + return new ArrayIterator(this._a); + }; + + function ArrayIterator(a) { + this._a = a; + this._l = toLength(a); + this._i = 0; + } + + ArrayIterator.prototype[$iterator$] = function () { + return this; + }; + + ArrayIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; + }; + + function numberIsFinite(value) { + return typeof value === 'number' && root.isFinite(value); + } + + function isNan(n) { + return n !== n; + } + + function getIterable(o) { + var i = o[$iterator$], it; + if (!i && typeof o === 'string') { + it = new StringIterable(o); + return it[$iterator$](); + } + if (!i && o.length !== undefined) { + it = new ArrayIterable(o); + return it[$iterator$](); + } + if (!i) { throw new TypeError('Object is not iterable'); } + return o[$iterator$](); + } + + function sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; + } + + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { return 0; } + if (len === 0 || !numberIsFinite(len)) { return len; } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { return 0; } + if (len > maxSafeInteger) { return maxSafeInteger; } + return len; + } + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. + * @param {Function} [mapFn] Map function to call on every element of the array. + * @param {Any} [thisArg] The context to use calling the mapFn if provided. + * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { + if (iterable == null) { + throw new Error('iterable cannot be null.') + } + if (mapFn && !isFunction(mapFn)) { + throw new Error('mapFn when provided must be a function'); + } + if (mapFn) { + var mapper = bindCallback(mapFn, thisArg, 2); + } + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromObservable(iterable, mapper, scheduler); + } + + var FromArrayObservable = (function(__super__) { + inherits(FromArrayObservable, __super__); + function FromArrayObservable(args, scheduler) { + this.args = args; + this.scheduler = scheduler; + __super__.call(this); + } + + FromArrayObservable.prototype.subscribeCore = function (observer) { + var sink = new FromArraySink(observer, this); + return sink.run(); + }; + + return FromArrayObservable; + }(ObservableBase)); + + function FromArraySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + FromArraySink.prototype.run = function () { + var observer = this.observer, args = this.parent.args, len = args.length; + function loopRecursive(i, recurse) { + if (i < len) { + observer.onNext(args[i]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. + * @deprecated use Observable.from or Observable.of + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. + */ + var observableFromArray = Observable.fromArray = function (array, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler) + }; + + /** + * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. + * + * @example + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); + * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. + * @returns {Observable} The generated sequence. + */ + Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new AnonymousObservable(function (o) { + var first = true; + return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { + var hasResult, result; + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + hasResult && (result = resultSelector(state)); + } catch (e) { + return o.onError(e); + } + if (hasResult) { + o.onNext(result); + self(state); + } else { + o.onCompleted(); + } + }); + }); + }; + + function observableOf (scheduler, array) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler); + } + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.of = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + return new FromArrayObservable(args, currentThreadScheduler); + }; + + /** + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. + * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. + */ + Observable.ofWithScheduler = function (scheduler) { + var len = arguments.length, args = new Array(len - 1); + for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } + return new FromArrayObservable(args, scheduler); + }; + + /** + * Creates an Observable sequence from changes to an array using Array.observe. + * @param {Array} array An array to observe changes. + * @returns {Observable} An observable sequence containing changes to an array from Array.observe. + */ + Observable.ofArrayChanges = function(array) { + if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } + if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Array.observe(array, observerFn); + + return function () { + Array.unobserve(array, observerFn); + }; + }); + }; + + /** + * Creates an Observable sequence from changes to an object using Object.observe. + * @param {Object} obj An object to observe changes. + * @returns {Observable} An observable sequence containing changes to an object from Object.observe. + */ + Observable.ofObjectChanges = function(obj) { + if (obj == null) { throw new TypeError('object must not be null or undefined.'); } + if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } + return new AnonymousObservable(function(observer) { + function observerFn(changes) { + for(var i = 0, len = changes.length; i < len; i++) { + observer.onNext(changes[i]); + } + } + + Object.observe(obj, observerFn); + + return function () { + Object.unobserve(obj, observerFn); + }; + }); + }; + + var NeverObservable = (function(__super__) { + inherits(NeverObservable, __super__); + function NeverObservable() { + __super__.call(this); + } + + NeverObservable.prototype.subscribeCore = function (observer) { + return disposableEmpty; + }; + + return NeverObservable; + }(ObservableBase)); + + /** + * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). + * @returns {Observable} An observable sequence whose observers will never get called. + */ + var observableNever = Observable.never = function () { + return new NeverObservable(); + }; + + var PairsObservable = (function(__super__) { + inherits(PairsObservable, __super__); + function PairsObservable(obj, scheduler) { + this.obj = obj; + this.keys = Object.keys(obj); + this.scheduler = scheduler; + __super__.call(this); + } + + PairsObservable.prototype.subscribeCore = function (observer) { + var sink = new PairsSink(observer, this); + return sink.run(); + }; + + return PairsObservable; + }(ObservableBase)); + + function PairsSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + PairsSink.prototype.run = function () { + var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; + function loopRecursive(i, recurse) { + if (i < len) { + var key = keys[i]; + observer.onNext([key, obj[key]]); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + /** + * Convert an object into an observable sequence of [key, value] pairs. + * @param {Object} obj The object to inspect. + * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. + * @returns {Observable} An observable sequence of [key, value] pairs from the object. + */ + Observable.pairs = function (obj, scheduler) { + scheduler || (scheduler = currentThreadScheduler); + return new PairsObservable(obj, scheduler); + }; + + var RangeObservable = (function(__super__) { + inherits(RangeObservable, __super__); + function RangeObservable(start, count, scheduler) { + this.start = start; + this.rangeCount = count; + this.scheduler = scheduler; + __super__.call(this); + } + + RangeObservable.prototype.subscribeCore = function (observer) { + var sink = new RangeSink(observer, this); + return sink.run(); + }; + + return RangeObservable; + }(ObservableBase)); + + var RangeSink = (function () { + function RangeSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RangeSink.prototype.run = function () { + var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer; + function loopRecursive(i, recurse) { + if (i < count) { + observer.onNext(start + i); + recurse(i + 1); + } else { + observer.onCompleted(); + } + } + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + + return RangeSink; + }()); + + /** + * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. + * @param {Number} start The value of the first integer in the sequence. + * @param {Number} count The number of sequential integers to generate. + * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. + * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. + */ + Observable.range = function (start, count, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RangeObservable(start, count, scheduler); + }; + + var RepeatObservable = (function(__super__) { + inherits(RepeatObservable, __super__); + function RepeatObservable(value, repeatCount, scheduler) { + this.value = value; + this.repeatCount = repeatCount == null ? -1 : repeatCount; + this.scheduler = scheduler; + __super__.call(this); + } + + RepeatObservable.prototype.subscribeCore = function (observer) { + var sink = new RepeatSink(observer, this); + return sink.run(); + }; + + return RepeatObservable; + }(ObservableBase)); + + function RepeatSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + RepeatSink.prototype.run = function () { + var observer = this.observer, value = this.parent.value; + function loopRecursive(i, recurse) { + if (i === -1 || i > 0) { + observer.onNext(value); + i > 0 && i--; + } + if (i === 0) { return observer.onCompleted(); } + recurse(i); + } + + return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); + }; + + /** + * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. + * @param {Mixed} value Element to repeat. + * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. + * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. + * @returns {Observable} An observable sequence that repeats the given element the specified number of times. + */ + Observable.repeat = function (value, repeatCount, scheduler) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new RepeatObservable(value, repeatCount, scheduler); + }; + + var JustObservable = (function(__super__) { + inherits(JustObservable, __super__); + function JustObservable(value, scheduler) { + this.value = value; + this.scheduler = scheduler; + __super__.call(this); + } + + JustObservable.prototype.subscribeCore = function (observer) { + var sink = new JustSink(observer, this); + return sink.run(); + }; + + function JustSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } + + function scheduleItem(s, state) { + var value = state[0], observer = state[1]; + observer.onNext(value); + observer.onCompleted(); + } + + JustSink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); + }; + + return JustObservable; + }(ObservableBase)); + + /** + * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. + * There is an alias called 'just' or browsers 0) { + parent.handleSubscribe(parent.q.shift()); + } else { + parent.activeCount--; + parent.done && parent.activeCount === 0 && parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeObserver; + }()); + + + + + + /** + * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. + * Or merges two observable sequences into a single observable sequence. + * + * @example + * 1 - merged = sources.merge(1); + * 2 - merged = source.merge(otherSource); + * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.merge = function (maxConcurrentOrOther) { + return typeof maxConcurrentOrOther !== 'number' ? + observableMerge(this, maxConcurrentOrOther) : + new MergeObservable(this, maxConcurrentOrOther); + }; + + /** + * Merges all the observable sequences into a single observable sequence. + * The scheduler is optional and if not specified, the immediate scheduler is used. + * @returns {Observable} The observable sequence that merges the elements of the observable sequences. + */ + var observableMerge = Observable.merge = function () { + var scheduler, sources = [], i, len = arguments.length; + if (!arguments[0]) { + scheduler = immediateScheduler; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else if (isScheduler(arguments[0])) { + scheduler = arguments[0]; + for(i = 1; i < len; i++) { sources.push(arguments[i]); } + } else { + scheduler = immediateScheduler; + for(i = 0; i < len; i++) { sources.push(arguments[i]); } + } + if (Array.isArray(sources[0])) { + sources = sources[0]; + } + return observableOf(scheduler, sources).mergeAll(); + }; + + var MergeAllObservable = (function (__super__) { + inherits(MergeAllObservable, __super__); + + function MergeAllObservable(source) { + this.source = source; + __super__.call(this); + } + + MergeAllObservable.prototype.subscribeCore = function (observer) { + var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); + g.add(m); + m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); + return g; + }; + + function MergeAllObserver(o, g) { + this.o = o; + this.g = g; + this.isStopped = false; + this.done = false; + } + MergeAllObserver.prototype.onNext = function(innerSource) { + if(this.isStopped) { return; } + var sad = new SingleAssignmentDisposable(); + this.g.add(sad); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); + }; + MergeAllObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + MergeAllObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.done = true; + this.g.length === 1 && this.o.onCompleted(); + } + }; + MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; + MergeAllObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + function InnerObserver(parent, g, sad) { + this.parent = parent; + this.g = g; + this.sad = sad; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + var parent = this.parent; + this.isStopped = true; + parent.g.remove(this.sad); + parent.done && parent.g.length === 1 && parent.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + + return false; + }; + + return MergeAllObservable; + }(ObservableBase)); + + /** + * Merges an observable sequence of observable sequences into an observable sequence. + * @returns {Observable} The observable sequence that merges the elements of the inner sequences. + */ + observableProto.mergeAll = observableProto.mergeObservable = function () { + return new MergeAllObservable(this); + }; + + var CompositeError = Rx.CompositeError = function(errors) { + this.name = "NotImplementedError"; + this.innerErrors = errors; + this.message = 'This contains multiple errors. Check the innerErrors'; + Error.call(this); + } + CompositeError.prototype = Error.prototype; + + /** + * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to + * receive all successfully emitted items from all of the source Observables without being interrupted by + * an error notification from one of them. + * + * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an + * error via the Observer's onError, mergeDelayError will refrain from propagating that + * error notification until all of the merged Observables have finished emitting items. + * @param {Array | Arguments} args Arguments or an array to merge. + * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable + */ + Observable.mergeDelayError = function() { + var args; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + } else { + var len = arguments.length; + args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + } + var source = observableOf(null, args); + + return new AnonymousObservable(function (o) { + var group = new CompositeDisposable(), + m = new SingleAssignmentDisposable(), + isStopped = false, + errors = []; + + function setCompletion() { + if (errors.length === 0) { + o.onCompleted(); + } else if (errors.length === 1) { + o.onError(errors[0]); + } else { + o.onError(new CompositeError(errors)); + } + } + + group.add(m); + + m.setDisposable(source.subscribe( + function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); + + // Check for promises support + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { o.onNext(x); }, + function (e) { + errors.push(e); + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + }, + function () { + group.remove(innerSubscription); + isStopped && group.length === 1 && setCompletion(); + })); + }, + function (e) { + errors.push(e); + isStopped = true; + group.length === 1 && setCompletion(); + }, + function () { + isStopped = true; + group.length === 1 && setCompletion(); + })); + return group; + }); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. + * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. + */ + observableProto.onErrorResumeNext = function (second) { + if (!second) { throw new Error('Second observable is required'); } + return onErrorResumeNext([this, second]); + }; + + /** + * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. + * + * @example + * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); + * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); + * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. + */ + var onErrorResumeNext = Observable.onErrorResumeNext = function () { + var sources = []; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } + } + return new AnonymousObservable(function (observer) { + var pos = 0, subscription = new SerialDisposable(), + cancelable = immediateScheduler.scheduleRecursive(function (self) { + var current, d; + if (pos < sources.length) { + current = sources[pos++]; + isPromise(current) && (current = observableFromPromise(current)); + d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); + } else { + observer.onCompleted(); + } + }); + return new CompositeDisposable(subscription, cancelable); + }); + }; + + /** + * Returns the values from the source observable sequence only after the other observable sequence produces a value. + * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. + */ + observableProto.skipUntil = function (other) { + var source = this; + return new AnonymousObservable(function (o) { + var isOpen = false; + var disposables = new CompositeDisposable(source.subscribe(function (left) { + isOpen && o.onNext(left); + }, function (e) { o.onError(e); }, function () { + isOpen && o.onCompleted(); + })); + + isPromise(other) && (other = observableFromPromise(other)); + + var rightSubscription = new SingleAssignmentDisposable(); + disposables.add(rightSubscription); + rightSubscription.setDisposable(other.subscribe(function () { + isOpen = true; + rightSubscription.dispose(); + }, function (e) { o.onError(e); }, function () { + rightSubscription.dispose(); + })); + + return disposables; + }, source); + }; + + var SwitchObservable = (function(__super__) { + inherits(SwitchObservable, __super__); + function SwitchObservable(source) { + this.source = source; + __super__.call(this); + } + + SwitchObservable.prototype.subscribeCore = function (o) { + var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); + return new CompositeDisposable(s, inner); + }; + + function SwitchObserver(o, inner) { + this.o = o; + this.inner = inner; + this.stopped = false; + this.latest = 0; + this.hasLatest = false; + this.isStopped = false; + } + SwitchObserver.prototype.onNext = function (innerSource) { + if (this.isStopped) { return; } + var d = new SingleAssignmentDisposable(), id = ++this.latest; + this.hasLatest = true; + this.inner.setDisposable(d); + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); + }; + SwitchObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + SwitchObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.stopped = true; + !this.hasLatest && this.o.onCompleted(); + } + }; + SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; + SwitchObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + function InnerObserver(parent, id) { + this.parent = parent; + this.id = id; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.parent.latest === this.id && this.parent.o.onNext(x); + }; + InnerObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.parent.latest === this.id && this.parent.o.onError(e); + } + }; + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + if (this.parent.latest === this.id) { + this.parent.hasLatest = false; + this.parent.isStopped && this.parent.o.onCompleted(); + } + } + }; + InnerObserver.prototype.dispose = function () { this.isStopped = true; } + InnerObserver.prototype.fail = function (e) { + if(!this.isStopped) { + this.isStopped = true; + this.parent.o.onError(e); + return true; + } + return false; + }; + + return SwitchObservable; + }(ObservableBase)); + + /** + * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto['switch'] = observableProto.switchLatest = function () { + return new SwitchObservable(this); + }; + + var TakeUntilObservable = (function(__super__) { + inherits(TakeUntilObservable, __super__); + + function TakeUntilObservable(source, other) { + this.source = source; + this.other = isPromise(other) ? observableFromPromise(other) : other; + __super__.call(this); + } + + TakeUntilObservable.prototype.subscribeCore = function(o) { + return new CompositeDisposable( + this.source.subscribe(o), + this.other.subscribe(new InnerObserver(o)) + ); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + this.o.onCompleted(); + }; + InnerObserver.prototype.onError = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + !this.isStopped && (this.isStopped = true); + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TakeUntilObservable; + }(ObservableBase)); + + /** + * Returns the values from the source observable sequence until the other observable sequence produces a value. + * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. + * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + observableProto.takeUntil = function (other) { + return new TakeUntilObservable(this, other); + }; + + function falseFactory() { return false; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.withLatestFrom = function () { + var len = arguments.length, args = new Array(len) + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var resultSelector = args.pop(), source = this; + Array.isArray(args[0]) && (args = args[0]); + + return new AnonymousObservable(function (observer) { + var n = args.length, + hasValue = arrayInitialize(n, falseFactory), + hasValueAll = false, + values = new Array(n); + + var subscriptions = new Array(n + 1); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var other = args[i], sad = new SingleAssignmentDisposable(); + isPromise(other) && (other = observableFromPromise(other)); + sad.setDisposable(other.subscribe(function (x) { + values[i] = x; + hasValue[i] = true; + hasValueAll = hasValue.every(identity); + }, function (e) { observer.onError(e); }, noop)); + subscriptions[i] = sad; + }(idx)); + } + + var sad = new SingleAssignmentDisposable(); + sad.setDisposable(source.subscribe(function (x) { + var allValues = [x].concat(values); + if (!hasValueAll) { return; } + var res = tryCatch(resultSelector).apply(null, allValues); + if (res === errorObj) { return observer.onError(res.e); } + observer.onNext(res); + }, function (e) { observer.onError(e); }, function () { + observer.onCompleted(); + })); + subscriptions[n] = sad; + + return new CompositeDisposable(subscriptions); + }, this); + }; + + function zipArray(second, resultSelector) { + var first = this; + return new AnonymousObservable(function (o) { + var index = 0, len = second.length; + return first.subscribe(function (left) { + if (index < len) { + var right = second[index++], res = tryCatch(resultSelector)(left, right); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, first); + } + + function falseFactory() { return false; } + function emptyArrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. + * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. + * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. + */ + observableProto.zip = function () { + if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + + var parent = this, resultSelector = args.pop(); + args.unshift(parent); + return new AnonymousObservable(function (o) { + var n = args.length, + queues = arrayInitialize(n, emptyArrayFactory), + isDone = arrayInitialize(n, falseFactory); + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + var source = args[i], sad = new SingleAssignmentDisposable(); + isPromise(source) && (source = observableFromPromise(source)); + sad.setDisposable(source.subscribe(function (x) { + queues[i].push(x); + if (queues.every(function (x) { return x.length > 0; })) { + var queuedValues = queues.map(function (x) { return x.shift(); }), + res = tryCatch(resultSelector).apply(parent, queuedValues); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + subscriptions[i] = sad; + })(idx); + } + + return new CompositeDisposable(subscriptions); + }, parent); + }; + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + * @param arguments Observable sources. + * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + Observable.zip = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var first = args.shift(); + return first.zip.apply(first, args); + }; + + function falseFactory() { return false; } + function arrayFactory() { return []; } + + /** + * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. + * @param arguments Observable sources. + * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. + */ + Observable.zipArray = function () { + var sources; + if (Array.isArray(arguments[0])) { + sources = arguments[0]; + } else { + var len = arguments.length; + sources = new Array(len); + for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var n = sources.length, + queues = arrayInitialize(n, arrayFactory), + isDone = arrayInitialize(n, falseFactory); + + var subscriptions = new Array(n); + for (var idx = 0; idx < n; idx++) { + (function (i) { + subscriptions[i] = new SingleAssignmentDisposable(); + subscriptions[i].setDisposable(sources[i].subscribe(function (x) { + queues[i].push(x); + if (queues.every(function (x) { return x.length > 0; })) { + var res = queues.map(function (x) { return x.shift(); }); + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + return o.onCompleted(); + } + }, function (e) { o.onError(e); }, function () { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + })); + })(idx); + } + + return new CompositeDisposable(subscriptions); + }); + }; + + /** + * Hides the identity of an observable sequence. + * @returns {Observable} An observable sequence that hides the identity of the source sequence. + */ + observableProto.asObservable = function () { + var source = this; + return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. + * + * @example + * var res = xs.bufferWithCount(10); + * var res = xs.bufferWithCount(10, 1); + * @param {Number} count Length of each buffer. + * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithCount = function (count, skip) { + if (typeof skip !== 'number') { + skip = count; + } + return this.windowWithCount(count, skip).selectMany(function (x) { + return x.toArray(); + }).where(function (x) { + return x.length > 0; + }); + }; + + /** + * Dematerializes the explicit notification values of an observable sequence as implicit notifications. + * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. + */ + observableProto.dematerialize = function () { + var source = this; + return new AnonymousObservable(function (o) { + return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + * + * var obs = observable.distinctUntilChanged(); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); + * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); + * + * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. + * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. + * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + observableProto.distinctUntilChanged = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hasCurrentKey = false, currentKey; + return source.subscribe(function (value) { + var key = value; + if (keySelector) { + key = tryCatch(keySelector)(value); + if (key === errorObj) { return o.onError(key.e); } + } + if (hasCurrentKey) { + var comparerEquals = tryCatch(comparer)(currentKey, key); + if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } + } + if (!hasCurrentKey || !comparerEquals) { + hasCurrentKey = true; + currentKey = key; + o.onNext(value); + } + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + var TapObservable = (function(__super__) { + inherits(TapObservable,__super__); + function TapObservable(source, observerOrOnNext, onError, onCompleted) { + this.source = source; + this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? + observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : + observerOrOnNext; + __super__.call(this); + } + + TapObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o, this.t)); + }; + + function InnerObserver(o, t) { + this.o = o; + this.t = t; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var res = tryCatch(this.t.onNext).call(this.t, x); + if (res === errorObj) { this.o.onError(res.e); } + this.o.onNext(x); + }; + InnerObserver.prototype.onError = function(err) { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onError).call(this.t, err); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { + this.isStopped = true; + var res = tryCatch(this.t.onCompleted).call(this.t); + if (res === errorObj) { return this.o.onError(res.e); } + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return TapObservable; + }(ObservableBase)); + + /** + * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. + * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { + return new TapObservable(this, observerOrOnNext, onError, onCompleted); + }; + + /** + * Invokes an action for each element in the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onNext Action to invoke for each element in the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { + return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); + }; + + /** + * Invokes an action upon exceptional termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { + return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); + }; + + /** + * Invokes an action upon graceful termination of the observable sequence. + * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. + * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} The source sequence with the side-effecting behavior applied. + */ + observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { + return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); + }; + + /** + * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. + * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. + * @returns {Observable} Source sequence with the action-invoking termination behavior applied. + */ + observableProto['finally'] = observableProto.ensure = function (action) { + var source = this; + return new AnonymousObservable(function (observer) { + var subscription; + try { + subscription = source.subscribe(observer); + } catch (e) { + action(); + throw e; + } + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }, this); + }; + + /** + * @deprecated use #finally or #ensure instead. + */ + observableProto.finallyAction = function (action) { + //deprecate('finallyAction', 'finally or ensure'); + return this.ensure(action); + }; + + var IgnoreElementsObservable = (function(__super__) { + inherits(IgnoreElementsObservable, __super__); + + function IgnoreElementsObservable(source) { + this.source = source; + __super__.call(this); + } + + IgnoreElementsObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o)); + }; + + function InnerObserver(o) { + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = noop; + InnerObserver.prototype.onError = function (err) { + if(!this.isStopped) { + this.isStopped = true; + this.o.onError(err); + } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.o.onCompleted(); + } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + + return false; + }; + + return IgnoreElementsObservable; + }(ObservableBase)); + + /** + * Ignores all elements in an observable sequence leaving only the termination messages. + * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. + */ + observableProto.ignoreElements = function () { + return new IgnoreElementsObservable(this); + }; + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. + */ + observableProto.materialize = function () { + var source = this; + return new AnonymousObservable(function (observer) { + return source.subscribe(function (value) { + observer.onNext(notificationCreateOnNext(value)); + }, function (e) { + observer.onNext(notificationCreateOnError(e)); + observer.onCompleted(); + }, function () { + observer.onNext(notificationCreateOnCompleted()); + observer.onCompleted(); + }); + }, source); + }; + + /** + * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. + * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. + * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. + */ + observableProto.repeat = function (repeatCount) { + return enumerableRepeat(this, repeatCount).concat(); + }; + + /** + * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. + * Note if you encounter an error and want it to retry once, then you must use .retry(2); + * + * @example + * var res = retried = retry.repeat(); + * var res = retried = retry.repeat(2); + * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retry = function (retryCount) { + return enumerableRepeat(this, retryCount).catchError(); + }; + + /** + * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. + * if the notifier completes, the observable sequence completes. + * + * @example + * var timer = Observable.timer(500); + * var source = observable.retryWhen(timer); + * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. + * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + observableProto.retryWhen = function (notifier) { + return enumerableRepeat(this).catchErrorWhen(notifier); + }; + var ScanObservable = (function(__super__) { + inherits(ScanObservable, __super__); + function ScanObservable(source, accumulator, hasSeed, seed) { + this.source = source; + this.accumulator = accumulator; + this.hasSeed = hasSeed; + this.seed = seed; + __super__.call(this); + } + + ScanObservable.prototype.subscribeCore = function(observer) { + return this.source.subscribe(new ScanObserver(observer,this)); + }; + + return ScanObservable; + }(ObservableBase)); + + function ScanObserver(observer, parent) { + this.observer = observer; + this.accumulator = parent.accumulator; + this.hasSeed = parent.hasSeed; + this.seed = parent.seed; + this.hasAccumulation = false; + this.accumulation = null; + this.hasValue = false; + this.isStopped = false; + } + ScanObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + !this.hasValue && (this.hasValue = true); + try { + if (this.hasAccumulation) { + this.accumulation = this.accumulator(this.accumulation, x); + } else { + this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; + this.hasAccumulation = true; + } + } catch (e) { + return this.observer.onError(e); + } + this.observer.onNext(this.accumulation); + }; + ScanObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + } + }; + ScanObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); + this.observer.onCompleted(); + } + }; + ScanObserver.prototype.dispose = function() { this.isStopped = true; }; + ScanObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } + return false; + }; + + /** + * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. + * For aggregation behavior with no intermediate results, see Observable.aggregate. + * @param {Mixed} [seed] The initial accumulator value. + * @param {Function} accumulator An accumulator function to be invoked on each element. + * @returns {Observable} An observable sequence containing the accumulated values. + */ + observableProto.scan = function () { + var hasSeed = false, seed, accumulator, source = this; + if (arguments.length === 2) { + hasSeed = true; + seed = arguments[0]; + accumulator = arguments[1]; + } else { + accumulator = arguments[0]; + } + return new ScanObservable(this, accumulator, hasSeed, seed); + }; + + /** + * Bypasses a specified number of elements at the end of an observable sequence. + * @description + * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are + * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. + * @param count Number of elements to bypass at the end of the source sequence. + * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. + */ + observableProto.skipLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && o.onNext(q.shift()); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. + * @example + * var res = source.startWith(1, 2, 3); + * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); + * @param {Arguments} args The specified values to prepend to the observable sequence + * @returns {Observable} The source sequence prepended with the specified values. + */ + observableProto.startWith = function () { + var values, scheduler, start = 0; + if (!!arguments.length && isScheduler(arguments[0])) { + scheduler = arguments[0]; + start = 1; + } else { + scheduler = immediateScheduler; + } + for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } + return enumerableOf([observableFromArray(args, scheduler), this]).concat(); + }; + + /** + * Returns a specified number of contiguous elements from the end of an observable sequence. + * @description + * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of + * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. + */ + observableProto.takeLast = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + while (q.length > 0) { o.onNext(q.shift()); } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns an array with the specified number of contiguous elements from the end of an observable sequence. + * + * @description + * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the + * source sequence, this buffer is produced on the result sequence. + * @param {Number} count Number of elements to take from the end of the source sequence. + * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. + */ + observableProto.takeLastBuffer = function (count) { + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + q.push(x); + q.length > count && q.shift(); + }, function (e) { o.onError(e); }, function () { + o.onNext(q); + o.onCompleted(); + }); + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. + * + * var res = xs.windowWithCount(10); + * var res = xs.windowWithCount(10, 1); + * @param {Number} count Length of each window. + * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithCount = function (count, skip) { + var source = this; + +count || (count = 0); + Math.abs(count) === Infinity && (count = 0); + if (count <= 0) { throw new ArgumentOutOfRangeError(); } + skip == null && (skip = count); + +skip || (skip = 0); + Math.abs(skip) === Infinity && (skip = 0); + + if (skip <= 0) { throw new ArgumentOutOfRangeError(); } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = []; + + function createWindow () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + + createWindow(); + + m.setDisposable(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + var c = n - count + 1; + c >= 0 && c % skip === 0 && q.shift().onCompleted(); + ++n % skip === 0 && createWindow(); + }, + function (e) { + while (q.length > 0) { q.shift().onError(e); } + observer.onError(e); + }, + function () { + while (q.length > 0) { q.shift().onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + function concatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).concatAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the + * source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.concatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }); + } + return isFunction(selector) ? + concatMap(this, selector, thisArg) : + concatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { + var source = this, + onNextFunc = bindCallback(onNext, thisArg, 2), + onErrorFunc = bindCallback(onError, thisArg, 1), + onCompletedFunc = bindCallback(onCompleted, thisArg, 0); + return new AnonymousObservable(function (observer) { + var index = 0; + return source.subscribe( + function (x) { + var result; + try { + result = onNextFunc(x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onErrorFunc(err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompletedFunc(); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, this).concatAll(); + }; + + /** + * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. + * + * var res = obs = xs.defaultIfEmpty(); + * 2 - obs = xs.defaultIfEmpty(false); + * + * @memberOf Observable# + * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. + * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. + */ + observableProto.defaultIfEmpty = function (defaultValue) { + var source = this; + defaultValue === undefined && (defaultValue = null); + return new AnonymousObservable(function (observer) { + var found = false; + return source.subscribe(function (x) { + found = true; + observer.onNext(x); + }, + function (e) { observer.onError(e); }, + function () { + !found && observer.onNext(defaultValue); + observer.onCompleted(); + }); + }, source); + }; + + // Swap out for Array.findIndex + function arrayIndexOfComparer(array, item, comparer) { + for (var i = 0, len = array.length; i < len; i++) { + if (comparer(array[i], item)) { return i; } + } + return -1; + } + + function HashSet(comparer) { + this.comparer = comparer; + this.set = []; + } + HashSet.prototype.push = function(value) { + var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; + retValue && this.set.push(value); + return retValue; + }; + + /** + * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. + * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. + * + * @example + * var res = obs = xs.distinct(); + * 2 - obs = xs.distinct(function (x) { return x.id; }); + * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); + * @param {Function} [keySelector] A function to compute the comparison key for each element. + * @param {Function} [comparer] Used to compare items in the collection. + * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. + */ + observableProto.distinct = function (keySelector, comparer) { + var source = this; + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (o) { + var hashSet = new HashSet(comparer); + return source.subscribe(function (x) { + var key = x; + + if (keySelector) { + try { + key = keySelector(x); + } catch (e) { + o.onError(e); + return; + } + } + hashSet.push(key) && o.onNext(x); + }, + function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, this); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. + * + * @example + * var res = observable.groupBy(function (x) { return x.id; }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. + * @param {Function} [comparer] Used to determine whether the objects are equal. + * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + observableProto.groupBy = function (keySelector, elementSelector, comparer) { + return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); + }; + + /** + * Groups the elements of an observable sequence according to a specified key selector function. + * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same + * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. + * + * @example + * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); + * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); + * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); + * @param {Function} keySelector A function to extract the key for each element. + * @param {Function} durationSelector A function to signal the expiration of a group. + * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. + * @returns {Observable} + * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. + * + */ + observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { + var source = this; + elementSelector || (elementSelector = identity); + comparer || (comparer = defaultComparer); + return new AnonymousObservable(function (observer) { + function handleError(e) { return function (item) { item.onError(e); }; } + var map = new Dictionary(0, comparer), + groupDisposable = new CompositeDisposable(), + refCountDisposable = new RefCountDisposable(groupDisposable); + + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } + + if (fireNewMapEntry) { + var group = new GroupedObservable(key, writer, refCountDisposable), + durationGroup = new GroupedObservable(key, writer); + try { + duration = durationSelector(durationGroup); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + observer.onNext(group); + + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); + + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; + + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } + + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); + + return refCountDisposable; + }, source); + }; + + var MapObservable = (function (__super__) { + inherits(MapObservable, __super__); + + function MapObservable(source, selector, thisArg) { + this.source = source; + this.selector = bindCallback(selector, thisArg, 3); + __super__.call(this); + } + + function innerMap(selector, self) { + return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } + } + + MapObservable.prototype.internalMap = function (selector, thisArg) { + return new MapObservable(this.source, innerMap(selector, this), thisArg); + }; + + MapObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.selector, this)); + }; + + function InnerObserver(o, selector, source) { + this.o = o; + this.selector = selector; + this.source = source; + this.i = 0; + this.isStopped = false; + } + + InnerObserver.prototype.onNext = function(x) { + if (this.isStopped) { return; } + var result = tryCatch(this.selector)(x, this.i++, this.source); + if (result === errorObj) { + return this.o.onError(result.e); + } + this.o.onNext(result); + }; + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + + return false; + }; + + return MapObservable; + + }(ObservableBase)); + + /** + * Projects each element of an observable sequence into a new form by incorporating the element's index. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + observableProto.map = observableProto.select = function (selector, thisArg) { + var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; + return this instanceof MapObservable ? + this.internalMap(selectorFn, thisArg) : + new MapObservable(this, selectorFn, thisArg); + }; + + /** + * Retrieves the value of a specified nested property from all elements in + * the Observable sequence. + * @param {Arguments} arguments The nested properties to pluck. + * @returns {Observable} Returns a new Observable sequence of property values. + */ + observableProto.pluck = function () { + var args = arguments, len = arguments.length; + if (len === 0) { throw new Error('List of properties cannot be empty.'); } + return this.map(function (x) { + var currentProp = x; + for (var i = 0; i < len; i++) { + var p = currentProp[args[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } else { + return undefined; + } + } + return currentProp; + }); + }; + + function flatMap(source, selector, thisArg) { + var selectorFunc = bindCallback(selector, thisArg, 3); + return source.map(function (x, i) { + var result = selectorFunc(x, i, source); + isPromise(result) && (result = observableFromPromise(result)); + (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); + return result; + }).mergeAll(); + } + + /** + * One of the Following: + * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * + * @example + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); + * Or: + * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. + * + * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); + * Or: + * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. + * + * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); + * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. + * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. + */ + observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { + if (isFunction(selector) && isFunction(resultSelector)) { + return this.flatMap(function (x, i) { + var selectorResult = selector(x, i); + isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); + (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); + + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); + }, thisArg); + } + return isFunction(selector) ? + flatMap(this, selector, thisArg) : + flatMap(this, function () { return selector; }); + }; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { + var source = this; + return new AnonymousObservable(function (observer) { + var index = 0; + + return source.subscribe( + function (x) { + var result; + try { + result = onNext.call(thisArg, x, index++); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + }, + function (err) { + var result; + try { + result = onError.call(thisArg, err); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }, + function () { + var result; + try { + result = onCompleted.call(thisArg); + } catch (e) { + observer.onError(e); + return; + } + isPromise(result) && (result = observableFromPromise(result)); + observer.onNext(result); + observer.onCompleted(); + }); + }, source).mergeAll(); + }; + + /** + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { + return this.select(selector, thisArg).switchLatest(); + }; + + var SkipObservable = (function(__super__) { + inherits(SkipObservable, __super__); + function SkipObservable(source, count) { + this.source = source; + this.skipCount = count; + __super__.call(this); + } + + SkipObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.skipCount)); + }; + + function InnerObserver(o, c) { + this.c = c; + this.r = c; + this.o = o; + this.isStopped = false; + } + InnerObserver.prototype.onNext = function (x) { + if (this.isStopped) { return; } + if (this.r <= 0) { + this.o.onNext(x); + } else { + this.r--; + } + }; + InnerObserver.prototype.onError = function(e) { + if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } + }; + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function(e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } + return false; + }; + + return SkipObservable; + }(ObservableBase)); + + /** + * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + * @param {Number} count The number of elements to skip before returning the remaining elements. + * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + observableProto.skip = function (count) { + if (count < 0) { throw new ArgumentOutOfRangeError(); } + return new SkipObservable(this, count); + }; + /** + * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + * The element's index is used in the logic of the predicate function. + * + * var res = source.skipWhile(function (value) { return value < 10; }); + * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); + * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. + * @param {Any} [thisArg] Object to use as this when executing callback. + * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + observableProto.skipWhile = function (predicate, thisArg) { + var source = this, + callback = bindCallback(predicate, thisArg, 3); + return new AnonymousObservable(function (o) { + var i = 0, running = false; + return source.subscribe(function (x) { + if (!running) { + try { + running = !callback(x, i++, source); + } catch (e) { + o.onError(e); + return; + } + } + running && o.onNext(x); + }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); + }, source); + }; + + /** + * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). + * + * var res = source.take(5); + * var res = source.take(0, Rx.Scheduler.timeout); + * @param {Number} count The number of elements to return. + * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.exception = null; + } + }); + + return BehaviorSubject; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. + */ + var ReplaySubject = Rx.ReplaySubject = (function (__super__) { + + var maxSafeInteger = Math.pow(2, 53) - 1; + + function createRemovableDisposable(subject, observer) { + return disposableCreate(function () { + observer.dispose(); + !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); + }); + } + + function subscribe(observer) { + var so = new ScheduledObserver(this.scheduler, observer), + subscription = createRemovableDisposable(this, so); + checkDisposed(this); + this._trim(this.scheduler.now()); + this.observers.push(so); + + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } + + if (this.hasError) { + so.onError(this.error); + } else if (this.isStopped) { + so.onCompleted(); + } + + so.ensureActive(); + return subscription; + } + + inherits(ReplaySubject, __super__); + + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; + this.windowSize = windowSize == null ? maxSafeInteger : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + __super__.call(this, subscribe); + } + + addProperties(ReplaySubject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + return this.observers.length > 0; + }, + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onNext(value); + observer.ensureActive(); + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + + function ConnectableObservable(source, subject) { + var hasSubscription = false, + subscription, + sourceObservable = source.asObservable(); + + this.connect = function () { + if (!hasSubscription) { + hasSubscription = true; + subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { + hasSubscription = false; + })); + } + return subscription; + }; + + __super__.call(this, function (o) { return subject.subscribe(o); }); + } + + ConnectableObservable.prototype.refCount = function () { + var connectableSubscription, count = 0, source = this; + return new AnonymousObservable(function (observer) { + var shouldConnect = ++count === 1, + subscription = source.subscribe(observer); + shouldConnect && (connectableSubscription = source.connect()); + return function () { + subscription.dispose(); + --count === 0 && connectableSubscription.dispose(); + }; + }); + }; + + return ConnectableObservable; + }(Observable)); + + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence + * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. + */ + observableProto.singleInstance = function() { + var source = this, hasObservable = false, observable; + + function getObservable() { + if (!hasObservable) { + hasObservable = true; + observable = source.finally(function() { hasObservable = false; }).publish().refCount(); + } + return observable; + }; + + return new AnonymousObservable(function(o) { + return getObservable().subscribe(o); + }); + }; + + var Dictionary = (function () { + + var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], + noSuchkey = "no such key", + duplicatekey = "duplicate key"; + + function isPrime(candidate) { + if ((candidate & 1) === 0) { return candidate === 2; } + var num1 = Math.sqrt(candidate), + num2 = 3; + while (num2 <= num1) { + if (candidate % num2 === 0) { return false; } + num2 += 2; + } + return true; + } + + function getPrime(min) { + var index, num, candidate; + for (index = 0; index < primes.length; ++index) { + num = primes[index]; + if (num >= min) { return num; } + } + candidate = min | 1; + while (candidate < primes[primes.length - 1]) { + if (isPrime(candidate)) { return candidate; } + candidate += 2; + } + return min; + } + + function stringHashFn(str) { + var hash = 757602046; + if (!str.length) { return hash; } + for (var i = 0, len = str.length; i < len; i++) { + var character = str.charCodeAt(i); + hash = ((hash << 5) - hash) + character; + hash = hash & hash; + } + return hash; + } + + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + var getHashCode = (function () { + var uniqueIdCounter = 0; + + return function (obj) { + if (obj == null) { throw new Error(noSuchkey); } + + // Check for built-ins before tacking on our own for any object + if (typeof obj === 'string') { return stringHashFn(obj); } + if (typeof obj === 'number') { return numberHashFn(obj); } + if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } + if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } + if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } + if (typeof obj.valueOf === 'function') { + // Hack check for valueOf + var valueOf = obj.valueOf(); + if (typeof valueOf === 'number') { return numberHashFn(valueOf); } + if (typeof valueOf === 'string') { return stringHashFn(valueOf); } + } + if (obj.hashCode) { return obj.hashCode(); } + + var id = 17 * uniqueIdCounter++; + obj.hashCode = function () { return id; }; + return id; + }; + }()); + + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } + + function Dictionary(capacity, comparer) { + if (capacity < 0) { throw new ArgumentOutOfRangeError(); } + if (capacity > 0) { this._initialize(capacity); } + + this.comparer = comparer || defaultComparer; + this.freeCount = 0; + this.size = 0; + this.freeList = -1; + } + + var dictionaryProto = Dictionary.prototype; + + dictionaryProto._initialize = function (capacity) { + var prime = getPrime(capacity), i; + this.buckets = new Array(prime); + this.entries = new Array(prime); + for (i = 0; i < prime; i++) { + this.buckets[i] = -1; + this.entries[i] = newEntry(); + } + this.freeList = -1; + }; + + dictionaryProto.add = function (key, value) { + this._insert(key, value, true); + }; + + dictionaryProto._insert = function (key, value, add) { + if (!this.buckets) { this._initialize(0); } + var index3, + num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length; + for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { + if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { + if (add) { throw new Error(duplicatekey); } + this.entries[index2].value = value; + return; + } + } + if (this.freeCount > 0) { + index3 = this.freeList; + this.freeList = this.entries[index3].next; + --this.freeCount; + } else { + if (this.size === this.entries.length) { + this._resize(); + index1 = num % this.buckets.length; + } + index3 = this.size; + ++this.size; + } + this.entries[index3].hashCode = num; + this.entries[index3].next = this.buckets[index1]; + this.entries[index3].key = key; + this.entries[index3].value = value; + this.buckets[index1] = index3; + }; + + dictionaryProto._resize = function () { + var prime = getPrime(this.size * 2), + numArray = new Array(prime); + for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } + var entryArray = new Array(prime); + for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } + for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } + for (var index1 = 0; index1 < this.size; ++index1) { + var index2 = entryArray[index1].hashCode % prime; + entryArray[index1].next = numArray[index2]; + numArray[index2] = index1; + } + this.buckets = numArray; + this.entries = entryArray; + }; + + dictionaryProto.remove = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647, + index1 = num % this.buckets.length, + index2 = -1; + for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { + if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { + if (index2 < 0) { + this.buckets[index1] = this.entries[index3].next; + } else { + this.entries[index2].next = this.entries[index3].next; + } + this.entries[index3].hashCode = -1; + this.entries[index3].next = this.freeList; + this.entries[index3].key = null; + this.entries[index3].value = null; + this.freeList = index3; + ++this.freeCount; + return true; + } else { + index2 = index3; + } + } + } + return false; + }; + + dictionaryProto.clear = function () { + var index, len; + if (this.size <= 0) { return; } + for (index = 0, len = this.buckets.length; index < len; ++index) { + this.buckets[index] = -1; + } + for (index = 0; index < this.size; ++index) { + this.entries[index] = newEntry(); + } + this.freeList = -1; + this.size = 0; + }; + + dictionaryProto._findEntry = function (key) { + if (this.buckets) { + var num = getHashCode(key) & 2147483647; + for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { + if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { + return index; + } + } + } + return -1; + }; + + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; + + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; + + dictionaryProto.getValues = function () { + var index = 0, results = []; + if (this.entries) { + for (var index1 = 0; index1 < this.size; index1++) { + if (this.entries[index1].hashCode >= 0) { + results[index++] = this.entries[index1].value; + } + } + } + return results; + }; + + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; + + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; + + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; + + return Dictionary; + }()); + + /** + * Correlates the elements of two sequences based on overlapping durations. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var leftDone = false, rightDone = false; + var leftId = 0, rightId = 0; + var leftMap = new Dictionary(), rightMap = new Dictionary(); + + group.add(left.subscribe( + function (value) { + var id = leftId++; + var md = new SingleAssignmentDisposable(); + + leftMap.add(id, value); + group.add(md); + + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); + + rightMap.add(id, value); + group.add(md); + + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch (exn) { + observer.onError(exn); + return; + } + + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + rightDone = true; + (leftDone || rightMap.count() === 0) && observer.onCompleted(); + }) + ); + return group; + }, left); + }; + + /** + * Correlates the elements of two sequences based on overlapping durations, and groups the results. + * + * @param {Observable} right The right observable sequence to join elements for. + * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. + * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. + * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. + * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. + */ + observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { + var left = this; + return new AnonymousObservable(function (observer) { + var group = new CompositeDisposable(); + var r = new RefCountDisposable(group); + var leftMap = new Dictionary(), rightMap = new Dictionary(); + var leftId = 0, rightId = 0; + + function handleError(e) { return function (v) { v.onError(e); }; }; + + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); + + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); + + rightMap.getValues().forEach(function (v) { s.onNext(v); }); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; + + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + observer.onCompleted.bind(observer)) + ); + + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); + + var md = new SingleAssignmentDisposable(); + group.add(md); + + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; + + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + md.setDisposable(duration.take(1).subscribe( + noop, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }, + expire) + ); + + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); + + return r; + }, left); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers. + * + * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { + return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into zero or more windows. + * + * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). + * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { + if (arguments.length === 1 && typeof arguments[0] !== 'function') { + return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); + } + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; + + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { + return win; + }); + } + + function observableWindowWithBoundaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var win = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); + + observer.onNext(addRef(win, r)); + + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); + + d.add(windowBoundaries.subscribe(function (w) { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + return r; + }, source); + } + + function observableWindowWithClosingSelector(windowClosingSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var m = new SerialDisposable(), + d = new CompositeDisposable(m), + r = new RefCountDisposable(d), + win = new Subject(); + observer.onNext(addRef(win, r)); + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); + + function createWindowClose () { + var windowClose; + try { + windowClose = windowClosingSelector(); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); + + var m1 = new SingleAssignmentDisposable(); + m.setDisposable(m1); + m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + win = new Subject(); + observer.onNext(addRef(win, r)); + createWindowClose(); + })); + } + + createWindowClose(); + return r; + }, source); + } + + /** + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. + * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. + */ + observableProto.pairwise = function () { + var source = this; + return new AnonymousObservable(function (observer) { + var previous, hasPrevious = false; + return source.subscribe( + function (x) { + if (hasPrevious) { + observer.onNext([previous, x]); + } else { + hasPrevious = true; + } + previous = x; + }, + observer.onError.bind(observer), + observer.onCompleted.bind(observer)); + }, source); + }; + + /** + * Returns two observables which partition the observations of the source by the given function. + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes + * when the source completes. + * @param {Function} predicate + * The function to determine which output Observable will trigger a particular observation. + * @returns {Array} + * An array of observables. The first triggers when the predicate returns true, + * and the second triggers when the predicate returns false. + */ + observableProto.partition = function(predicate, thisArg) { + return [ + this.filter(predicate, thisArg), + this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) + ]; + }; + + var WhileEnumerable = (function(__super__) { + inherits(WhileEnumerable, __super__); + function WhileEnumerable(c, s) { + this.c = c; + this.s = s; + } + WhileEnumerable.prototype[$iterator$] = function () { + var self = this; + return { + next: function () { + return self.c() ? + { done: false, value: self.s } : + { done: true, value: void 0 }; + } + }; + }; + return WhileEnumerable; + }(Enumerable)); + + function enumerableWhile(condition, source) { + return new WhileEnumerable(condition, source); + } + + /** + * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. + * This operator allows for a fluent style of writing queries that use the same sequence multiple times. + * + * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.letBind = observableProto['let'] = function (func) { + return func(this); + }; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; + } + if (isOwner) { + m.setDisposable(scheduler.scheduleRecursive(function (self) { + var work; + if (q.length > 0) { + work = q.shift(); + } else { + isAcquired = false; + return; + } + var m1 = new SingleAssignmentDisposable(); + d.add(m1); + m1.setDisposable(work.subscribe(function (x) { + observer.onNext(x); + var result = null; + try { + result = selector(x); + } catch (e) { + observer.onError(e); + } + q.push(result); + activeCount++; + ensureActive(); + }, observer.onError.bind(observer), function () { + d.remove(m1); + activeCount--; + if (activeCount === 0) { + observer.onCompleted(); + } + })); + self(); + })); + } + }; + + q.push(source); + activeCount++; + ensureActive(); + return d; + }, this); + }; + + /** + * Runs all observable sequences in parallel and collect their last elements. + * + * @example + * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); + * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); + * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. + */ + Observable.forkJoin = function () { + var allSources = []; + if (Array.isArray(arguments[0])) { + allSources = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } + } + return new AnonymousObservable(function (subscriber) { + var count = allSources.length; + if (count === 0) { + subscriber.onCompleted(); + return disposableEmpty; + } + var group = new CompositeDisposable(), + finished = false, + hasResults = new Array(count), + hasCompleted = new Array(count), + results = new Array(count); + + for (var idx = 0; idx < count; idx++) { + (function (i) { + var source = allSources[i]; + isPromise(source) && (source = observableFromPromise(source)); + group.add( + source.subscribe( + function (value) { + if (!finished) { + hasResults[i] = true; + results[i] = value; + } + }, + function (e) { + finished = true; + subscriber.onError(e); + group.dispose(); + }, + function () { + if (!finished) { + if (!hasResults[i]) { + subscriber.onCompleted(); + return; + } + hasCompleted[i] = true; + for (var ix = 0; ix < count; ix++) { + if (!hasCompleted[ix]) { return; } + } + finished = true; + subscriber.onNext(results); + subscriber.onCompleted(); + } + })); + })(idx); + } + + return group; + }); + }; + + /** + * Runs two observable sequences in parallel and combines their last elemenets. + * + * @param {Observable} second Second observable sequence. + * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. + * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. + */ + observableProto.forkJoin = function (second, resultSelector) { + var first = this; + return new AnonymousObservable(function (observer) { + var leftStopped = false, rightStopped = false, + hasLeft = false, hasRight = false, + lastLeft, lastRight, + leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); + + isPromise(second) && (second = observableFromPromise(second)); + + leftSubscription.setDisposable( + first.subscribe(function (left) { + hasLeft = true; + lastLeft = left; + }, function (err) { + rightSubscription.dispose(); + observer.onError(err); + }, function () { + leftStopped = true; + if (rightStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + rightSubscription.setDisposable( + second.subscribe(function (right) { + hasRight = true; + lastRight = right; + }, function (err) { + leftSubscription.dispose(); + observer.onError(err); + }, function () { + rightStopped = true; + if (leftStopped) { + if (!hasLeft) { + observer.onCompleted(); + } else if (!hasRight) { + observer.onCompleted(); + } else { + var result; + try { + result = resultSelector(lastLeft, lastRight); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + observer.onCompleted(); + } + } + }) + ); + + return new CompositeDisposable(leftSubscription, rightSubscription); + }, first); + }; + + /** + * Comonadic bind operator. + * @param {Function} selector A transform function to apply to each element. + * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. + * @returns {Observable} An observable sequence which results from the comonadic bind operation. + */ + observableProto.manySelect = observableProto.extend = function (selector, scheduler) { + isScheduler(scheduler) || (scheduler = immediateScheduler); + var source = this; + return observableDefer(function () { + var chain; + + return source + .map(function (x) { + var curr = new ChainObservable(x); + + chain && chain.onNext(x); + chain = curr; + + return curr; + }) + .tap( + noop, + function (e) { chain && chain.onError(e); }, + function () { chain && chain.onCompleted(); } + ) + .observeOn(scheduler) + .map(selector); + }, source); + }; + + var ChainObservable = (function (__super__) { + + function subscribe (observer) { + var self = this, g = new CompositeDisposable(); + g.add(currentThreadScheduler.schedule(function () { + observer.onNext(self.head); + g.add(self.tail.mergeAll().subscribe(observer)); + })); + + return g; + } + + inherits(ChainObservable, __super__); + + function ChainObservable(head) { + __super__.call(this, subscribe); + this.head = head; + this.tail = new AsyncSubject(); + } + + addProperties(ChainObservable.prototype, Observer, { + onCompleted: function () { + this.onNext(Observable.empty()); + }, + onError: function (e) { + this.onNext(Observable.throwError(e)); + }, + onNext: function (v) { + this.tail.onNext(v); + this.tail.onCompleted(); + } + }); + + return ChainObservable; + + }(Observable)); + + /** @private */ + var Map = root.Map || (function () { + + function Map() { + this._keys = []; + this._values = []; + } + + Map.prototype.get = function (key) { + var i = this._keys.indexOf(key); + return i !== -1 ? this._values[i] : undefined; + }; + + Map.prototype.set = function (key, value) { + var i = this._keys.indexOf(key); + i !== -1 && (this._values[i] = value); + this._values[this._keys.push(key) - 1] = value; + }; + + Map.prototype.forEach = function (callback, thisArg) { + for (var i = 0, len = this._keys.length; i < len; i++) { + callback.call(thisArg, this._values[i], this._keys[i]); + } + }; + + return Map; + }()); + + /** + * @constructor + * Represents a join pattern over observable sequences. + */ + function Pattern(patterns) { + this.patterns = patterns; + } + + /** + * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. + * @param other Observable sequence to match in addition to the current pattern. + * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. + */ + Pattern.prototype.and = function (other) { + return new Pattern(this.patterns.concat(other)); + }; + + /** + * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. + * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. + * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + Pattern.prototype.thenDo = function (selector) { + return new Plan(this, selector); + }; + + function Plan(expression, selector) { + this.expression = expression; + this.selector = selector; + } + + Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { + var self = this; + var joinObservers = []; + for (var i = 0, len = this.expression.patterns.length; i < len; i++) { + joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); + } + var activePlan = new ActivePlan(joinObservers, function () { + var result; + try { + result = self.selector.apply(self, arguments); + } catch (e) { + observer.onError(e); + return; + } + observer.onNext(result); + }, function () { + for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { + joinObservers[j].removeActivePlan(activePlan); + } + deactivate(activePlan); + }); + for (i = 0, len = joinObservers.length; i < len; i++) { + joinObservers[i].addActivePlan(activePlan); + } + return activePlan; + }; + + function planCreateObserver(externalSubscriptions, observable, onError) { + var entry = externalSubscriptions.get(observable); + if (!entry) { + var observer = new JoinObserver(observable, onError); + externalSubscriptions.set(observable, observer); + return observer; + } + return entry; + } + + function ActivePlan(joinObserverArray, onNext, onCompleted) { + this.joinObserverArray = joinObserverArray; + this.onNext = onNext; + this.onCompleted = onCompleted; + this.joinObservers = new Map(); + for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { + var joinObserver = this.joinObserverArray[i]; + this.joinObservers.set(joinObserver, joinObserver); + } + } + + ActivePlan.prototype.dequeue = function () { + this.joinObservers.forEach(function (v) { v.queue.shift(); }); + }; + + ActivePlan.prototype.match = function () { + var i, len, hasValues = true; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + if (this.joinObserverArray[i].queue.length === 0) { + hasValues = false; + break; + } + } + if (hasValues) { + var firstValues = [], + isCompleted = false; + for (i = 0, len = this.joinObserverArray.length; i < len; i++) { + firstValues.push(this.joinObserverArray[i].queue[0]); + this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); + } + if (isCompleted) { + this.onCompleted(); + } else { + this.dequeue(); + var values = []; + for (i = 0, len = firstValues.length; i < firstValues.length; i++) { + values.push(firstValues[i].value); + } + this.onNext.apply(this, values); + } + } + }; + + var JoinObserver = (function (__super__) { + inherits(JoinObserver, __super__); + + function JoinObserver(source, onError) { + __super__.call(this); + this.source = source; + this.onError = onError; + this.queue = []; + this.activePlans = []; + this.subscription = new SingleAssignmentDisposable(); + this.isDisposed = false; + } + + var JoinObserverPrototype = JoinObserver.prototype; + + JoinObserverPrototype.next = function (notification) { + if (!this.isDisposed) { + if (notification.kind === 'E') { + return this.onError(notification.exception); + } + this.queue.push(notification); + var activePlans = this.activePlans.slice(0); + for (var i = 0, len = activePlans.length; i < len; i++) { + activePlans[i].match(); + } + } + }; + + JoinObserverPrototype.error = noop; + JoinObserverPrototype.completed = noop; + + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; + + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; + + JoinObserverPrototype.removeActivePlan = function (activePlan) { + this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); + this.activePlans.length === 0 && this.dispose(); + }; + + JoinObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); + } + }; + + return JoinObserver; + } (AbstractObserver)); + + /** + * Creates a pattern that matches when both observable sequences have an available value. + * + * @param right Observable sequence to match with the current sequence. + * @return {Pattern} Pattern object that matches when both observable sequences have an available value. + */ + observableProto.and = function (right) { + return new Pattern([this, right]); + }; + + /** + * Matches when the observable sequence has an available value and projects the value. + * + * @param {Function} selector Selector that will be invoked for values in the source sequence. + * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. + */ + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); + }; + + /** + * Joins together the results from several patterns. + * + * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. + * @returns {Observable} Observable sequence with the results form matching several patterns. + */ + Observable.when = function () { + var len = arguments.length, plans; + if (Array.isArray(arguments[0])) { + plans = arguments[0]; + } else { + plans = new Array(len); + for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } + } + return new AnonymousObservable(function (o) { + var activePlans = [], + externalSubscriptions = new Map(); + var outObserver = observerCreate( + function (x) { o.onNext(x); }, + function (err) { + externalSubscriptions.forEach(function (v) { v.onError(err); }); + o.onError(err); + }, + function (x) { o.onCompleted(); } + ); + try { + for (var i = 0, len = plans.length; i < len; i++) { + activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { + var idx = activePlans.indexOf(activePlan); + activePlans.splice(idx, 1); + activePlans.length === 0 && o.onCompleted(); + })); + } + } catch (e) { + observableThrow(e).subscribe(o); + } + var group = new CompositeDisposable(); + externalSubscriptions.forEach(function (joinObserver) { + joinObserver.subscribe(); + group.add(joinObserver); + }); + + return group; + }); + }; + + function observableTimerDate(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithAbsolute(dueTime, function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerDateAndPeriod(dueTime, period, scheduler) { + return new AnonymousObservable(function (observer) { + var d = dueTime, p = normalizeTime(period); + return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { + if (p > 0) { + var now = scheduler.now(); + d = d + p; + d <= now && (d = now + p); + } + observer.onNext(count); + self(count + 1, d); + }); + }); + } + + function observableTimerTimeSpan(dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { + observer.onNext(0); + observer.onCompleted(); + }); + }); + } + + function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { + return dueTime === period ? + new AnonymousObservable(function (observer) { + return scheduler.schedulePeriodicWithState(0, period, function (count) { + observer.onNext(count); + return count + 1; + }); + }) : + observableDefer(function () { + return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); + }); + } + + /** + * Returns an observable sequence that produces a value after each period. + * + * @example + * 1 - res = Rx.Observable.interval(1000); + * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); + * + * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. + * @returns {Observable} An observable sequence that produces a value after each period. + */ + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); + }; + + /** + * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. + * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. + */ + var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { + var period; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { + period = periodOrScheduler; + } else if (isScheduler(periodOrScheduler)) { + scheduler = periodOrScheduler; + } + if (dueTime instanceof Date && period === undefined) { + return observableTimerDate(dueTime.getTime(), scheduler); + } + if (dueTime instanceof Date && period !== undefined) { + period = periodOrScheduler; + return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); + } + return period === undefined ? + observableTimerTimeSpan(dueTime, scheduler) : + observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); + }; + + function observableDelayTimeSpan(source, dueTime, scheduler) { + return new AnonymousObservable(function (observer) { + var active = false, + cancelable = new SerialDisposable(), + exception = null, + q = [], + running = false, + subscription; + subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { + var d, shouldRun; + if (notification.value.kind === 'E') { + q = []; + q.push(notification); + exception = notification.value.exception; + shouldRun = !running; + } else { + q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); + shouldRun = !active; + active = true; + } + if (shouldRun) { + if (exception !== null) { + observer.onError(exception); + } else { + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { + var e, recurseDueTime, result, shouldRecurse; + if (exception !== null) { + return; + } + running = true; + do { + result = null; + if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { + result = q.shift().value; + } + if (result !== null) { + result.accept(observer); + } + } while (result !== null); + shouldRecurse = false; + recurseDueTime = 0; + if (q.length > 0) { + shouldRecurse = true; + recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); + } else { + active = false; + } + e = exception; + running = false; + if (e !== null) { + observer.onError(e); + } else if (shouldRecurse) { + self(recurseDueTime); + } + })); + } + } + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + } + + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } + + /** + * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. + * + * @example + * 1 - res = Rx.Observable.delay(new Date()); + * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); + * + * 3 - res = Rx.Observable.delay(5000); + * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); + * @memberOf Observable# + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. + * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); + }; + + /** + * Ignores values from an observable sequence which are followed by another value before dueTime. + * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). + * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (observer) { + var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; + var subscription = source.subscribe( + function (x) { + hasvalue = true; + value = x; + id++; + var currentId = id, + d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { + hasvalue && id === currentId && observer.onNext(value); + hasvalue = false; + })); + }, + function (e) { + cancelable.dispose(); + observer.onError(e); + hasvalue = false; + id++; + }, + function () { + cancelable.dispose(); + hasvalue && observer.onNext(value); + observer.onCompleted(); + hasvalue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, this); + }; + + /** + * @deprecated use #debounce or #throttleWithTimeout instead. + */ + observableProto.throttle = function(dueTime, scheduler) { + //deprecate('throttle', 'debounce or throttleWithTimeout'); + return this.debounce(dueTime, scheduler); + }; + + /** + * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. + * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + var source = this, timeShift; + timeShiftOrScheduler == null && (timeShift = timeSpan); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + if (typeof timeShiftOrScheduler === 'number') { + timeShift = timeShiftOrScheduler; + } else if (isScheduler(timeShiftOrScheduler)) { + timeShift = timeSpan; + scheduler = timeShiftOrScheduler; + } + return new AnonymousObservable(function (observer) { + var groupDisposable, + nextShift = timeShift, + nextSpan = timeSpan, + q = [], + refCountDisposable, + timerD = new SerialDisposable(), + totalTime = 0; + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable); + + function createTimer () { + var m = new SingleAssignmentDisposable(), + isSpan = false, + isShift = false; + timerD.setDisposable(m); + if (nextSpan === nextShift) { + isSpan = true; + isShift = true; + } else if (nextSpan < nextShift) { + isSpan = true; + } else { + isShift = true; + } + var newTotalTime = isSpan ? nextSpan : nextShift, + ts = newTotalTime - totalTime; + totalTime = newTotalTime; + if (isSpan) { + nextSpan += timeShift; + } + if (isShift) { + nextShift += timeShift; + } + m.setDisposable(scheduler.scheduleWithRelative(ts, function () { + if (isShift) { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); + } + isSpan && q.shift().onCompleted(); + createTimer(); + })); + }; + q.push(new Subject()); + observer.onNext(addRef(q[0], refCountDisposable)); + createTimer(); + groupDisposable.add(source.subscribe( + function (x) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } + }, + function (e) { + for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } + observer.onError(e); + }, + function () { + for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. + * @param {Number} timeSpan Maximum time length of a window. + * @param {Number} count Maximum element count of a window. + * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of windows. + */ + observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var timerD = new SerialDisposable(), + groupDisposable = new CompositeDisposable(timerD), + refCountDisposable = new RefCountDisposable(groupDisposable), + n = 0, + windowId = 0, + s = new Subject(); + + function createTimer(id) { + var m = new SingleAssignmentDisposable(); + timerD.setDisposable(m); + m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { + if (id !== windowId) { return; } + n = 0; + var newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + createTimer(newId); + })); + } + + observer.onNext(addRef(s, refCountDisposable)); + createTimer(0); + + groupDisposable.add(source.subscribe( + function (x) { + var newId = 0, newWindow = false; + s.onNext(x); + if (++n === count) { + newWindow = true; + n = 0; + newId = ++windowId; + s.onCompleted(); + s = new Subject(); + observer.onNext(addRef(s, refCountDisposable)); + } + newWindow && createTimer(newId); + }, + function (e) { + s.onError(e); + observer.onError(e); + }, function () { + s.onCompleted(); + observer.onCompleted(); + } + )); + return refCountDisposable; + }, source); + }; + + /** + * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. + * + * @example + * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second + * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds + * + * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). + * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. + * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { + return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); + }; + + /** + * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. + * + * @example + * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array + * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array + * + * @param {Number} timeSpan Maximum time length of a buffer. + * @param {Number} count Maximum element count of a buffer. + * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence of buffers. + */ + observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { + return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { + return x.toArray(); + }); + }; + + /** + * Records the time interval between consecutive values in an observable sequence. + * + * @example + * 1 - res = source.timeInterval(); + * 2 - res = source.timeInterval(Rx.Scheduler.timeout); + * + * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. + * @returns {Observable} An observable sequence with time interval information on values. + */ + observableProto.timeInterval = function (scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return observableDefer(function () { + var last = scheduler.now(); + return source.map(function (x) { + var now = scheduler.now(), span = now - last; + last = now; + return { value: x, interval: span }; + }); + }); + }; + + /** + * Records the timestamp for each value in an observable sequence. + * + * @example + * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } + * 2 - res = source.timestamp(Rx.Scheduler.default); + * + * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. + * @returns {Observable} An observable sequence with timestamp information on values. + */ + observableProto.timestamp = function (scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return this.map(function (x) { + return { value: x, timestamp: scheduler.now() }; + }); + }; + + function sampleObservable(source, sampler) { + return new AnonymousObservable(function (o) { + var atEnd = false, value, hasValue = false; + + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + o.onNext(value); + } + atEnd && o.onCompleted(); + } + + var sourceSubscription = new SingleAssignmentDisposable(); + sourceSubscription.setDisposable(source.subscribe( + function (newValue) { + hasValue = true; + value = newValue; + }, + function (e) { o.onError(e); }, + function () { + atEnd = true; + sourceSubscription.dispose(); + } + )); + + return new CompositeDisposable( + sourceSubscription, + sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) + ); + }, source); + } + + /** + * Samples the observable sequence at each interval. + * + * @example + * 1 - res = source.sample(sampleObservable); // Sampler tick sequence + * 2 - res = source.sample(5000); // 5 seconds + * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds + * + * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. + * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Sampled observable sequence. + */ + observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return typeof intervalOrSampler === 'number' ? + sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : + sampleObservable(this, intervalOrSampler); + }; + + /** + * Returns the source observable sequence or the other observable sequence if dueTime elapses. + * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. + * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. + * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeout = function (dueTime, other, scheduler) { + (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); + isScheduler(scheduler) || (scheduler = timeoutScheduler); + + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); + + subscription.setDisposable(original); + + function createTimer() { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + } + + createTimer(); + + original.setDisposable(source.subscribe(function (x) { + if (!switched) { + id++; + observer.onNext(x); + createTimer(); + } + }, function (e) { + if (!switched) { + id++; + observer.onError(e); + } + }, function () { + if (!switched) { + id++; + observer.onCompleted(); + } + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithAbsoluteTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return new Date(); } + * }); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Generates an observable sequence by iterating a state from an initial state until the condition fails. + * + * @example + * res = source.generateWithRelativeTime(0, + * function (x) { return return true; }, + * function (x) { return x + 1; }, + * function (x) { return x; }, + * function (x) { return 500; } + * ); + * + * @param {Mixed} initialState Initial state. + * @param {Function} condition Condition to terminate generation (upon returning false). + * @param {Function} iterate Iteration step function. + * @param {Function} resultSelector Selector function for results produced in the sequence. + * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. + * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. + * @returns {Observable} The generated sequence. + */ + Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var first = true, + hasResult = false; + return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { + hasResult && observer.onNext(state); + + try { + if (first) { + first = false; + } else { + state = iterate(state); + } + hasResult = condition(state); + if (hasResult) { + var result = resultSelector(state); + var time = timeSelector(state); + } + } catch (e) { + observer.onError(e); + return; + } + if (hasResult) { + self(result, time); + } else { + observer.onCompleted(); + } + }); + }); + }; + + /** + * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.delaySubscription(5000); // 5s + * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds + * + * @param {Number} dueTime Relative or absolute time shift of the subscription. + * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delaySubscription = function (dueTime, scheduler) { + var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var d = new SerialDisposable(); + + d.setDisposable(scheduler[scheduleMethod](dueTime, function() { + d.setDisposable(source.subscribe(o)); + })); + + return d; + }, this); + }; + + /** + * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. + * + * @example + * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only + * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector + * + * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. + * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. + * @returns {Observable} Time-shifted sequence. + */ + observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { + var source = this, subDelay, selector; + if (isFunction(subscriptionDelay)) { + selector = subscriptionDelay; + } else { + subDelay = subscriptionDelay; + selector = delayDurationSelector; + } + return new AnonymousObservable(function (observer) { + var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); + + function start() { + subscription.setDisposable(source.subscribe( + function (x) { + var delay = tryCatch(selector)(x); + if (delay === errorObj) { return observer.onError(delay.e); } + var d = new SingleAssignmentDisposable(); + delays.add(d); + d.setDisposable(delay.subscribe( + function () { + observer.onNext(x); + delays.remove(d); + done(); + }, + function (e) { observer.onError(e); }, + function () { + observer.onNext(x); + delays.remove(d); + done(); + } + )) + }, + function (e) { observer.onError(e); }, + function () { + atEnd = true; + subscription.dispose(); + done(); + } + )) + } + + function done () { + atEnd && delays.length === 0 && observer.onCompleted(); + } + + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); + } + + return new CompositeDisposable(subscription, delays); + }, this); + }; + + /** + * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. + * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). + * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. + * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). + * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. + */ + observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { + if (arguments.length === 1) { + timeoutdurationSelector = firstTimeout; + firstTimeout = observableNever(); + } + other || (other = observableThrow(new Error('Timeout'))); + var source = this; + return new AnonymousObservable(function (observer) { + var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); + + subscription.setDisposable(original); + + var id = 0, switched = false; + + function setTimer(timeout) { + var myId = id; + + function timerWins () { + return id === myId; + } + + var d = new SingleAssignmentDisposable(); + timer.setDisposable(d); + d.setDisposable(timeout.subscribe(function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + d.dispose(); + }, function (e) { + timerWins() && observer.onError(e); + }, function () { + timerWins() && subscription.setDisposable(other.subscribe(observer)); + })); + }; + + setTimer(firstTimeout); + + function observerWins() { + var res = !switched; + if (res) { id++; } + return res; + } + + original.setDisposable(source.subscribe(function (x) { + if (observerWins()) { + observer.onNext(x); + var timeout; + try { + timeout = timeoutdurationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); + } + }, function (e) { + observerWins() && observer.onError(e); + }, function () { + observerWins() && observer.onCompleted(); + })); + return new CompositeDisposable(subscription, timer); + }, source); + }; + + /** + * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. + * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. + * @returns {Observable} The debounced sequence. + */ + observableProto.debounceWithSelector = function (durationSelector) { + var source = this; + return new AnonymousObservable(function (observer) { + var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; + var subscription = source.subscribe(function (x) { + var throttle; + try { + throttle = durationSelector(x); + } catch (e) { + observer.onError(e); + return; + } + + isPromise(throttle) && (throttle = observableFromPromise(throttle)); + + hasValue = true; + value = x; + id++; + var currentid = id, d = new SingleAssignmentDisposable(); + cancelable.setDisposable(d); + d.setDisposable(throttle.subscribe(function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + }, observer.onError.bind(observer), function () { + hasValue && id === currentid && observer.onNext(value); + hasValue = false; + d.dispose(); + })); + }, function (e) { + cancelable.dispose(); + observer.onError(e); + hasValue = false; + id++; + }, function () { + cancelable.dispose(); + hasValue && observer.onNext(value); + observer.onCompleted(); + hasValue = false; + id++; + }); + return new CompositeDisposable(subscription, cancelable); + }, source); + }; + + /** + * @deprecated use #debounceWithSelector instead. + */ + observableProto.throttleWithSelector = function (durationSelector) { + //deprecate('throttleWithSelector', 'debounceWithSelector'); + return this.debounceWithSelector(durationSelector); + }; + + /** + * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * + * 1 - res = source.skipLastWithTime(5000); + * 2 - res = source.skipLastWithTime(5000, scheduler); + * + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for skipping elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. + */ + observableProto.skipLastWithTime = function (duration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this; + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); + } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0) { + var next = q.shift(); + if (now - next.interval <= duration) { o.onNext(next.value); } + } + o.onCompleted(); + }); + }, source); + }; + + /** + * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the end of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. + */ + observableProto.takeLastBufferWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + var q = []; + return source.subscribe(function (x) { + var now = scheduler.now(); + q.push({ interval: now, value: x }); + while (q.length > 0 && now - q[0].interval >= duration) { + q.shift(); + } + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(), res = []; + while (q.length > 0) { + var next = q.shift(); + now - next.interval <= duration && res.push(next.value); + } + o.onNext(res); + o.onCompleted(); + }); + }, source); + }; + + /** + * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.takeWithTime(5000, [optional scheduler]); + * @description + * This operator accumulates a queue with a length enough to store elements received during the initial duration window. + * As more elements are received, elements older than the specified duration are taken from the queue and produced on the + * result sequence. This causes elements to be delayed with duration. + * @param {Number} duration Duration for taking elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + observableProto.takeWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (o) { + return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); + }, source); + }; + + /** + * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + * + * @example + * 1 - res = source.skipWithTime(5000, [optional scheduler]); + * + * @description + * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. + * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded + * may not execute immediately, despite the zero due time. + * + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. + * @param {Number} duration Duration for skipping elements from the start of the sequence. + * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + observableProto.skipWithTime = function (duration, scheduler) { + var source = this; + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return new AnonymousObservable(function (observer) { + var open = false; + return new CompositeDisposable( + scheduler.scheduleWithRelative(duration, function () { open = true; }), + source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); + }, source); + }; + + /** + * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. + * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. + * + * @examples + * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); + * 2 - res = source.skipUntilWithTime(5000, [scheduler]); + * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. + * @returns {Observable} An observable sequence with the elements skipped until the specified start time. + */ + observableProto.skipUntilWithTime = function (startTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = startTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + var open = false; + + return new CompositeDisposable( + scheduler[schedulerMethod](startTime, function () { open = true; }), + source.subscribe( + function (x) { open && o.onNext(x); }, + function (e) { o.onError(e); }, function () { o.onCompleted(); })); + }, source); + }; + + /** + * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. + * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. + * @param {Scheduler} [scheduler] Scheduler to run the timer on. + * @returns {Observable} An observable sequence with the elements taken until the specified end time. + */ + observableProto.takeUntilWithTime = function (endTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var source = this, schedulerMethod = endTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; + return new AnonymousObservable(function (o) { + return new CompositeDisposable( + scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), + source.subscribe(o)); + }, source); + }; + + /** + * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. + * @param {Number} windowDuration time to wait before emitting another item after emitting the last item + * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. + * @returns {Observable} An Observable that performs the throttle operation. + */ + observableProto.throttleFirst = function (windowDuration, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + var duration = +windowDuration || 0; + if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } + var source = this; + return new AnonymousObservable(function (o) { + var lastOnNext = 0; + return source.subscribe( + function (x) { + var now = scheduler.now(); + if (lastOnNext === 0 || now - lastOnNext >= duration) { + lastOnNext = now; + o.onNext(x); + } + },function (e) { o.onError(e); }, function () { o.onCompleted(); } + ); + }, source); + }; + + /** + * Executes a transducer to transform the observable sequence + * @param {Transducer} transducer A transducer to execute + * @returns {Observable} An Observable sequence containing the results from the transducer. + */ + observableProto.transduce = function(transducer) { + var source = this; + + function transformForObserver(o) { + return { + '@@transducer/init': function() { + return o; + }, + '@@transducer/step': function(obs, input) { + return obs.onNext(input); + }, + '@@transducer/result': function(obs) { + return obs.onCompleted(); + } + }; + } + + return new AnonymousObservable(function(o) { + var xform = transducer(transformForObserver(o)); + return source.subscribe( + function(v) { + try { + xform['@@transducer/step'](o, v); + } catch (e) { + o.onError(e); + } + }, + function (e) { o.onError(e); }, + function() { xform['@@transducer/result'](o); } + ); + }, source); + }; + + /* + * Performs a exclusive waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @returns {Observable} A exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + if (!hasCurrent) { + hasCurrent = true; + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + var innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + innerSubscription.setDisposable(innerSource.subscribe( + observer.onNext.bind(observer), + observer.onError.bind(observer), + function () { + g.remove(innerSubscription); + hasCurrent = false; + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + observer.onError.bind(observer), + function () { + isStopped = true; + if (!hasCurrent && g.length === 1) { + observer.onCompleted(); + } + })); + + return g; + }, this); + }; + + /* + * Performs a exclusive map waiting for the first to finish before subscribing to another observable. + * Observables that come in between subscriptions will be dropped on the floor. + * @param {Function} selector Selector to invoke for every item in the current subscription. + * @param {Any} [thisArg] An optional context to invoke with the selector parameter. + * @returns {Observable} An exclusive observable with only the results that happen when subscribed. + */ + observableProto.exclusiveMap = function (selector, thisArg) { + var sources = this, + selectorFunc = bindCallback(selector, thisArg, 3); + return new AnonymousObservable(function (observer) { + var index = 0, + hasCurrent = false, + isStopped = true, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); + + g.add(m); + + m.setDisposable(sources.subscribe( + function (innerSource) { + + if (!hasCurrent) { + hasCurrent = true; + + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); + + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selectorFunc(x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } + + observer.onNext(result); + }, + function (e) { observer.onError(e); }, + function () { + g.remove(innerSubscription); + hasCurrent = false; + + if (isStopped && g.length === 1) { + observer.onCompleted(); + } + })); + } + }, + function (e) { observer.onError(e); }, + function () { + isStopped = true; + if (g.length === 1 && !hasCurrent) { + observer.onCompleted(); + } + })); + return g; + }, this); + }; + + /** Provides a set of extension methods for virtual time scheduling. */ + Rx.VirtualTimeScheduler = (function (__super__) { + + function localNow() { + return this.toDateTimeOffset(this.clock); + } + + function scheduleNow(state, action) { + return this.scheduleAbsoluteWithState(state, this.clock, action); + } + + function scheduleRelative(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); + } + + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); + } + + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } + + inherits(VirtualTimeScheduler, __super__); + + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); + } + + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; + + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelative = notImplemented; + + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsoluteWithState(state, runAt, action); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { + return this.scheduleRelativeWithState(action, dueTime, invokeAction); + }; + + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; + + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + + this.advanceTo(dt); + }; + + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } + + this.clock = dt; + }; + + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Scheduler} scheduler Scheduler to execute the action on. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { + return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); + }; + + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { + var self = this; + + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } + + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + + return si.disposable; + }; + + return VirtualTimeScheduler; + }(Scheduler)); + + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); + + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; + + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); + }; + + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; + }; + + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); + + var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { + inherits(AnonymousObservable, __super__); + + // Fix subscriber to check for undefined or function returned to decorate as Disposable + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; + } + + function setDisposable(s, state) { + var ado = state[0], subscribe = state[1]; + var sub = tryCatch(subscribe)(ado); + + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + } + ado.setDisposable(fixSubscriber(sub)); + } + + function AnonymousObservable(subscribe, parent) { + this.source = parent; + + function s(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } + + __super__.call(this, s); + } + + return AnonymousObservable; + + }(Observable)); + + var AutoDetachObserver = (function (__super__) { + inherits(AutoDetachObserver, __super__); + + function AutoDetachObserver(observer) { + __super__.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); + } + + var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + + AutoDetachObserverPrototype.next = function (value) { + var result = tryCatch(this.observer.onNext).call(this.observer, value); + if (result === errorObj) { + this.dispose(); + thrower(result.e); + } + }; + + AutoDetachObserverPrototype.error = function (err) { + var result = tryCatch(this.observer.onError).call(this.observer, err); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.completed = function () { + var result = tryCatch(this.observer.onCompleted).call(this.observer); + this.dispose(); + result === errorObj && thrower(result.e); + }; + + AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; + AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; + + AutoDetachObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.m.dispose(); + }; + + return AutoDetachObserver; + }(AbstractObserver)); + + var GroupedObservable = (function (__super__) { + inherits(GroupedObservable, __super__); + + function subscribe(observer) { + return this.underlyingObservable.subscribe(observer); + } + + function GroupedObservable(key, underlyingObservable, mergedDisposable) { + __super__.call(this, subscribe); + this.key = key; + this.underlyingObservable = !mergedDisposable ? + underlyingObservable : + new AnonymousObservable(function (observer) { + return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); + }); + } + + return GroupedObservable; + }(Observable)); + + /** + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed observers. + */ + var Subject = Rx.Subject = (function (__super__) { + function subscribe(observer) { + checkDisposed(this); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + if (this.hasError) { + observer.onError(this.error); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } + + inherits(Subject, __super__); + + /** + * Creates a subject. + */ + function Subject() { + __super__.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + this.hasError = false; + } + + addProperties(Subject.prototype, Observer.prototype, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { return this.observers.length > 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.error = error; + this.hasError = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (!this.isStopped) { + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + + /** + * Creates a subject from the specified observer and observable. + * @param {Observer} observer The observer used to send messages to the subject. + * @param {Observable} observable The observable used to subscribe to messages sent from the subject. + * @returns {Subject} Subject implemented using the given observer and observable. + */ + Subject.create = function (observer, observable) { + return new AnonymousSubject(observer, observable); + }; + + return Subject; + }(Observable)); + + /** + * Represents the result of an asynchronous operation. + * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. + */ + var AsyncSubject = Rx.AsyncSubject = (function (__super__) { + + function subscribe(observer) { + checkDisposed(this); + + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } + + if (this.hasError) { + observer.onError(this.error); + } else if (this.hasValue) { + observer.onNext(this.value); + observer.onCompleted(); + } else { + observer.onCompleted(); + } + + return disposableEmpty; + } + + inherits(AsyncSubject, __super__); + + /** + * Creates a subject that can only receive one value and that value is cached for all future observations. + * @constructor + */ + function AsyncSubject() { + __super__.call(this, subscribe); + + this.isDisposed = false; + this.isStopped = false; + this.hasValue = false; + this.observers = []; + this.hasError = false; + } + + addProperties(AsyncSubject.prototype, Observer, { + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { + checkDisposed(this); + return this.observers.length > 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). + */ + onCompleted: function () { + var i, len; + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + var os = cloneArray(this.observers), len = os.length; + + if (this.hasValue) { + for (i = 0; i < len; i++) { + var o = os[i]; + o.onNext(this.value); + o.onCompleted(); + } + } else { + for (i = 0; i < len; i++) { + os[i].onCompleted(); + } + } + + this.observers.length = 0; + } + }, + /** + * Notifies all subscribed observers about the error. + * @param {Mixed} error The Error to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (!this.isStopped) { + this.isStopped = true; + this.hasError = true; + this.error = error; + + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } + + this.observers.length = 0; + } + }, + /** + * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. + * @param {Mixed} value The value to store in the subject. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + this.hasValue = true; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.exception = null; + this.value = null; + } + }); + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function subscribe(observer) { + return this.observable.subscribe(observer); + } + + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, subscribe); + } + + addProperties(AnonymousSubject.prototype, Observer.prototype, { + onCompleted: function () { + this.observer.onCompleted(); + }, + onError: function (error) { + this.observer.onError(error); + }, + onNext: function (value) { + this.observer.onNext(value); + } + }); + + return AnonymousSubject; + }(Observable)); + + /** + * Used to pause and resume streams. + */ + Rx.Pauser = (function (__super__) { + inherits(Pauser, __super__); + + function Pauser() { + __super__.call(this); + } + + /** + * Pauses the underlying sequence. + */ + Pauser.prototype.pause = function () { this.onNext(false); }; + + /** + * Resumes the underlying sequence. + */ + Pauser.prototype.resume = function () { this.onNext(true); }; + + return Pauser; + }(Subject)); + + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + root.Rx = Rx; + + define(function() { + return Rx; + }); + } else if (freeExports && freeModule) { + // in Node.js or RingoJS + if (moduleExports) { + (freeModule.exports = Rx).Rx = Rx; + } else { + freeExports.Rx = Rx; + } + } else { + // in a browser or Rhino + root.Rx = Rx; + } + + // All code before this point will be filtered from stack traces. + var rEndingLine = captureLine(); + +}.call(this)); + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":117}],3:[function(require,module,exports){ +module.exports={ + "name": "rx", + "description": "Library for composing asynchronous and event-based operations in JavaScript", + "version": "2.5.3", + "author": { + "name": "Cloud Programmability Team", + "url": "https://github.com/Reactive-Extensions/RxJS/blob/master/authors.txt" + }, + "homepage": "https://github.com/Reactive-Extensions/RxJS", + "repository": { + "type": "git", + "url": "git+https://github.com/Reactive-Extensions/RxJS.git" + }, + "bugs": { + "url": "https://github.com/Reactive-Extensions/RxJS/issues" + }, + "main": "index.js", + "dist": { + "tarball": "https://megusta.artifactoryonline.com/megusta/api/npm/npm/rx/-/rx-2.5.3.tgz", + "shasum": "21adc7d80f02002af50dae97fd9dbf248755f566" + }, + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "grunt-cli": "*", + "grunt": "*", + "grunt-contrib-copy": "*", + "grunt-contrib-jshint": "*", + "grunt-contrib-connect": "*", + "grunt-contrib-uglify": "*", + "grunt-contrib-concat": "*", + "grunt-contrib-qunit": "*", + "grunt-contrib-watch": "*", + "grunt-saucelabs": "*", + "grunt-jscs": "*", + "load-grunt-tasks": "*" + }, + "keywords": [ + "LINQ", + "FRP", + "Reactive", + "Events", + "Rx", + "RxJS" + ], + "license": "Apache-2.0", + "maintainers": [ + { + "name": "vvilhonen", + "email": "vesa@vilhonen.com" + }, + { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + } + ], + "directories": {}, + "scripts": { + "test": "grunt" + }, + "_from": "rx@2.5.3", + "_npmVersion": "2.7.4", + "_npmUser": { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + }, + "_id": "rx@2.5.3", + "gitHead": "6507118725e93498f7a52a603acf679e472f47b7", + "jam": { + "main": "dist/rx.all.js" + }, + "browser": { + "index.js": "dist/rx.all.js" + }, + "_shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", + "title": "Reactive Extensions for JavaScript (RxJS)", + "_nodeVersion": "0.12.2", + "_resolved": "https://megusta.artifactoryonline.com/megusta/api/npm/npm/rx/-/rx-2.5.3.tgz", + "readme": "ERROR: No README data found!" +} + +},{}],4:[function(require,module,exports){ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var _require = require('@cycle/core'); + +var Rx = _require.Rx; + +var ALL_PROPS = '*'; +var PROPS_DRIVER_NAME = 'props'; +var EVENTS_SINK_NAME = 'events'; + +function makeDispatchFunction(element, eventName) { + return function dispatchCustomEvent(evData) { + //console.log('%cdispatchCustomEvent ' + eventName, + // 'background-color: #CCCCFF; color: black'); + var event = undefined; + try { + event = new Event(eventName); + } catch (err) { + event = document.createEvent('Event'); + event.initEvent(eventName, true, true); + } + event.detail = evData; + element.dispatchEvent(event); + }; +} + +function subscribeDispatchers(element) { + var customEvents = element.cycleCustomElementMetadata.customEvents; + + var disposables = new Rx.CompositeDisposable(); + for (var _name in customEvents) { + if (customEvents.hasOwnProperty(_name)) { + if (typeof customEvents[_name].subscribe === 'function') { + var disposable = customEvents[_name].subscribe(makeDispatchFunction(element, _name)); + disposables.add(disposable); + } + } + } + return disposables; +} + +function subscribeDispatchersWhenRootChanges(metadata) { + return metadata.rootElem$.distinctUntilChanged(Rx.helpers.identity, function (x, y) { + return x && y && x.isEqualNode && x.isEqualNode(y); + }).subscribe(function resubscribeDispatchers(rootElem) { + if (metadata.eventDispatchingSubscription) { + metadata.eventDispatchingSubscription.dispose(); + } + metadata.eventDispatchingSubscription = subscribeDispatchers(rootElem); + }); +} + +function subscribeEventDispatchingSink(element, widget) { + element.cycleCustomElementMetadata.eventDispatchingSubscription = subscribeDispatchers(element); + widget.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); + widget.disposables.add(subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)); +} + +function makePropertiesDriver() { + var propertiesDriver = {}; + var defaultComparer = Rx.helpers.defaultComparer; + Object.defineProperty(propertiesDriver, 'type', { + enumerable: false, + value: 'PropertiesDriver' + }); + Object.defineProperty(propertiesDriver, 'get', { + enumerable: false, + value: function get(streamKey) { + var comparer = arguments.length <= 1 || arguments[1] === undefined ? defaultComparer : arguments[1]; + + if (typeof streamKey === 'undefined') { + throw new Error('Custom element driver `props.get()` expects an ' + 'argument in the getter.'); + } + if (typeof this[streamKey] === 'undefined') { + this[streamKey] = new Rx.ReplaySubject(1); + } + return this[streamKey].distinctUntilChanged(Rx.helpers.identity, comparer); + } + }); + Object.defineProperty(propertiesDriver, 'getAll', { + enumerable: false, + value: function getAll() { + return this.get(ALL_PROPS); + } + }); + return propertiesDriver; +} + +function createContainerElement(tagName, vtreeProperties) { + var element = document.createElement('div'); + element.id = vtreeProperties.id || ''; + element.className = vtreeProperties.className || ''; + element.className += ' cycleCustomElement-' + tagName.toUpperCase(); + element.cycleCustomElementMetadata = { + propertiesDriver: null, + rootElem$: null, + customEvents: null, + eventDispatchingSubscription: false + }; + return element; +} + +function throwIfVTreeHasPropertyChildren(vtree) { + if (typeof vtree.properties.children !== 'undefined') { + throw new Error('Custom element should not have property `children`. ' + 'It is reserved for children elements nested into this custom element.'); + } +} + +function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) { + var _ref; + + return (_ref = {}, _defineProperty(_ref, domDriverName, domOutput), _defineProperty(_ref, PROPS_DRIVER_NAME, propertiesDriver), _ref); +} + +function makeConstructor() { + return function customElementConstructor(vtree, CERegistry, driverName) { + //console.log('%cnew (constructor) custom element ' + vtree.tagName, + // 'color: #880088'); + throwIfVTreeHasPropertyChildren(vtree); + this.type = 'Widget'; + this.properties = vtree.properties; + this.properties.children = vtree.children; + this.key = vtree.key; + this.isCustomElementWidget = true; + this.customElementsRegistry = CERegistry; + this.driverName = driverName; + this.firstRootElem$ = new Rx.ReplaySubject(1); + this.disposables = new Rx.CompositeDisposable(); + }; +} + +function validateDefFnOutput(defFnOutput, domDriverName, tagName) { + if (typeof defFnOutput !== 'object') { + throw new Error('Custom element definition function for \'' + tagName + '\' ' + ' should output an object.'); + } + if (typeof defFnOutput[domDriverName] === 'undefined') { + throw new Error('Custom element definition function for \'' + tagName + '\' ' + ('should output an object containing \'' + domDriverName + '\'.')); + } + if (typeof defFnOutput[domDriverName].subscribe !== 'function') { + throw new Error('Custom element definition function for \'' + tagName + '\' ' + 'should output an object containing an Observable of VTree, named ' + ('\'' + domDriverName + '\'.')); + } + for (var _name2 in defFnOutput) { + if (defFnOutput.hasOwnProperty(_name2)) { + if (_name2 !== domDriverName && _name2 !== EVENTS_SINK_NAME) { + throw new Error('Unknown \'' + _name2 + '\' found on custom element ' + ('\'' + tagName + '\'s definition function\'s output.')); + } + } + } +} + +function makeInit(tagName, definitionFn) { + var _require2 = require('./render-dom'); + + var makeDOMDriverWithRegistry = _require2.makeDOMDriverWithRegistry; + + return function initCustomElement() { + //console.log('%cInit() custom element ' + tagName, 'color: #880088'); + var widget = this; + var driverName = widget.driverName; + var registry = widget.customElementsRegistry; + var element = createContainerElement(tagName, widget.properties); + var proxyVTree$ = new Rx.ReplaySubject(1); + var domDriver = makeDOMDriverWithRegistry(element, registry); + var propertiesDriver = makePropertiesDriver(); + var domResponse = domDriver(proxyVTree$, driverName); + var rootElem$ = domResponse.get(':root'); + rootElem$.subscribe(function (rootElem) { + // This is expected to happen before initCustomElement() returns `element` + element = rootElem; + }); + var defFnInput = makeCustomElementInput(domResponse, propertiesDriver, driverName); + var requests = definitionFn(defFnInput); + validateDefFnOutput(requests, driverName, tagName); + widget.disposables.add(requests[driverName].subscribe(proxyVTree$.asObserver())); + widget.disposables.add(rootElem$.subscribe(widget.firstRootElem$.asObserver())); + element.cycleCustomElementMetadata = { + propertiesDriver: propertiesDriver, + rootElem$: rootElem$, + customEvents: requests.events, + eventDispatchingSubscription: false + }; + subscribeEventDispatchingSink(element, widget); + widget.disposables.add(widget.firstRootElem$); + widget.disposables.add(proxyVTree$); + widget.disposables.add(domResponse); + widget.update(null, element); + return element; + }; +} + +function validatePropertiesDriverInMetadata(element, fnName) { + if (!element) { + throw new Error('Missing DOM element when calling ' + fnName + ' on custom ' + 'element Widget.'); + } + if (!element.cycleCustomElementMetadata) { + throw new Error('Missing custom element metadata on DOM element when ' + 'calling ' + fnName + ' on custom element Widget.'); + } + var metadata = element.cycleCustomElementMetadata; + if (metadata.propertiesDriver.type !== 'PropertiesDriver') { + throw new Error('Custom element metadata\'s propertiesDriver type is ' + 'invalid: ' + metadata.propertiesDriver.type + '.'); + } +} + +function updateCustomElement(previous, element) { + if (previous) { + this.disposables = previous.disposables; + this.firstRootElem$.onNext(0); + this.firstRootElem$.onCompleted(); + } + validatePropertiesDriverInMetadata(element, 'update()'); + + //console.log(`%cupdate() ${element.className}`, 'color: #880088'); + var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; + if (propsDriver.hasOwnProperty(ALL_PROPS)) { + propsDriver[ALL_PROPS].onNext(this.properties); + } + for (var prop in propsDriver) { + if (propsDriver.hasOwnProperty(prop)) { + if (this.properties.hasOwnProperty(prop)) { + propsDriver[prop].onNext(this.properties[prop]); + } + } + } +} + +function destroyCustomElement(element) { + //console.log(`%cdestroy() custom el ${element.className}`, 'color: #808'); + // Dispose propertiesDriver + var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; + for (var prop in propsDriver) { + if (propsDriver.hasOwnProperty(prop)) { + this.disposables.add(propsDriver[prop]); + } + } + if (element.cycleCustomElementMetadata.eventDispatchingSubscription) { + // This subscription has to be disposed. + // Because disposing subscribeDispatchersWhenRootChanges only + // is not enough. + this.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); + } + this.disposables.dispose(); +} + +function makeWidgetClass(tagName, definitionFn) { + if (typeof definitionFn !== 'function') { + throw new Error('A custom element definition given to the DOM driver ' + 'should be a function.'); + } + + var WidgetClass = makeConstructor(); + WidgetClass.definitionFn = definitionFn; // needed by renderAsHTML + WidgetClass.prototype.init = makeInit(tagName, definitionFn); + WidgetClass.prototype.update = updateCustomElement; + WidgetClass.prototype.destroy = destroyCustomElement; + return WidgetClass; +} + +module.exports = { + makeDispatchFunction: makeDispatchFunction, + subscribeDispatchers: subscribeDispatchers, + subscribeDispatchersWhenRootChanges: subscribeDispatchersWhenRootChanges, + makePropertiesDriver: makePropertiesDriver, + createContainerElement: createContainerElement, + throwIfVTreeHasPropertyChildren: throwIfVTreeHasPropertyChildren, + makeConstructor: makeConstructor, + makeInit: makeInit, + updateCustomElement: updateCustomElement, + destroyCustomElement: destroyCustomElement, + + ALL_PROPS: ALL_PROPS, + makeCustomElementInput: makeCustomElementInput, + makeWidgetClass: makeWidgetClass +}; +},{"./render-dom":7,"@cycle/core":1}],5:[function(require,module,exports){ +'use strict'; + +var _require = require('./custom-element-widget'); + +var makeWidgetClass = _require.makeWidgetClass; + +var Map = Map || require('es6-map'); // eslint-disable-line no-native-reassign + +function replaceCustomElementsWithSomething(vtree, registry, toSomethingFn) { + // Silently ignore corner cases + if (!vtree) { + return vtree; + } + var tagName = (vtree.tagName || '').toUpperCase(); + // Replace vtree itself + if (tagName && registry.has(tagName)) { + var WidgetClass = registry.get(tagName); + return toSomethingFn(vtree, WidgetClass); + } + // Or replace children recursively + if (Array.isArray(vtree.children)) { + for (var i = vtree.children.length - 1; i >= 0; i--) { + vtree.children[i] = replaceCustomElementsWithSomething(vtree.children[i], registry, toSomethingFn); + } + } + return vtree; +} + +function makeCustomElementsRegistry(definitions) { + var registry = new Map(); + for (var tagName in definitions) { + if (definitions.hasOwnProperty(tagName)) { + registry.set(tagName.toUpperCase(), makeWidgetClass(tagName, definitions[tagName])); + } + } + return registry; +} + +module.exports = { + replaceCustomElementsWithSomething: replaceCustomElementsWithSomething, + makeCustomElementsRegistry: makeCustomElementsRegistry +}; +},{"./custom-element-widget":4,"es6-map":9}],6:[function(require,module,exports){ +'use strict'; +var VirtualDOM = require('virtual-dom'); +var svg = require('virtual-dom/virtual-hyperscript/svg'); + +var _require = require('./render-dom'); + +var makeDOMDriver = _require.makeDOMDriver; + +var _require2 = require('./render-html'); + +var makeHTMLDriver = _require2.makeHTMLDriver; + +var CycleDOM = { + /** + * A factory for the DOM driver function. Takes a `container` to define the + * target on the existing DOM which this driver will operate on. All custom + * elements which this driver can detect should be given as the second + * parameter. The output of this driver is a collection of Observables queried + * by a getter function: `domDriverOutput.get(selector, eventType)` returns an + * Observable of events of `eventType` happening on the element determined by + * `selector`. Also, `domDriverOutput.get(':root')` returns an Observable of + * DOM element corresponding to the root (or container) of the app on the DOM. + * + * @param {(String|HTMLElement)} container the DOM selector for the element + * (or the element itself) to contain the rendering of the VTrees. + * @param {Object} customElements a collection of custom element definitions. + * The key of each property should be the tag name of the custom element, and + * the value should be a function defining the implementation of the custom + * element. This function follows the same contract as the top-most `main` + * function: input are driver responses, output are requests to drivers. + * @return {Function} the DOM driver function. The function expects an + * Observable of VTree as input, and outputs the response object for this + * driver, containing functions `get()` and `dispose()` that can be used for + * debugging and testing. + * @function makeDOMDriver + */ + makeDOMDriver: makeDOMDriver, + + /** + * A factory for the HTML driver function. Takes the registry object of all + * custom elements as the only parameter. The HTML driver function will use + * the custom element registry to detect custom element on the VTree and apply + * their implementations. + * + * @param {Object} customElements a collection of custom element definitions. + * The key of each property should be the tag name of the custom element, and + * the value should be a function defining the implementation of the custom + * element. This function follows the same contract as the top-most `main` + * function: input are driver responses, output are requests to drivers. + * @return {Function} the HTML driver function. The function expects an + * Observable of Virtual DOM elements as input, and outputs an Observable of + * strings as the HTML renderization of the virtual DOM elements. + * @function makeHTMLDriver + */ + makeHTMLDriver: makeHTMLDriver, + + /** + * A shortcut to [virtual-hyperscript]( + * https://github.com/Matt-Esch/virtual-dom/tree/master/virtual-hyperscript). + * This is a helper for creating VTrees in Views. + * @name h + */ + h: VirtualDOM.h, + + /** + * An adapter around virtual-hyperscript `h()` to allow JSX to be used easily + * with Babel. Place the [Babel configuration comment]( + * http://babeljs.io/docs/advanced/transformers/other/react/) `@jsx hJSX` at + * the top of the ES6 file, make sure you import `hJSX` with + * `import {hJSX} from '@cycle/dom'`, and then you can use JSX to create + * VTrees. + * @name hJSX + */ + hJSX: function hJSX(tag, attrs) { + for (var _len = arguments.length, children = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + children[_key - 2] = arguments[_key]; + } + + return VirtualDOM.h(tag, attrs, children); + }, + + /** + * A shortcut to the svg hyperscript function. + * @name svg + */ + svg: svg +}; + +module.exports = CycleDOM; +},{"./render-dom":7,"./render-html":8,"virtual-dom":82,"virtual-dom/virtual-hyperscript/svg":103}],7:[function(require,module,exports){ +'use strict'; + +var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + +var _require = require('@cycle/core'); + +var Rx = _require.Rx; + +var VDOM = { + h: require('virtual-dom').h, + diff: require('virtual-dom/diff'), + patch: require('virtual-dom/patch'), + parse: typeof window !== 'undefined' ? require('vdom-parser') : function () {} +}; + +var _require2 = require('./custom-elements'); + +var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; +var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; + +function isElement(obj) { + return typeof HTMLElement === 'object' ? obj instanceof HTMLElement || obj instanceof DocumentFragment : //DOM2 + obj && typeof obj === 'object' && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === 'string'; +} + +function fixRootElem$(rawRootElem$, domContainer) { + // Create rootElem stream and automatic className correction + var originalClasses = (domContainer.className || '').trim().split(/\s+/); + var originalId = domContainer.id; + //console.log('%coriginalClasses: ' + originalClasses, 'color: lightgray'); + return rawRootElem$.map(function fixRootElemClassNameAndId(rootElem) { + var previousClasses = rootElem.className.trim().split(/\s+/); + var missingClasses = originalClasses.filter(function (clss) { + return previousClasses.indexOf(clss) < 0; + }); + //console.log('%cfixRootElemClassName(), missingClasses: ' + + // missingClasses, 'color: lightgray'); + rootElem.className = previousClasses.concat(missingClasses).join(' '); + rootElem.id = originalId; + //console.log('%c result: ' + rootElem.className, 'color: lightgray'); + //console.log('%cEmit rootElem$ ' + rootElem.tagName + '.' + + // rootElem.className, 'color: #009988'); + return rootElem; + }).replay(null, 1); +} + +function isVTreeCustomElement(vtree) { + return vtree.type === 'Widget' && vtree.isCustomElementWidget; +} + +function makeReplaceCustomElementsWithWidgets(CERegistry, driverName) { + return function replaceCustomElementsWithWidgets(vtree) { + return replaceCustomElementsWithSomething(vtree, CERegistry, function (_vtree, WidgetClass) { + return new WidgetClass(_vtree, CERegistry, driverName); + }); + }; +} + +function getArrayOfAllWidgetFirstRootElem$(vtree) { + if (vtree.type === 'Widget' && vtree.firstRootElem$) { + return [vtree.firstRootElem$]; + } + // Or replace children recursively + var array = []; + if (Array.isArray(vtree.children)) { + for (var i = vtree.children.length - 1; i >= 0; i--) { + array = array.concat(getArrayOfAllWidgetFirstRootElem$(vtree.children[i])); + } + } + return array; +} + +function checkRootVTreeNotCustomElement(vtree) { + if (isVTreeCustomElement(vtree)) { + throw new Error('Illegal to use a Cycle custom element as the root of ' + 'a View.'); + } +} + +function isRootForCustomElement(rootElem) { + return !!rootElem.cycleCustomElementMetadata; +} + +function wrapTopLevelVTree(vtree, rootElem) { + if (isRootForCustomElement(rootElem)) { + return vtree; + } + + var _vtree$properties$id = vtree.properties.id; + var vtreeId = _vtree$properties$id === undefined ? '' : _vtree$properties$id; + var _vtree$properties$className = vtree.properties.className; + var vtreeClass = _vtree$properties$className === undefined ? '' : _vtree$properties$className; + + var sameId = vtreeId === rootElem.id; + var sameClass = vtreeClass === rootElem.className; + var sameTagName = vtree.tagName.toUpperCase() === rootElem.tagName; + if (sameId && sameClass && sameTagName) { + return vtree; + } else { + return VDOM.h(rootElem.tagName, { id: rootElem.id, className: rootElem.className }, [vtree]); + } +} + +function makeDiffAndPatchToElement$(rootElem) { + return function diffAndPatchToElement$(_ref) { + var _ref2 = _slicedToArray(_ref, 2); + + var oldVTree = _ref2[0]; + var newVTree = _ref2[1]; + + if (typeof newVTree === 'undefined') { + return Rx.Observable.empty(); + } + + //let isCustomElement = isRootForCustomElement(rootElem); + //let k = isCustomElement ? ' is custom element ' : ' is top level'; + var prevVTree = wrapTopLevelVTree(oldVTree, rootElem); + var nextVTree = wrapTopLevelVTree(newVTree, rootElem); + var waitForChildrenStreams = getArrayOfAllWidgetFirstRootElem$(nextVTree); + var rootElemAfterChildrenFirstRootElem$ = Rx.Observable.combineLatest(waitForChildrenStreams, function () { + //console.log('%crawRootElem$ emits. (1)' + k, 'color: #008800'); + return rootElem; + }); + var cycleCustomElementMetadata = rootElem.cycleCustomElementMetadata; + //console.log('%cVDOM diff and patch START' + k, 'color: #636300'); + /* eslint-disable */ + rootElem = VDOM.patch(rootElem, VDOM.diff(prevVTree, nextVTree)); + /* eslint-enable */ + //console.log('%cVDOM diff and patch END' + k, 'color: #636300'); + if (cycleCustomElementMetadata) { + rootElem.cycleCustomElementMetadata = cycleCustomElementMetadata; + } + if (waitForChildrenStreams.length === 0) { + //console.log('%crawRootElem$ emits. (2)' + k, 'color: #008800'); + return Rx.Observable.just(rootElem); + } else { + //console.log('%crawRootElem$ waiting children.' + k, 'color: #008800'); + return rootElemAfterChildrenFirstRootElem$; + } + }; +} + +function renderRawRootElem$(vtree$, domContainer, CERegistry, driverName) { + var diffAndPatchToElement$ = makeDiffAndPatchToElement$(domContainer); + return vtree$.startWith(VDOM.parse(domContainer)).map(makeReplaceCustomElementsWithWidgets(CERegistry, driverName)).doOnNext(checkRootVTreeNotCustomElement).pairwise().flatMap(diffAndPatchToElement$); +} + +function makeRootElemToEvent$(selector, eventName) { + return function rootElemToEvent$(rootElem) { + if (!rootElem) { + return Rx.Observable.empty(); + } + //let isCustomElement = !!rootElem.cycleCustomElementMetadata; + //console.log(`%cget('${selector}', '${eventName}') flatMapper` + + // (isCustomElement ? ' for a custom element' : ' for top-level View'), + // 'color: #0000BB'); + var klass = selector.replace('.', ''); + if (rootElem.className.search(new RegExp('\\b' + klass + '\\b')) >= 0) { + //console.log('%c Good return. (A)', 'color:#0000BB'); + //console.log(rootElem); + return Rx.Observable.fromEvent(rootElem, eventName); + } + var targetElements = rootElem.querySelectorAll(selector); + if (targetElements && targetElements.length > 0) { + //console.log('%c Good return. (B)', 'color:#0000BB'); + //console.log(targetElements); + return Rx.Observable.fromEvent(targetElements, eventName); + } else { + //console.log('%c returning empty!', 'color: #0000BB'); + return Rx.Observable.empty(); + } + }; +} + +function makeResponseGetter(rootElem$) { + return function get(selector, eventName) { + if (typeof selector !== 'string') { + throw new Error('DOM driver\'s get() expects first argument to be a ' + 'string as a CSS selector'); + } + if (selector.trim() === ':root') { + return rootElem$; + } + if (typeof eventName !== 'string') { + throw new Error('DOM driver\'s get() expects second argument to be a ' + 'string representing the event type to listen for.'); + } + + //console.log(`%cget("${selector}", "${eventName}")`, 'color: #0000BB'); + return rootElem$.flatMapLatest(makeRootElemToEvent$(selector, eventName)).share(); + }; +} + +function validateDOMDriverInput(vtree$) { + if (!vtree$ || typeof vtree$.subscribe !== 'function') { + throw new Error('The DOM driver function expects as input an ' + 'Observable of virtual DOM elements'); + } +} + +function makeDOMDriverWithRegistry(container, CERegistry) { + return function domDriver(vtree$, driverName) { + validateDOMDriverInput(vtree$); + var rawRootElem$ = renderRawRootElem$(vtree$, container, CERegistry, driverName); + if (!isRootForCustomElement(container)) { + rawRootElem$ = rawRootElem$.startWith(container); + } + var rootElem$ = fixRootElem$(rawRootElem$, container); + var disposable = rootElem$.connect(); + return { + get: makeResponseGetter(rootElem$), + dispose: disposable.dispose.bind(disposable) + }; + }; +} + +function makeDOMDriver(container) { + var customElementDefinitions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + // Find and prepare the container + var domContainer = typeof container === 'string' ? document.querySelector(container) : container; + // Check pre-conditions + if (typeof container === 'string' && domContainer === null) { + throw new Error('Cannot render into unknown element \'' + container + '\''); + } else if (!isElement(domContainer)) { + throw new Error('Given container is not a DOM element neither a selector ' + 'string.'); + } + + var registry = makeCustomElementsRegistry(customElementDefinitions); + return makeDOMDriverWithRegistry(domContainer, registry); +} + +module.exports = { + isElement: isElement, + fixRootElem$: fixRootElem$, + isVTreeCustomElement: isVTreeCustomElement, + makeReplaceCustomElementsWithWidgets: makeReplaceCustomElementsWithWidgets, + getArrayOfAllWidgetFirstRootElem$: getArrayOfAllWidgetFirstRootElem$, + isRootForCustomElement: isRootForCustomElement, + wrapTopLevelVTree: wrapTopLevelVTree, + checkRootVTreeNotCustomElement: checkRootVTreeNotCustomElement, + makeDiffAndPatchToElement$: makeDiffAndPatchToElement$, + renderRawRootElem$: renderRawRootElem$, + makeResponseGetter: makeResponseGetter, + validateDOMDriverInput: validateDOMDriverInput, + makeDOMDriverWithRegistry: makeDOMDriverWithRegistry, + + makeDOMDriver: makeDOMDriver +}; +},{"./custom-elements":5,"@cycle/core":1,"vdom-parser":64,"virtual-dom":82,"virtual-dom/diff":80,"virtual-dom/patch":90}],8:[function(require,module,exports){ +'use strict'; + +var _require = require('@cycle/core'); + +var Rx = _require.Rx; + +var toHTML = require('vdom-to-html'); + +var _require2 = require('./custom-elements'); + +var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; +var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; + +var _require3 = require('./custom-element-widget'); + +var makeCustomElementInput = _require3.makeCustomElementInput; +var ALL_PROPS = _require3.ALL_PROPS; + +function makePropertiesDriverFromVTree(vtree) { + return { + get: function get(propertyName) { + if (propertyName === ALL_PROPS) { + return Rx.Observable.just(vtree.properties); + } else { + return Rx.Observable.just(vtree.properties[propertyName]); + } + } + }; +} + +/** + * Converts a tree of VirtualNode|Observable into + * Observable. + */ +function transposeVTree(vtree) { + if (typeof vtree.subscribe === 'function') { + return vtree; + } else if (vtree.type === 'VirtualText') { + return Rx.Observable.just(vtree); + } else if (vtree.type === 'VirtualNode' && Array.isArray(vtree.children) && vtree.children.length > 0) { + return Rx.Observable.combineLatest(vtree.children.map(transposeVTree), function () { + for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) { + arr[_key] = arguments[_key]; + } + + vtree.children = arr; + return vtree; + }); + } else if (vtree.type === 'VirtualNode') { + return Rx.Observable.just(vtree); + } else { + throw new Error('Unhandled case in transposeVTree()'); + } +} + +function makeReplaceCustomElementsWithVTree$(CERegistry, driverName) { + return function replaceCustomElementsWithVTree$(vtree) { + return replaceCustomElementsWithSomething(vtree, CERegistry, function toVTree$(_vtree, WidgetClass) { + var interactions = { get: function get() { + return Rx.Observable.empty(); + } }; + var props = makePropertiesDriverFromVTree(_vtree); + var input = makeCustomElementInput(interactions, props); + var output = WidgetClass.definitionFn(input); + var vtree$ = output[driverName].last(); + /*eslint-disable no-use-before-define */ + return convertCustomElementsToVTree(vtree$, CERegistry, driverName); + /*eslint-enable no-use-before-define */ + }); + }; +} + +function convertCustomElementsToVTree(vtree$, CERegistry, driverName) { + return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry, driverName)).flatMap(transposeVTree); +} + +function makeResponseGetter() { + return function get(selector) { + if (selector === ':root') { + return this; + } else { + return Rx.Observable.empty(); + } + }; +} + +function makeHTMLDriver() { + var customElementDefinitions = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + + var registry = makeCustomElementsRegistry(customElementDefinitions); + return function htmlDriver(vtree$, driverName) { + var vtreeLast$ = vtree$.last(); + var output$ = convertCustomElementsToVTree(vtreeLast$, registry, driverName).map(function (vtree) { + return toHTML(vtree); + }); + output$.get = makeResponseGetter(); + return output$; + }; +} + +module.exports = { + makePropertiesDriverFromVTree: makePropertiesDriverFromVTree, + makeReplaceCustomElementsWithVTree$: makeReplaceCustomElementsWithVTree$, + convertCustomElementsToVTree: convertCustomElementsToVTree, + + makeHTMLDriver: makeHTMLDriver +}; +},{"./custom-element-widget":4,"./custom-elements":5,"@cycle/core":1,"vdom-to-html":68}],9:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() ? Map : require('./polyfill'); + +},{"./is-implemented":10,"./polyfill":63}],10:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + var map, iterator, result; + if (typeof Map !== 'function') return false; + try { + // WebKit doesn't support arguments and crashes + map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); + } catch (e) { + return false; + } + if (map.size !== 3) return false; + if (typeof map.clear !== 'function') return false; + if (typeof map.delete !== 'function') return false; + if (typeof map.entries !== 'function') return false; + if (typeof map.forEach !== 'function') return false; + if (typeof map.get !== 'function') return false; + if (typeof map.has !== 'function') return false; + if (typeof map.keys !== 'function') return false; + if (typeof map.set !== 'function') return false; + if (typeof map.values !== 'function') return false; + + iterator = map.entries(); + result = iterator.next(); + if (result.done !== false) return false; + if (!result.value) return false; + if (result.value[0] !== 'raz') return false; + if (result.value[1] !== 'one') return false; + return true; +}; + +},{}],11:[function(require,module,exports){ +// Exports true if environment provides native `Map` implementation, +// whatever that is. + +'use strict'; + +module.exports = (function () { + if (typeof Map === 'undefined') return false; + return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); +}()); + +},{}],12:[function(require,module,exports){ +'use strict'; + +module.exports = require('es5-ext/object/primitive-set')('key', + 'value', 'key+value'); + +},{"es5-ext/object/primitive-set":37}],13:[function(require,module,exports){ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('es6-iterator') + , toStringTagSymbol = require('es6-symbol').toStringTag + , kinds = require('./iterator-kinds') + + , defineProperties = Object.defineProperties + , unBind = Iterator.prototype._unBind + , MapIterator; + +MapIterator = module.exports = function (map, kind) { + if (!(this instanceof MapIterator)) return new MapIterator(map, kind); + Iterator.call(this, map.__mapKeysData__, map); + if (!kind || !kinds[kind]) kind = 'key+value'; + defineProperties(this, { + __kind__: d('', kind), + __values__: d('w', map.__mapValuesData__) + }); +}; +if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); + +MapIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(MapIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__values__[i]; + if (this.__kind__ === 'key') return this.__list__[i]; + return [this.__list__[i], this.__values__[i]]; + }), + _unBind: d(function () { + this.__values__ = null; + unBind.call(this); + }), + toString: d(function () { return '[object Map Iterator]'; }) +}); +Object.defineProperty(MapIterator.prototype, toStringTagSymbol, + d('c', 'Map Iterator')); + +},{"./iterator-kinds":12,"d":15,"es5-ext/object/set-prototype-of":38,"es6-iterator":50,"es6-symbol":59}],14:[function(require,module,exports){ +'use strict'; + +var copy = require('es5-ext/object/copy') + , map = require('es5-ext/object/map') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') + + , bind = Function.prototype.bind, defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, bindTo) { + var value = validValue(desc) && callable(desc.value), dgs; + dgs = copy(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (hasOwnProperty.call(this, name)) return value; + desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); + defineProperty(this, name, desc); + return this[name]; + }; + return dgs; +}; + +module.exports = function (props/*, bindTo*/) { + var bindTo = arguments[1]; + return map(props, function (desc, name) { + return define(name, desc, bindTo); + }); +}; + +},{"es5-ext/object/copy":27,"es5-ext/object/map":35,"es5-ext/object/valid-callable":41,"es5-ext/object/valid-value":42}],15:[function(require,module,exports){ +'use strict'; + +var assign = require('es5-ext/object/assign') + , normalizeOpts = require('es5-ext/object/normalize-options') + , isCallable = require('es5-ext/object/is-callable') + , contains = require('es5-ext/string/#/contains') + + , d; + +d = module.exports = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + w = contains.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!isCallable(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!isCallable(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + +},{"es5-ext/object/assign":24,"es5-ext/object/is-callable":30,"es5-ext/object/normalize-options":36,"es5-ext/string/#/contains":43}],16:[function(require,module,exports){ +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + value(this).length = 0; + return this; +}; + +},{"../../object/valid-value":42}],17:[function(require,module,exports){ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , indexOf = Array.prototype.indexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; + +module.exports = function (searchElement/*, fromIndex*/) { + var i, l, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return indexOf.apply(this, arguments); + } + + l = toPosInt(value(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = 0; + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i < l; ++i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; +}; + +},{"../../number/to-pos-integer":22,"../../object/valid-value":42}],18:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sign + : require('./shim'); + +},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + var sign = Math.sign; + if (typeof sign !== 'function') return false; + return ((sign(10) === 1) && (sign(-20) === -1)); +}; + +},{}],20:[function(require,module,exports){ +'use strict'; + +module.exports = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return (value > 0) ? 1 : -1; +}; + +},{}],21:[function(require,module,exports){ +'use strict'; + +var sign = require('../math/sign') + + , abs = Math.abs, floor = Math.floor; + +module.exports = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return sign(value) * floor(abs(value)); +}; + +},{"../math/sign":18}],22:[function(require,module,exports){ +'use strict'; + +var toInteger = require('./to-integer') + + , max = Math.max; + +module.exports = function (value) { return max(0, toInteger(value)); }; + +},{"./to-integer":21}],23:[function(require,module,exports){ +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +'use strict'; + +var callable = require('./valid-callable') + , value = require('./valid-value') + + , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (method, defVal) { + return function (obj, cb/*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable(cb); + + list = keys(obj); + if (compareFn) { + list.sort((typeof compareFn === 'function') ? bind.call(compareFn, obj) : undefined); + } + if (typeof method !== 'function') method = list[method]; + return call.call(method, list, function (key, index) { + if (!propertyIsEnumerable.call(obj, key)) return defVal; + return call.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; + +},{"./valid-callable":41,"./valid-value":42}],24:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.assign + : require('./shim'); + +},{"./is-implemented":25,"./shim":26}],25:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + var assign = Object.assign, obj; + if (typeof assign !== 'function') return false; + obj = { foo: 'raz' }; + assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); + return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; +}; + +},{}],26:[function(require,module,exports){ +'use strict'; + +var keys = require('../keys') + , value = require('../valid-value') + + , max = Math.max; + +module.exports = function (dest, src/*, …srcn*/) { + var error, i, l = max(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function (key) { + try { dest[key] = src[key]; } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < l; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; + +},{"../keys":32,"../valid-value":42}],27:[function(require,module,exports){ +'use strict'; + +var assign = require('./assign') + , value = require('./valid-value'); + +module.exports = function (obj) { + var copy = Object(value(obj)); + if (copy !== obj) return copy; + return assign({}, obj); +}; + +},{"./assign":24,"./valid-value":42}],28:[function(require,module,exports){ +// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 + +'use strict'; + +var create = Object.create, shim; + +if (!require('./set-prototype-of/is-implemented')()) { + shim = require('./set-prototype-of/shim'); +} + +module.exports = (function () { + var nullObject, props, desc; + if (!shim) return create; + if (shim.level !== 1) return create; + + nullObject = {}; + props = {}; + desc = { configurable: false, enumerable: false, writable: true, + value: undefined }; + Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { + if (name === '__proto__') { + props[name] = { configurable: true, enumerable: false, writable: true, + value: undefined }; + return; + } + props[name] = desc; + }); + Object.defineProperties(nullObject, props); + + Object.defineProperty(shim, 'nullPolyfill', { configurable: false, + enumerable: false, writable: false, value: nullObject }); + + return function (prototype, props) { + return create((prototype === null) ? nullObject : prototype, props); + }; +}()); + +},{"./set-prototype-of/is-implemented":39,"./set-prototype-of/shim":40}],29:[function(require,module,exports){ +'use strict'; + +module.exports = require('./_iterate')('forEach'); + +},{"./_iterate":23}],30:[function(require,module,exports){ +// Deprecated + +'use strict'; + +module.exports = function (obj) { return typeof obj === 'function'; }; + +},{}],31:[function(require,module,exports){ +'use strict'; + +var map = { function: true, object: true }; + +module.exports = function (x) { + return ((x != null) && map[typeof x]) || false; +}; + +},{}],32:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.keys + : require('./shim'); + +},{"./is-implemented":33,"./shim":34}],33:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + try { + Object.keys('primitive'); + return true; + } catch (e) { return false; } +}; + +},{}],34:[function(require,module,exports){ +'use strict'; + +var keys = Object.keys; + +module.exports = function (object) { + return keys(object == null ? object : Object(object)); +}; + +},{}],35:[function(require,module,exports){ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + o[key] = call.call(cb, thisArg, value, key, obj, index); + }); + return o; +}; + +},{"./for-each":29,"./valid-callable":41}],36:[function(require,module,exports){ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +var process = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +module.exports = function (options/*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (options == null) return; + process(Object(options), result); + }); + return result; +}; + +},{}],37:[function(require,module,exports){ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +module.exports = function (arg/*, …args*/) { + var set = create(null); + forEach.call(arguments, function (name) { set[name] = true; }); + return set; +}; + +},{}],38:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.setPrototypeOf + : require('./shim'); + +},{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){ +'use strict'; + +var create = Object.create, getPrototypeOf = Object.getPrototypeOf + , x = {}; + +module.exports = function (/*customCreate*/) { + var setPrototypeOf = Object.setPrototypeOf + , customCreate = arguments[0] || create; + if (typeof setPrototypeOf !== 'function') return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; +}; + +},{}],40:[function(require,module,exports){ +// Big thanks to @WebReflection for sorting this out +// https://gist.github.com/WebReflection/5593554 + +'use strict'; + +var isObject = require('../is-object') + , value = require('../valid-value') + + , isPrototypeOf = Object.prototype.isPrototypeOf + , defineProperty = Object.defineProperty + , nullDesc = { configurable: true, enumerable: false, writable: true, + value: undefined } + , validate; + +validate = function (obj, prototype) { + value(obj); + if ((prototype === null) || isObject(prototype)) return obj; + throw new TypeError('Prototype must be null or an object'); +}; + +module.exports = (function (status) { + var fn, set; + if (!status) return null; + if (status.level === 2) { + if (status.set) { + set = status.set; + fn = function (obj, prototype) { + set.call(validate(obj, prototype), prototype); + return obj; + }; + } else { + fn = function (obj, prototype) { + validate(obj, prototype).__proto__ = prototype; + return obj; + }; + } + } else { + fn = function self(obj, prototype) { + var isNullBase; + validate(obj, prototype); + isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); + if (isNullBase) delete self.nullPolyfill.__proto__; + if (prototype === null) prototype = self.nullPolyfill; + obj.__proto__ = prototype; + if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); + return obj; + }; + } + return Object.defineProperty(fn, 'level', { configurable: false, + enumerable: false, writable: false, value: status.level }); +}((function () { + var x = Object.create(null), y = {}, set + , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); + + if (desc) { + try { + set = desc.set; // Opera crashes at this point + set.call(x, y); + } catch (ignore) { } + if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; + } + + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 2 }; + + x = {}; + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 1 }; + + return false; +}()))); + +require('../create'); + +},{"../create":28,"../is-object":31,"../valid-value":42}],41:[function(require,module,exports){ +'use strict'; + +module.exports = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +module.exports = function (value) { + if (value == null) throw new TypeError("Cannot use null or undefined"); + return value; +}; + +},{}],43:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.contains + : require('./shim'); + +},{"./is-implemented":44,"./shim":45}],44:[function(require,module,exports){ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.contains !== 'function') return false; + return ((str.contains('dwa') === true) && (str.contains('foo') === false)); +}; + +},{}],45:[function(require,module,exports){ +'use strict'; + +var indexOf = String.prototype.indexOf; + +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + +},{}],46:[function(require,module,exports){ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(''); + +module.exports = function (x) { + return (typeof x === 'string') || (x && (typeof x === 'object') && + ((x instanceof String) || (toString.call(x) === id))) || false; +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , ArrayIterator; + +ArrayIterator = module.exports = function (arr, kind) { + if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); + Iterator.call(this, arr); + if (!kind) kind = 'value'; + else if (contains.call(kind, 'key+value')) kind = 'key+value'; + else if (contains.call(kind, 'key')) kind = 'key'; + else kind = 'value'; + defineProperty(this, '__kind__', d('', kind)); +}; +if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); + +ArrayIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(ArrayIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__list__[i]; + if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; + return i; + }), + toString: d(function () { return '[object Array Iterator]'; }) +}); + +},{"./":50,"d":15,"es5-ext/object/set-prototype-of":38,"es5-ext/string/#/contains":43}],48:[function(require,module,exports){ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , isString = require('es5-ext/string/is-string') + , get = require('./get') + + , isArray = Array.isArray, call = Function.prototype.call; + +module.exports = function (iterable, cb/*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; + if (isArray(iterable)) mode = 'array'; + else if (isString(iterable)) mode = 'string'; + else iterable = get(iterable); + + callable(cb); + doBreak = function () { broken = true; }; + if (mode === 'array') { + iterable.some(function (value) { + call.call(cb, thisArg, value, doBreak); + if (broken) return true; + }); + return; + } + if (mode === 'string') { + l = iterable.length; + for (i = 0; i < l; ++i) { + char = iterable[i]; + if ((i + 1) < l) { + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; + } + call.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); + + while (!result.done) { + call.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; + +},{"./get":49,"es5-ext/object/valid-callable":41,"es5-ext/string/is-string":46}],49:[function(require,module,exports){ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , ArrayIterator = require('./array') + , StringIterator = require('./string') + , iterable = require('./valid-iterable') + , iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (obj) { + if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); + if (isString(obj)) return new StringIterator(obj); + return new ArrayIterator(obj); +}; + +},{"./array":47,"./string":57,"./valid-iterable":58,"es5-ext/string/is-string":46,"es6-symbol":52}],50:[function(require,module,exports){ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , assign = require('es5-ext/object/assign') + , callable = require('es5-ext/object/valid-callable') + , value = require('es5-ext/object/valid-value') + , d = require('d') + , autoBind = require('d/auto-bind') + , Symbol = require('es6-symbol') + + , defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , Iterator; + +module.exports = Iterator = function (list, context) { + if (!(this instanceof Iterator)) return new Iterator(list, context); + defineProperties(this, { + __list__: d('w', value(list)), + __context__: d('w', context), + __nextIndex__: d('w', 0) + }); + if (!context) return; + callable(context.on); + context.on('_add', this._onAdd); + context.on('_delete', this._onDelete); + context.on('_clear', this._onClear); +}; + +defineProperties(Iterator.prototype, assign({ + constructor: d(Iterator), + _next: d(function () { + var i; + if (!this.__list__) return; + if (this.__redo__) { + i = this.__redo__.shift(); + if (i !== undefined) return i; + } + if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; + this._unBind(); + }), + next: d(function () { return this._createResult(this._next()); }), + _createResult: d(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: d(function (i) { return this.__list__[i]; }), + _unBind: d(function () { + this.__list__ = null; + delete this.__redo__; + if (!this.__context__) return; + this.__context__.off('_add', this._onAdd); + this.__context__.off('_delete', this._onDelete); + this.__context__.off('_clear', this._onClear); + this.__context__ = null; + }), + toString: d(function () { return '[object Iterator]'; }) +}, autoBind({ + _onAdd: d(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + defineProperty(this, '__redo__', d('c', [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: d(function (index) { + var i; + if (index >= this.__nextIndex__) return; + --this.__nextIndex__; + if (!this.__redo__) return; + i = this.__redo__.indexOf(index); + if (i !== -1) this.__redo__.splice(i, 1); + this.__redo__.forEach(function (redo, i) { + if (redo > index) this.__redo__[i] = --redo; + }, this); + }), + _onClear: d(function () { + if (this.__redo__) clear.call(this.__redo__); + this.__nextIndex__ = 0; + }) +}))); + +defineProperty(Iterator.prototype, Symbol.iterator, d(function () { + return this; +})); +defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); + +},{"d":15,"d/auto-bind":14,"es5-ext/array/#/clear":16,"es5-ext/object/assign":24,"es5-ext/object/valid-callable":41,"es5-ext/object/valid-value":42,"es6-symbol":52}],51:[function(require,module,exports){ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , iteratorSymbol = require('es6-symbol').iterator + + , isArray = Array.isArray; + +module.exports = function (value) { + if (value == null) return false; + if (isArray(value)) return true; + if (isString(value)) return true; + return (typeof value[iteratorSymbol] === 'function'); +}; + +},{"es5-ext/string/is-string":46,"es6-symbol":52}],52:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); + +},{"./is-implemented":53,"./polyfill":55}],53:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; + +},{}],54:[function(require,module,exports){ +'use strict'; + +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; + +},{}],55:[function(require,module,exports){ +'use strict'; + +var d = require('d') + , validateSymbol = require('./validate-symbol') + + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty, objPrototype = Object.prototype + , Symbol, HiddenSymbol, globalSymbols = create(null); + +var generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0, name; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + defineProperty(objPrototype, name, d.gs(null, function (value) { + defineProperty(this, name, d(value)); + })); + return name; + }; +}()); + +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); + return Symbol(description); +}; +module.exports = Symbol = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); + symbol = create(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; +defineProperties(Symbol, { + for: d(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = Symbol(String(key))); + }), + keyFor: d(function (s) { + var key; + validateSymbol(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + iterator: d('', Symbol('iterator')), + match: d('', Symbol('match')), + replace: d('', Symbol('replace')), + search: d('', Symbol('search')), + species: d('', Symbol('species')), + split: d('', Symbol('split')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); +defineProperties(HiddenSymbol.prototype, { + constructor: d(Symbol), + toString: d('', function () { return this.__name__; }) +}); + +defineProperties(Symbol.prototype, { + toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), + valueOf: d(function () { return validateSymbol(this); }) +}); +defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function () { return validateSymbol(this); })); +defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); + +defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, + d('c', Symbol.prototype[Symbol.toPrimitive])); +defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, + d('c', Symbol.prototype[Symbol.toStringTag])); + +},{"./validate-symbol":56,"d":15}],56:[function(require,module,exports){ +'use strict'; + +var isSymbol = require('./is-symbol'); + +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; + +},{"./is-symbol":54}],57:[function(require,module,exports){ +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , StringIterator; + +StringIterator = module.exports = function (str) { + if (!(this instanceof StringIterator)) return new StringIterator(str); + str = String(str); + Iterator.call(this, str); + defineProperty(this, '__length__', d('', str.length)); + +}; +if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); + +StringIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(StringIterator), + _next: d(function () { + if (!this.__list__) return; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + }), + _resolve: d(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; + return char; + }), + toString: d(function () { return '[object String Iterator]'; }) +}); + +},{"./":50,"d":15,"es5-ext/object/set-prototype-of":38}],58:[function(require,module,exports){ +'use strict'; + +var isIterable = require('./is-iterable'); + +module.exports = function (value) { + if (!isIterable(value)) throw new TypeError(value + " is not iterable"); + return value; +}; + +},{"./is-iterable":51}],59:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"./is-implemented":60,"./polyfill":61,"dup":52}],60:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.isRegExp !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; + +},{}],61:[function(require,module,exports){ +'use strict'; + +var d = require('d') + + , create = Object.create, defineProperties = Object.defineProperties + , generateName, Symbol; + +generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + return '@@' + desc; + }; +}()); + +module.exports = Symbol = function (description) { + var symbol; + if (this instanceof Symbol) { + throw new TypeError('TypeError: Symbol is not a constructor'); + } + symbol = create(Symbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; + +Object.defineProperties(Symbol, { + create: d('', Symbol('create')), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + isRegExp: d('', Symbol('isRegExp')), + iterator: d('', Symbol('iterator')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); + +defineProperties(Symbol.prototype, { + properToString: d(function () { + return 'Symbol (' + this.__description__ + ')'; + }), + toString: d('', function () { return this.__name__; }) +}); +Object.defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function (hint) { + throw new TypeError("Conversion of symbol objects is not allowed"); + })); +Object.defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); + +},{"d":15}],62:[function(require,module,exports){ +'use strict'; + +var d = require('d') + , callable = require('es5-ext/object/valid-callable') + + , apply = Function.prototype.apply, call = Function.prototype.call + , create = Object.create, defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , hasOwnProperty = Object.prototype.hasOwnProperty + , descriptor = { configurable: true, enumerable: false, writable: true } + + , on, once, off, emit, methods, descriptors, base; + +on = function (type, listener) { + var data; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) { + data = descriptor.value = create(null); + defineProperty(this, '__ee__', descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type]) data[type] = listener; + else if (typeof data[type] === 'object') data[type].push(listener); + else data[type] = [data[type], listener]; + + return this; +}; + +once = function (type, listener) { + var once, self; + + callable(listener); + self = this; + on.call(this, type, once = function () { + off.call(self, type, once); + apply.call(listener, this, arguments); + }); + + once.__eeOnceListener__ = listener; + return this; +}; + +off = function (type, listener) { + var data, listeners, candidate, i; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) return this; + data = this.__ee__; + if (!data[type]) return this; + listeners = data[type]; + + if (typeof listeners === 'object') { + for (i = 0; (candidate = listeners[i]); ++i) { + if ((candidate === listener) || + (candidate.__eeOnceListener__ === listener)) { + if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; + else listeners.splice(i, 1); + } + } + } else { + if ((listeners === listener) || + (listeners.__eeOnceListener__ === listener)) { + delete data[type]; + } + } + + return this; +}; + +emit = function (type) { + var i, l, listener, listeners, args; + + if (!hasOwnProperty.call(this, '__ee__')) return; + listeners = this.__ee__[type]; + if (!listeners) return; + + if (typeof listeners === 'object') { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + + listeners = listeners.slice(); + for (i = 0; (listener = listeners[i]); ++i) { + apply.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call.call(listeners, this); + break; + case 2: + call.call(listeners, this, arguments[1]); + break; + case 3: + call.call(listeners, this, arguments[1], arguments[2]); + break; + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply.call(listeners, this, args); + } + } +}; + +methods = { + on: on, + once: once, + off: off, + emit: emit +}; + +descriptors = { + on: d(on), + once: d(once), + off: d(off), + emit: d(emit) +}; + +base = defineProperties({}, descriptors); + +module.exports = exports = function (o) { + return (o == null) ? create(base) : defineProperties(Object(o), descriptors); +}; +exports.methods = methods; + +},{"d":15,"es5-ext/object/valid-callable":41}],63:[function(require,module,exports){ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , eIndexOf = require('es5-ext/array/#/e-index-of') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') + , d = require('d') + , ee = require('event-emitter') + , Symbol = require('es6-symbol') + , iterator = require('es6-iterator/valid-iterable') + , forOf = require('es6-iterator/for-of') + , Iterator = require('./lib/iterator') + , isNative = require('./is-native-implemented') + + , call = Function.prototype.call, defineProperties = Object.defineProperties + , MapPoly; + +module.exports = MapPoly = function (/*iterable*/) { + var iterable = arguments[0], keys, values; + if (!(this instanceof MapPoly)) return new MapPoly(iterable); + if (this.__mapKeysData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) iterator(iterable); + defineProperties(this, { + __mapKeysData__: d('c', keys = []), + __mapValuesData__: d('c', values = []) + }); + if (!iterable) return; + forOf(iterable, function (value) { + var key = validValue(value)[0]; + value = value[1]; + if (eIndexOf.call(keys, key) !== -1) return; + keys.push(key); + values.push(value); + }, this); +}; + +if (isNative) { + if (setPrototypeOf) setPrototypeOf(MapPoly, Map); + MapPoly.prototype = Object.create(Map.prototype, { + constructor: d(MapPoly) + }); +} + +ee(defineProperties(MapPoly.prototype, { + clear: d(function () { + if (!this.__mapKeysData__.length) return; + clear.call(this.__mapKeysData__); + clear.call(this.__mapValuesData__); + this.emit('_clear'); + }), + delete: d(function (key) { + var index = eIndexOf.call(this.__mapKeysData__, key); + if (index === -1) return false; + this.__mapKeysData__.splice(index, 1); + this.__mapValuesData__.splice(index, 1); + this.emit('_delete', index, key); + return true; + }), + entries: d(function () { return new Iterator(this, 'key+value'); }), + forEach: d(function (cb/*, thisArg*/) { + var thisArg = arguments[1], iterator, result; + callable(cb); + iterator = this.entries(); + result = iterator._next(); + while (result !== undefined) { + call.call(cb, thisArg, this.__mapValuesData__[result], + this.__mapKeysData__[result], this); + result = iterator._next(); + } + }), + get: d(function (key) { + var index = eIndexOf.call(this.__mapKeysData__, key); + if (index === -1) return; + return this.__mapValuesData__[index]; + }), + has: d(function (key) { + return (eIndexOf.call(this.__mapKeysData__, key) !== -1); + }), + keys: d(function () { return new Iterator(this, 'key'); }), + set: d(function (key, value) { + var index = eIndexOf.call(this.__mapKeysData__, key), emit; + if (index === -1) { + index = this.__mapKeysData__.push(key) - 1; + emit = true; + } + this.__mapValuesData__[index] = value; + if (emit) this.emit('_add', index, key); + return this; + }), + size: d.gs(function () { return this.__mapKeysData__.length; }), + values: d(function () { return new Iterator(this, 'value'); }), + toString: d(function () { return '[object Map]'; }) +})); +Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { + return this.entries(); +})); +Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); + +},{"./is-native-implemented":11,"./lib/iterator":13,"d":15,"es5-ext/array/#/clear":16,"es5-ext/array/#/e-index-of":17,"es5-ext/object/set-prototype-of":38,"es5-ext/object/valid-callable":41,"es5-ext/object/valid-value":42,"es6-iterator/for-of":48,"es6-iterator/valid-iterable":58,"es6-symbol":59,"event-emitter":62}],64:[function(require,module,exports){ + +/** + * index.js + * + * A client-side DOM to vdom parser based on DOMParser API + */ + +'use strict'; + +var VNode = require('virtual-dom/vnode/vnode'); +var VText = require('virtual-dom/vnode/vtext'); +var domParser; + +var propertyMap = require('./property-map'); +var namespaceMap = require('./namespace-map'); + +var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; + +module.exports = parser; + +/** + * DOM/html string to vdom parser + * + * @param Mixed el DOM element or html string + * @param String attr Attribute name that contains vdom key + * @return Object VNode or VText + */ +function parser(el, attr) { + // empty input fallback to empty text node + if (!el) { + return createNode(document.createTextNode('')); + } + + if (typeof el === 'string') { + if ( !('DOMParser' in window) ) { + throw new Error('DOMParser is not available, so parsing string to DOM node is not possible.'); + } + domParser = domParser || new DOMParser(); + var doc = domParser.parseFromString(el, 'text/html'); + + // most tags default to body + if (doc.body.firstChild) { + el = doc.getElementsByTagName('body')[0].firstChild; + + // some tags, like script and style, default to head + } else if (doc.head.firstChild && (doc.head.firstChild.tagName !== 'TITLE' || doc.title)) { + el = doc.head.firstChild; + + // special case for html comment, cdata, doctype + } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { + el = doc.firstChild; + + // other element, such as whitespace, or html/body/head tag, fallback to empty text node + } else { + el = document.createTextNode(''); + } + } + + if (typeof el !== 'object' || !el || !el.nodeType) { + throw new Error('invalid dom node', el); + } + + return createNode(el, attr); +} + +/** + * Create vdom from dom node + * + * @param Object el DOM element + * @param String attr Attribute name that contains vdom key + * @return Object VNode or VText + */ +function createNode(el, attr) { + // html comment is not currently supported by virtual-dom + if (el.nodeType === 3) { + return createVirtualTextNode(el); + + // cdata or doctype is not currently supported by virtual-dom + } else if (el.nodeType === 1 || el.nodeType === 9) { + return createVirtualDomNode(el, attr); + } + + // default to empty text node + return new VText(''); +} + +/** + * Create vtext from dom node + * + * @param Object el Text node + * @return Object VText + */ +function createVirtualTextNode(el) { + return new VText(el.nodeValue); +} + +/** + * Create vnode from dom node + * + * @param Object el DOM element + * @param String attr Attribute name that contains vdom key + * @return Object VNode + */ +function createVirtualDomNode(el, attr) { + var ns = el.namespaceURI !== HTML_NAMESPACE ? el.namespaceURI : null; + var key = attr && el.getAttribute(attr) ? el.getAttribute(attr) : null; + + return new VNode( + el.tagName + , createProperties(el) + , createChildren(el, attr) + , key + , ns + ); +} + +/** + * Recursively create vdom + * + * @param Object el Parent element + * @param String attr Attribute name that contains vdom key + * @return Array Child vnode or vtext + */ +function createChildren(el, attr) { + var children = []; + for (var i = 0; i < el.childNodes.length; i++) { + children.push(createNode(el.childNodes[i], attr)); + }; + + return children; +} + +/** + * Create properties from dom node + * + * @param Object el DOM element + * @return Object Node properties and attributes + */ +function createProperties(el) { + var properties = {}; + + if (!el.hasAttributes()) { + return properties; + } + + var ns; + if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) { + ns = el.namespaceURI; + } + + var attr; + for (var i = 0; i < el.attributes.length; i++) { + // use built in css style parsing + if(el.attributes[i].name == 'style'){ + var style = el.style; + var output = {}; + for (var i = 0; i < style.length; ++i) { + var item = style.item(i); + output[item] = style[item]; + // hack to workaround browser inconsistency with url() + if (output[item].indexOf('url') > -1) { + output[item] = output[item].replace(/\"/g, '') + } + } + attr = {name: 'style', value: output}; + } + else if (ns) { + attr = createPropertyNS(el.attributes[i]); + } else { + attr = createProperty(el.attributes[i]); + } + + // special case, namespaced attribute, use properties.foobar + if (attr.ns) { + properties[attr.name] = { + namespace: attr.ns + , value: attr.value + }; + + // special case, use properties.attributes.foobar + } else if (attr.isAttr) { + // init attributes object only when necessary + if (!properties.attributes) { + properties.attributes = {} + } + properties.attributes[attr.name] = attr.value; + + // default case, use properties.foobar + } else { + properties[attr.name] = attr.value; + } + }; + + return properties; +} + +/** + * Create property from dom attribute + * + * @param Object attr DOM attribute + * @return Object Normalized attribute + */ +function createProperty(attr) { + var name, value, isAttr; + + // using a map to find the correct case of property name + if (propertyMap[attr.name]) { + name = propertyMap[attr.name]; + } else { + name = attr.name; + } + // special cases for data attribute, we default to properties.attributes.data + if (name.indexOf('data-') === 0) { + value = attr.value; + isAttr = true; + } else { + value = attr.value; + } + + return { + name: name + , value: value + , isAttr: isAttr || false + }; +} + +/** + * Create namespaced property from dom attribute + * + * @param Object attr DOM attribute + * @return Object Normalized attribute + */ +function createPropertyNS(attr) { + var name, value; + + return { + name: attr.name + , value: attr.value + , ns: namespaceMap[attr.name] || '' + }; +} + +},{"./namespace-map":65,"./property-map":66,"virtual-dom/vnode/vnode":111,"virtual-dom/vnode/vtext":113}],65:[function(require,module,exports){ + +/** + * namespace-map.js + * + * Necessary to map svg attributes back to their namespace + */ + +'use strict'; + +// extracted from https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/svg-attribute-namespace.js +var DEFAULT_NAMESPACE = null; +var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; +var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; +var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; + +var namespaces = { + 'about': DEFAULT_NAMESPACE + , 'accent-height': DEFAULT_NAMESPACE + , 'accumulate': DEFAULT_NAMESPACE + , 'additive': DEFAULT_NAMESPACE + , 'alignment-baseline': DEFAULT_NAMESPACE + , 'alphabetic': DEFAULT_NAMESPACE + , 'amplitude': DEFAULT_NAMESPACE + , 'arabic-form': DEFAULT_NAMESPACE + , 'ascent': DEFAULT_NAMESPACE + , 'attributeName': DEFAULT_NAMESPACE + , 'attributeType': DEFAULT_NAMESPACE + , 'azimuth': DEFAULT_NAMESPACE + , 'bandwidth': DEFAULT_NAMESPACE + , 'baseFrequency': DEFAULT_NAMESPACE + , 'baseProfile': DEFAULT_NAMESPACE + , 'baseline-shift': DEFAULT_NAMESPACE + , 'bbox': DEFAULT_NAMESPACE + , 'begin': DEFAULT_NAMESPACE + , 'bias': DEFAULT_NAMESPACE + , 'by': DEFAULT_NAMESPACE + , 'calcMode': DEFAULT_NAMESPACE + , 'cap-height': DEFAULT_NAMESPACE + , 'class': DEFAULT_NAMESPACE + , 'clip': DEFAULT_NAMESPACE + , 'clip-path': DEFAULT_NAMESPACE + , 'clip-rule': DEFAULT_NAMESPACE + , 'clipPathUnits': DEFAULT_NAMESPACE + , 'color': DEFAULT_NAMESPACE + , 'color-interpolation': DEFAULT_NAMESPACE + , 'color-interpolation-filters': DEFAULT_NAMESPACE + , 'color-profile': DEFAULT_NAMESPACE + , 'color-rendering': DEFAULT_NAMESPACE + , 'content': DEFAULT_NAMESPACE + , 'contentScriptType': DEFAULT_NAMESPACE + , 'contentStyleType': DEFAULT_NAMESPACE + , 'cursor': DEFAULT_NAMESPACE + , 'cx': DEFAULT_NAMESPACE + , 'cy': DEFAULT_NAMESPACE + , 'd': DEFAULT_NAMESPACE + , 'datatype': DEFAULT_NAMESPACE + , 'defaultAction': DEFAULT_NAMESPACE + , 'descent': DEFAULT_NAMESPACE + , 'diffuseConstant': DEFAULT_NAMESPACE + , 'direction': DEFAULT_NAMESPACE + , 'display': DEFAULT_NAMESPACE + , 'divisor': DEFAULT_NAMESPACE + , 'dominant-baseline': DEFAULT_NAMESPACE + , 'dur': DEFAULT_NAMESPACE + , 'dx': DEFAULT_NAMESPACE + , 'dy': DEFAULT_NAMESPACE + , 'edgeMode': DEFAULT_NAMESPACE + , 'editable': DEFAULT_NAMESPACE + , 'elevation': DEFAULT_NAMESPACE + , 'enable-background': DEFAULT_NAMESPACE + , 'end': DEFAULT_NAMESPACE + , 'ev:event': EV_NAMESPACE + , 'event': DEFAULT_NAMESPACE + , 'exponent': DEFAULT_NAMESPACE + , 'externalResourcesRequired': DEFAULT_NAMESPACE + , 'fill': DEFAULT_NAMESPACE + , 'fill-opacity': DEFAULT_NAMESPACE + , 'fill-rule': DEFAULT_NAMESPACE + , 'filter': DEFAULT_NAMESPACE + , 'filterRes': DEFAULT_NAMESPACE + , 'filterUnits': DEFAULT_NAMESPACE + , 'flood-color': DEFAULT_NAMESPACE + , 'flood-opacity': DEFAULT_NAMESPACE + , 'focusHighlight': DEFAULT_NAMESPACE + , 'focusable': DEFAULT_NAMESPACE + , 'font-family': DEFAULT_NAMESPACE + , 'font-size': DEFAULT_NAMESPACE + , 'font-size-adjust': DEFAULT_NAMESPACE + , 'font-stretch': DEFAULT_NAMESPACE + , 'font-style': DEFAULT_NAMESPACE + , 'font-variant': DEFAULT_NAMESPACE + , 'font-weight': DEFAULT_NAMESPACE + , 'format': DEFAULT_NAMESPACE + , 'from': DEFAULT_NAMESPACE + , 'fx': DEFAULT_NAMESPACE + , 'fy': DEFAULT_NAMESPACE + , 'g1': DEFAULT_NAMESPACE + , 'g2': DEFAULT_NAMESPACE + , 'glyph-name': DEFAULT_NAMESPACE + , 'glyph-orientation-horizontal': DEFAULT_NAMESPACE + , 'glyph-orientation-vertical': DEFAULT_NAMESPACE + , 'glyphRef': DEFAULT_NAMESPACE + , 'gradientTransform': DEFAULT_NAMESPACE + , 'gradientUnits': DEFAULT_NAMESPACE + , 'handler': DEFAULT_NAMESPACE + , 'hanging': DEFAULT_NAMESPACE + , 'height': DEFAULT_NAMESPACE + , 'horiz-adv-x': DEFAULT_NAMESPACE + , 'horiz-origin-x': DEFAULT_NAMESPACE + , 'horiz-origin-y': DEFAULT_NAMESPACE + , 'id': DEFAULT_NAMESPACE + , 'ideographic': DEFAULT_NAMESPACE + , 'image-rendering': DEFAULT_NAMESPACE + , 'in': DEFAULT_NAMESPACE + , 'in2': DEFAULT_NAMESPACE + , 'initialVisibility': DEFAULT_NAMESPACE + , 'intercept': DEFAULT_NAMESPACE + , 'k': DEFAULT_NAMESPACE + , 'k1': DEFAULT_NAMESPACE + , 'k2': DEFAULT_NAMESPACE + , 'k3': DEFAULT_NAMESPACE + , 'k4': DEFAULT_NAMESPACE + , 'kernelMatrix': DEFAULT_NAMESPACE + , 'kernelUnitLength': DEFAULT_NAMESPACE + , 'kerning': DEFAULT_NAMESPACE + , 'keyPoints': DEFAULT_NAMESPACE + , 'keySplines': DEFAULT_NAMESPACE + , 'keyTimes': DEFAULT_NAMESPACE + , 'lang': DEFAULT_NAMESPACE + , 'lengthAdjust': DEFAULT_NAMESPACE + , 'letter-spacing': DEFAULT_NAMESPACE + , 'lighting-color': DEFAULT_NAMESPACE + , 'limitingConeAngle': DEFAULT_NAMESPACE + , 'local': DEFAULT_NAMESPACE + , 'marker-end': DEFAULT_NAMESPACE + , 'marker-mid': DEFAULT_NAMESPACE + , 'marker-start': DEFAULT_NAMESPACE + , 'markerHeight': DEFAULT_NAMESPACE + , 'markerUnits': DEFAULT_NAMESPACE + , 'markerWidth': DEFAULT_NAMESPACE + , 'mask': DEFAULT_NAMESPACE + , 'maskContentUnits': DEFAULT_NAMESPACE + , 'maskUnits': DEFAULT_NAMESPACE + , 'mathematical': DEFAULT_NAMESPACE + , 'max': DEFAULT_NAMESPACE + , 'media': DEFAULT_NAMESPACE + , 'mediaCharacterEncoding': DEFAULT_NAMESPACE + , 'mediaContentEncodings': DEFAULT_NAMESPACE + , 'mediaSize': DEFAULT_NAMESPACE + , 'mediaTime': DEFAULT_NAMESPACE + , 'method': DEFAULT_NAMESPACE + , 'min': DEFAULT_NAMESPACE + , 'mode': DEFAULT_NAMESPACE + , 'name': DEFAULT_NAMESPACE + , 'nav-down': DEFAULT_NAMESPACE + , 'nav-down-left': DEFAULT_NAMESPACE + , 'nav-down-right': DEFAULT_NAMESPACE + , 'nav-left': DEFAULT_NAMESPACE + , 'nav-next': DEFAULT_NAMESPACE + , 'nav-prev': DEFAULT_NAMESPACE + , 'nav-right': DEFAULT_NAMESPACE + , 'nav-up': DEFAULT_NAMESPACE + , 'nav-up-left': DEFAULT_NAMESPACE + , 'nav-up-right': DEFAULT_NAMESPACE + , 'numOctaves': DEFAULT_NAMESPACE + , 'observer': DEFAULT_NAMESPACE + , 'offset': DEFAULT_NAMESPACE + , 'opacity': DEFAULT_NAMESPACE + , 'operator': DEFAULT_NAMESPACE + , 'order': DEFAULT_NAMESPACE + , 'orient': DEFAULT_NAMESPACE + , 'orientation': DEFAULT_NAMESPACE + , 'origin': DEFAULT_NAMESPACE + , 'overflow': DEFAULT_NAMESPACE + , 'overlay': DEFAULT_NAMESPACE + , 'overline-position': DEFAULT_NAMESPACE + , 'overline-thickness': DEFAULT_NAMESPACE + , 'panose-1': DEFAULT_NAMESPACE + , 'path': DEFAULT_NAMESPACE + , 'pathLength': DEFAULT_NAMESPACE + , 'patternContentUnits': DEFAULT_NAMESPACE + , 'patternTransform': DEFAULT_NAMESPACE + , 'patternUnits': DEFAULT_NAMESPACE + , 'phase': DEFAULT_NAMESPACE + , 'playbackOrder': DEFAULT_NAMESPACE + , 'pointer-events': DEFAULT_NAMESPACE + , 'points': DEFAULT_NAMESPACE + , 'pointsAtX': DEFAULT_NAMESPACE + , 'pointsAtY': DEFAULT_NAMESPACE + , 'pointsAtZ': DEFAULT_NAMESPACE + , 'preserveAlpha': DEFAULT_NAMESPACE + , 'preserveAspectRatio': DEFAULT_NAMESPACE + , 'primitiveUnits': DEFAULT_NAMESPACE + , 'propagate': DEFAULT_NAMESPACE + , 'property': DEFAULT_NAMESPACE + , 'r': DEFAULT_NAMESPACE + , 'radius': DEFAULT_NAMESPACE + , 'refX': DEFAULT_NAMESPACE + , 'refY': DEFAULT_NAMESPACE + , 'rel': DEFAULT_NAMESPACE + , 'rendering-intent': DEFAULT_NAMESPACE + , 'repeatCount': DEFAULT_NAMESPACE + , 'repeatDur': DEFAULT_NAMESPACE + , 'requiredExtensions': DEFAULT_NAMESPACE + , 'requiredFeatures': DEFAULT_NAMESPACE + , 'requiredFonts': DEFAULT_NAMESPACE + , 'requiredFormats': DEFAULT_NAMESPACE + , 'resource': DEFAULT_NAMESPACE + , 'restart': DEFAULT_NAMESPACE + , 'result': DEFAULT_NAMESPACE + , 'rev': DEFAULT_NAMESPACE + , 'role': DEFAULT_NAMESPACE + , 'rotate': DEFAULT_NAMESPACE + , 'rx': DEFAULT_NAMESPACE + , 'ry': DEFAULT_NAMESPACE + , 'scale': DEFAULT_NAMESPACE + , 'seed': DEFAULT_NAMESPACE + , 'shape-rendering': DEFAULT_NAMESPACE + , 'slope': DEFAULT_NAMESPACE + , 'snapshotTime': DEFAULT_NAMESPACE + , 'spacing': DEFAULT_NAMESPACE + , 'specularConstant': DEFAULT_NAMESPACE + , 'specularExponent': DEFAULT_NAMESPACE + , 'spreadMethod': DEFAULT_NAMESPACE + , 'startOffset': DEFAULT_NAMESPACE + , 'stdDeviation': DEFAULT_NAMESPACE + , 'stemh': DEFAULT_NAMESPACE + , 'stemv': DEFAULT_NAMESPACE + , 'stitchTiles': DEFAULT_NAMESPACE + , 'stop-color': DEFAULT_NAMESPACE + , 'stop-opacity': DEFAULT_NAMESPACE + , 'strikethrough-position': DEFAULT_NAMESPACE + , 'strikethrough-thickness': DEFAULT_NAMESPACE + , 'string': DEFAULT_NAMESPACE + , 'stroke': DEFAULT_NAMESPACE + , 'stroke-dasharray': DEFAULT_NAMESPACE + , 'stroke-dashoffset': DEFAULT_NAMESPACE + , 'stroke-linecap': DEFAULT_NAMESPACE + , 'stroke-linejoin': DEFAULT_NAMESPACE + , 'stroke-miterlimit': DEFAULT_NAMESPACE + , 'stroke-opacity': DEFAULT_NAMESPACE + , 'stroke-width': DEFAULT_NAMESPACE + , 'surfaceScale': DEFAULT_NAMESPACE + , 'syncBehavior': DEFAULT_NAMESPACE + , 'syncBehaviorDefault': DEFAULT_NAMESPACE + , 'syncMaster': DEFAULT_NAMESPACE + , 'syncTolerance': DEFAULT_NAMESPACE + , 'syncToleranceDefault': DEFAULT_NAMESPACE + , 'systemLanguage': DEFAULT_NAMESPACE + , 'tableValues': DEFAULT_NAMESPACE + , 'target': DEFAULT_NAMESPACE + , 'targetX': DEFAULT_NAMESPACE + , 'targetY': DEFAULT_NAMESPACE + , 'text-anchor': DEFAULT_NAMESPACE + , 'text-decoration': DEFAULT_NAMESPACE + , 'text-rendering': DEFAULT_NAMESPACE + , 'textLength': DEFAULT_NAMESPACE + , 'timelineBegin': DEFAULT_NAMESPACE + , 'title': DEFAULT_NAMESPACE + , 'to': DEFAULT_NAMESPACE + , 'transform': DEFAULT_NAMESPACE + , 'transformBehavior': DEFAULT_NAMESPACE + , 'type': DEFAULT_NAMESPACE + , 'typeof': DEFAULT_NAMESPACE + , 'u1': DEFAULT_NAMESPACE + , 'u2': DEFAULT_NAMESPACE + , 'underline-position': DEFAULT_NAMESPACE + , 'underline-thickness': DEFAULT_NAMESPACE + , 'unicode': DEFAULT_NAMESPACE + , 'unicode-bidi': DEFAULT_NAMESPACE + , 'unicode-range': DEFAULT_NAMESPACE + , 'units-per-em': DEFAULT_NAMESPACE + , 'v-alphabetic': DEFAULT_NAMESPACE + , 'v-hanging': DEFAULT_NAMESPACE + , 'v-ideographic': DEFAULT_NAMESPACE + , 'v-mathematical': DEFAULT_NAMESPACE + , 'values': DEFAULT_NAMESPACE + , 'version': DEFAULT_NAMESPACE + , 'vert-adv-y': DEFAULT_NAMESPACE + , 'vert-origin-x': DEFAULT_NAMESPACE + , 'vert-origin-y': DEFAULT_NAMESPACE + , 'viewBox': DEFAULT_NAMESPACE + , 'viewTarget': DEFAULT_NAMESPACE + , 'visibility': DEFAULT_NAMESPACE + , 'width': DEFAULT_NAMESPACE + , 'widths': DEFAULT_NAMESPACE + , 'word-spacing': DEFAULT_NAMESPACE + , 'writing-mode': DEFAULT_NAMESPACE + , 'x': DEFAULT_NAMESPACE + , 'x-height': DEFAULT_NAMESPACE + , 'x1': DEFAULT_NAMESPACE + , 'x2': DEFAULT_NAMESPACE + , 'xChannelSelector': DEFAULT_NAMESPACE + , 'xlink:actuate': XLINK_NAMESPACE + , 'xlink:arcrole': XLINK_NAMESPACE + , 'xlink:href': XLINK_NAMESPACE + , 'xlink:role': XLINK_NAMESPACE + , 'xlink:show': XLINK_NAMESPACE + , 'xlink:title': XLINK_NAMESPACE + , 'xlink:type': XLINK_NAMESPACE + , 'xml:base': XML_NAMESPACE + , 'xml:id': XML_NAMESPACE + , 'xml:lang': XML_NAMESPACE + , 'xml:space': XML_NAMESPACE + , 'y': DEFAULT_NAMESPACE + , 'y1': DEFAULT_NAMESPACE + , 'y2': DEFAULT_NAMESPACE + , 'yChannelSelector': DEFAULT_NAMESPACE + , 'z': DEFAULT_NAMESPACE + , 'zoomAndPan': DEFAULT_NAMESPACE +}; + +module.exports = namespaces; + +},{}],66:[function(require,module,exports){ + +/** + * property-map.js + * + * Necessary to map dom attributes back to vdom properties + */ + +'use strict'; + +// invert of https://www.npmjs.com/package/html-attributes +var properties = { + 'abbr': 'abbr' + , 'accept': 'accept' + , 'accept-charset': 'acceptCharset' + , 'accesskey': 'accessKey' + , 'action': 'action' + , 'allowfullscreen': 'allowFullScreen' + , 'allowtransparency': 'allowTransparency' + , 'alt': 'alt' + , 'async': 'async' + , 'autocomplete': 'autoComplete' + , 'autofocus': 'autoFocus' + , 'autoplay': 'autoPlay' + , 'cellpadding': 'cellPadding' + , 'cellspacing': 'cellSpacing' + , 'challenge': 'challenge' + , 'charset': 'charset' + , 'checked': 'checked' + , 'cite': 'cite' + , 'class': 'className' + , 'cols': 'cols' + , 'colspan': 'colSpan' + , 'command': 'command' + , 'content': 'content' + , 'contenteditable': 'contentEditable' + , 'contextmenu': 'contextMenu' + , 'controls': 'controls' + , 'coords': 'coords' + , 'crossorigin': 'crossOrigin' + , 'data': 'data' + , 'datetime': 'dateTime' + , 'default': 'default' + , 'defer': 'defer' + , 'dir': 'dir' + , 'disabled': 'disabled' + , 'download': 'download' + , 'draggable': 'draggable' + , 'dropzone': 'dropzone' + , 'enctype': 'encType' + , 'for': 'htmlFor' + , 'form': 'form' + , 'formaction': 'formAction' + , 'formenctype': 'formEncType' + , 'formmethod': 'formMethod' + , 'formnovalidate': 'formNoValidate' + , 'formtarget': 'formTarget' + , 'frameBorder': 'frameBorder' + , 'headers': 'headers' + , 'height': 'height' + , 'hidden': 'hidden' + , 'high': 'high' + , 'href': 'href' + , 'hreflang': 'hrefLang' + , 'http-equiv': 'httpEquiv' + , 'icon': 'icon' + , 'id': 'id' + , 'inputmode': 'inputMode' + , 'ismap': 'isMap' + , 'itemid': 'itemId' + , 'itemprop': 'itemProp' + , 'itemref': 'itemRef' + , 'itemscope': 'itemScope' + , 'itemtype': 'itemType' + , 'kind': 'kind' + , 'label': 'label' + , 'lang': 'lang' + , 'list': 'list' + , 'loop': 'loop' + , 'manifest': 'manifest' + , 'max': 'max' + , 'maxlength': 'maxLength' + , 'media': 'media' + , 'mediagroup': 'mediaGroup' + , 'method': 'method' + , 'min': 'min' + , 'minlength': 'minLength' + , 'multiple': 'multiple' + , 'muted': 'muted' + , 'name': 'name' + , 'novalidate': 'noValidate' + , 'open': 'open' + , 'optimum': 'optimum' + , 'pattern': 'pattern' + , 'ping': 'ping' + , 'placeholder': 'placeholder' + , 'poster': 'poster' + , 'preload': 'preload' + , 'radiogroup': 'radioGroup' + , 'readonly': 'readOnly' + , 'rel': 'rel' + , 'required': 'required' + , 'role': 'role' + , 'rows': 'rows' + , 'rowspan': 'rowSpan' + , 'sandbox': 'sandbox' + , 'scope': 'scope' + , 'scoped': 'scoped' + , 'scrolling': 'scrolling' + , 'seamless': 'seamless' + , 'selected': 'selected' + , 'shape': 'shape' + , 'size': 'size' + , 'sizes': 'sizes' + , 'sortable': 'sortable' + , 'span': 'span' + , 'spellcheck': 'spellCheck' + , 'src': 'src' + , 'srcdoc': 'srcDoc' + , 'srcset': 'srcSet' + , 'start': 'start' + , 'step': 'step' + , 'style': 'style' + , 'tabindex': 'tabIndex' + , 'target': 'target' + , 'title': 'title' + , 'translate': 'translate' + , 'type': 'type' + , 'typemustmatch': 'typeMustMatch' + , 'usemap': 'useMap' + , 'value': 'value' + , 'width': 'width' + , 'wmode': 'wmode' + , 'wrap': 'wrap' +}; + +module.exports = properties; + +},{}],67:[function(require,module,exports){ +var escape = require('escape-html'); +var propConfig = require('./property-config'); +var types = propConfig.attributeTypes; +var properties = propConfig.properties; +var attributeNames = propConfig.attributeNames; + +var prefixAttribute = memoizeString(function (name) { + return escape(name) + '="'; +}); + +module.exports = createAttribute; + +/** + * Create attribute string. + * + * @param {String} name The name of the property or attribute + * @param {*} value The value + * @param {Boolean} [isAttribute] Denotes whether `name` is an attribute. + * @return {?String} Attribute string || null if not a valid property or custom attribute. + */ + +function createAttribute(name, value, isAttribute) { + if (properties.hasOwnProperty(name)) { + if (shouldSkip(name, value)) return ''; + name = (attributeNames[name] || name).toLowerCase(); + var attrType = properties[name]; + // for BOOLEAN `value` only has to be truthy + // for OVERLOADED_BOOLEAN `value` has to be === true + if ((attrType === types.BOOLEAN) || + (attrType === types.OVERLOADED_BOOLEAN && value === true)) { + return escape(name); + } + return prefixAttribute(name) + escape(value) + '"'; + } else if (isAttribute) { + if (value == null) return ''; + return prefixAttribute(name) + escape(value) + '"'; + } + // return null if `name` is neither a valid property nor an attribute + return null; +} + +/** + * Should skip false boolean attributes. + */ + +function shouldSkip(name, value) { + var attrType = properties[name]; + return value == null || + (attrType === types.BOOLEAN && !value) || + (attrType === types.OVERLOADED_BOOLEAN && value === false); +} + +/** + * Memoizes the return value of a function that accepts one string argument. + * + * @param {function} callback + * @return {function} + */ + +function memoizeString(callback) { + var cache = {}; + return function(string) { + if (cache.hasOwnProperty(string)) { + return cache[string]; + } else { + return cache[string] = callback.call(this, string); + } + }; +} +},{"./property-config":77,"escape-html":69}],68:[function(require,module,exports){ +var escape = require('escape-html'); +var extend = require('xtend'); +var isVNode = require('virtual-dom/vnode/is-vnode'); +var isVText = require('virtual-dom/vnode/is-vtext'); +var isThunk = require('virtual-dom/vnode/is-thunk'); +var isWidget = require('virtual-dom/vnode/is-widget'); +var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook'); +var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook'); +var paramCase = require('param-case'); +var createAttribute = require('./create-attribute'); +var voidElements = require('./void-elements'); + +module.exports = toHTML; + +function toHTML(node, parent) { + if (!node) return ''; + + if (isThunk(node)) { + node = node.render(); + } + + if (isWidget(node) && node.render) { + node = node.render(); + } + + if (isVNode(node)) { + return openTag(node) + tagContent(node) + closeTag(node); + } else if (isVText(node)) { + if (parent && parent.tagName.toLowerCase() === 'script') return String(node.text); + return escape(String(node.text)); + } + + return ''; +} + +function openTag(node) { + var props = node.properties; + var ret = '<' + node.tagName.toLowerCase(); + + for (var name in props) { + var value = props[name]; + if (value == null) continue; + + if (name == 'attributes') { + value = extend({}, value); + for (var attrProp in value) { + ret += ' ' + createAttribute(attrProp, value[attrProp], true); + } + continue; + } + + if (name == 'style') { + var css = ''; + value = extend({}, value); + for (var styleProp in value) { + css += paramCase(styleProp) + ': ' + value[styleProp] + '; '; + } + value = css.trim(); + } + + if (value instanceof softHook || value instanceof attrHook) { + ret += ' ' + createAttribute(name, value.value, true); + continue; + } + + var attr = createAttribute(name, value); + if (attr) ret += ' ' + attr; + } + + return ret + '>'; +} + +function tagContent(node) { + var innerHTML = node.properties.innerHTML; + if (innerHTML != null) return innerHTML; + else { + var ret = ''; + if (node.children && node.children.length) { + for (var i = 0, l = node.children.length; i'; +} +},{"./create-attribute":67,"./void-elements":78,"escape-html":69,"param-case":75,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":97,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":99,"virtual-dom/vnode/is-thunk":105,"virtual-dom/vnode/is-vnode":107,"virtual-dom/vnode/is-vtext":108,"virtual-dom/vnode/is-widget":109,"xtend":76}],69:[function(require,module,exports){ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} + +},{}],70:[function(require,module,exports){ +/** + * Special language-specific overrides. + * + * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt + * + * @type {Object} + */ +var LANGUAGES = { + tr: { + regexp: /\u0130|\u0049|\u0049\u0307/g, + map: { + '\u0130': '\u0069', + '\u0049': '\u0131', + '\u0049\u0307': '\u0069' + } + }, + az: { + regexp: /[\u0130]/g, + map: { + '\u0130': '\u0069', + '\u0049': '\u0131', + '\u0049\u0307': '\u0069' + } + }, + lt: { + regexp: /[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g, + map: { + '\u0049': '\u0069\u0307', + '\u004A': '\u006A\u0307', + '\u012E': '\u012F\u0307', + '\u00CC': '\u0069\u0307\u0300', + '\u00CD': '\u0069\u0307\u0301', + '\u0128': '\u0069\u0307\u0303' + } + } +} + +/** + * Lowercase a string. + * + * @param {String} str + * @return {String} + */ +module.exports = function (str, locale) { + var lang = LANGUAGES[locale] + + str = str == null ? '' : String(str) + + if (lang) { + str = str.replace(lang.regexp, function (m) { return lang.map[m] }) + } + + return str.toLowerCase() +} + +},{}],71:[function(require,module,exports){ +var lowerCase = require('lower-case') + +var NON_WORD_REGEXP = require('./vendor/non-word-regexp') +var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp') +var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp') + +/** + * Sentence case a string. + * + * @param {String} str + * @param {String} locale + * @param {String} replacement + * @return {String} + */ +module.exports = function (str, locale, replacement) { + if (str == null) { + return '' + } + + replacement = replacement || ' ' + + function replace (match, index, string) { + if (index === 0 || index === (string.length - match.length)) { + return '' + } + + return replacement + } + + str = String(str) + // Support camel case ("camelCase" -> "camel Case"). + .replace(CAMEL_CASE_REGEXP, '$1 $2') + // Support digit groups ("test2012" -> "test 2012"). + .replace(TRAILING_DIGIT_REGEXP, '$1 $2') + // Remove all non-word characters and replace with a single space. + .replace(NON_WORD_REGEXP, replace) + + // Lower case the entire string. + return lowerCase(str, locale) +} + +},{"./vendor/camel-case-regexp":72,"./vendor/non-word-regexp":73,"./vendor/trailing-digit-regexp":74,"lower-case":70}],72:[function(require,module,exports){ +module.exports = /([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g + +},{}],73:[function(require,module,exports){ +module.exports = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g + +},{}],74:[function(require,module,exports){ +module.exports = /([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g + +},{}],75:[function(require,module,exports){ +var sentenceCase = require('sentence-case') + +/** + * Param case a string. + * + * @param {String} string + * @param {String} [locale] + * @return {String} + */ +module.exports = function (string, locale) { + return sentenceCase(string, locale, '-') +} + +},{"sentence-case":71}],76:[function(require,module,exports){ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + +},{}],77:[function(require,module,exports){ +/** + * Attribute types. + */ + +var types = { + BOOLEAN: 1, + OVERLOADED_BOOLEAN: 2 +}; + +/** + * Properties. + * + * Taken from https://github.com/facebook/react/blob/847357e42e5267b04dd6e297219eaa125ab2f9f4/src/browser/ui/dom/HTMLDOMPropertyConfig.js + * + */ + +var properties = { + /** + * Standard Properties + */ + accept: true, + acceptCharset: true, + accessKey: true, + action: true, + allowFullScreen: types.BOOLEAN, + allowTransparency: true, + alt: true, + async: types.BOOLEAN, + autocomplete: true, + autofocus: types.BOOLEAN, + autoplay: types.BOOLEAN, + cellPadding: true, + cellSpacing: true, + charset: true, + checked: types.BOOLEAN, + classID: true, + className: true, + cols: true, + colSpan: true, + content: true, + contentEditable: true, + contextMenu: true, + controls: types.BOOLEAN, + coords: true, + crossOrigin: true, + data: true, // For `` acts as `src`. + dateTime: true, + defer: types.BOOLEAN, + dir: true, + disabled: types.BOOLEAN, + download: types.OVERLOADED_BOOLEAN, + draggable: true, + enctype: true, + form: true, + formAction: true, + formEncType: true, + formMethod: true, + formNoValidate: types.BOOLEAN, + formTarget: true, + frameBorder: true, + headers: true, + height: true, + hidden: types.BOOLEAN, + href: true, + hreflang: true, + htmlFor: true, + httpEquiv: true, + icon: true, + id: true, + label: true, + lang: true, + list: true, + loop: types.BOOLEAN, + manifest: true, + marginHeight: true, + marginWidth: true, + max: true, + maxLength: true, + media: true, + mediaGroup: true, + method: true, + min: true, + multiple: types.BOOLEAN, + muted: types.BOOLEAN, + name: true, + noValidate: types.BOOLEAN, + open: true, + pattern: true, + placeholder: true, + poster: true, + preload: true, + radiogroup: true, + readOnly: types.BOOLEAN, + rel: true, + required: types.BOOLEAN, + role: true, + rows: true, + rowSpan: true, + sandbox: true, + scope: true, + scrolling: true, + seamless: types.BOOLEAN, + selected: types.BOOLEAN, + shape: true, + size: true, + sizes: true, + span: true, + spellcheck: true, + src: true, + srcdoc: true, + srcset: true, + start: true, + step: true, + style: true, + tabIndex: true, + target: true, + title: true, + type: true, + useMap: true, + value: true, + width: true, + wmode: true, + + /** + * Non-standard Properties + */ + // autoCapitalize and autoCorrect are supported in Mobile Safari for + // keyboard hints. + autocapitalize: true, + autocorrect: true, + // itemProp, itemScope, itemType are for Microdata support. See + // http://schema.org/docs/gs.html + itemProp: true, + itemScope: types.BOOLEAN, + itemType: true, + // property is supported for OpenGraph in meta tags. + property: true +}; + +/** + * Properties to attributes mapping. + * + * The ones not here are simply converted to lower case. + */ + +var attributeNames = { + acceptCharset: 'accept-charset', + className: 'class', + htmlFor: 'for', + httpEquiv: 'http-equiv' +}; + +/** + * Exports. + */ + +module.exports = { + attributeTypes: types, + properties: properties, + attributeNames: attributeNames +}; +},{}],78:[function(require,module,exports){ + +/** + * Void elements. + * + * https://github.com/facebook/react/blob/v0.12.0/src/browser/ui/ReactDOMComponent.js#L99 + */ + +module.exports = { + 'area': true, + 'base': true, + 'br': true, + 'col': true, + 'embed': true, + 'hr': true, + 'img': true, + 'input': true, + 'keygen': true, + 'link': true, + 'meta': true, + 'param': true, + 'source': true, + 'track': true, + 'wbr': true +}; +},{}],79:[function(require,module,exports){ +var createElement = require("./vdom/create-element.js") + +module.exports = createElement + +},{"./vdom/create-element.js":92}],80:[function(require,module,exports){ +var diff = require("./vtree/diff.js") + +module.exports = diff + +},{"./vtree/diff.js":115}],81:[function(require,module,exports){ +var h = require("./virtual-hyperscript/index.js") + +module.exports = h + +},{"./virtual-hyperscript/index.js":100}],82:[function(require,module,exports){ +var diff = require("./diff.js") +var patch = require("./patch.js") +var h = require("./h.js") +var create = require("./create-element.js") +var VNode = require('./vnode/vnode.js') +var VText = require('./vnode/vtext.js') + +module.exports = { + diff: diff, + patch: patch, + h: h, + create: create, + VNode: VNode, + VText: VText +} + +},{"./create-element.js":79,"./diff.js":80,"./h.js":81,"./patch.js":90,"./vnode/vnode.js":111,"./vnode/vtext.js":113}],83:[function(require,module,exports){ +/*! + * Cross-Browser Split 1.1.1 + * Copyright 2007-2012 Steven Levithan + * Available under the MIT License + * ECMAScript compliant, uniform cross-browser split method + */ + +/** + * Splits a string into an array of strings using a regex or string separator. Matches of the + * separator are not included in the result array. However, if `separator` is a regex that contains + * capturing groups, backreferences are spliced into the result each time `separator` is matched. + * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably + * cross-browser. + * @param {String} str String to split. + * @param {RegExp|String} separator Regex or string to use for separating the string. + * @param {Number} [limit] Maximum number of items to include in the result array. + * @returns {Array} Array of substrings. + * @example + * + * // Basic use + * split('a b c d', ' '); + * // -> ['a', 'b', 'c', 'd'] + * + * // With limit + * split('a b c d', ' ', 2); + * // -> ['a', 'b'] + * + * // Backreferences in result array + * split('..word1 word2..', /([a-z]+)(\d+)/i); + * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] + */ +module.exports = (function split(undef) { + + var nativeSplit = String.prototype.split, + compliantExecNpcg = /()??/.exec("")[1] === undef, + // NPCG: nonparticipating capturing group + self; + + self = function(str, separator, limit) { + // If `separator` is not a regex, use `nativeSplit` + if (Object.prototype.toString.call(separator) !== "[object RegExp]") { + return nativeSplit.call(str, separator, limit); + } + var output = [], + flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 + (separator.sticky ? "y" : ""), + // Firefox 3+ + lastLastIndex = 0, + // Make `global` and avoid `lastIndex` issues by working with a copy + separator = new RegExp(separator.source, flags + "g"), + separator2, match, lastIndex, lastLength; + str += ""; // Type-convert + if (!compliantExecNpcg) { + // Doesn't need flags gy, but they don't hurt + separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); + } + /* Values for `limit`, per the spec: + * If undefined: 4294967295 // Math.pow(2, 32) - 1 + * If 0, Infinity, or NaN: 0 + * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; + * If negative number: 4294967296 - Math.floor(Math.abs(limit)) + * If other: Type-convert, then use the above rules + */ + limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 + limit >>> 0; // ToUint32(limit) + while (match = separator.exec(str)) { + // `separator.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0].length; + if (lastIndex > lastLastIndex) { + output.push(str.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for + // nonparticipating capturing groups + if (!compliantExecNpcg && match.length > 1) { + match[0].replace(separator2, function() { + for (var i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undef) { + match[i] = undef; + } + } + }); + } + if (match.length > 1 && match.index < str.length) { + Array.prototype.push.apply(output, match.slice(1)); + } + lastLength = match[0].length; + lastLastIndex = lastIndex; + if (output.length >= limit) { + break; + } + } + if (separator.lastIndex === match.index) { + separator.lastIndex++; // Avoid an infinite loop + } + } + if (lastLastIndex === str.length) { + if (lastLength || !separator.test("")) { + output.push(""); + } + } else { + output.push(str.slice(lastLastIndex)); + } + return output.length > limit ? output.slice(0, limit) : output; + }; + + return self; +})(); + +},{}],84:[function(require,module,exports){ +'use strict'; + +var OneVersionConstraint = require('individual/one-version'); + +var MY_VERSION = '7'; +OneVersionConstraint('ev-store', MY_VERSION); + +var hashKey = '__EV_STORE_KEY@' + MY_VERSION; + +module.exports = EvStore; + +function EvStore(elem) { + var hash = elem[hashKey]; + + if (!hash) { + hash = elem[hashKey] = {}; + } + + return hash; +} + +},{"individual/one-version":86}],85:[function(require,module,exports){ +(function (global){ +'use strict'; + +/*global window, global*/ + +var root = typeof window !== 'undefined' ? + window : typeof global !== 'undefined' ? + global : {}; + +module.exports = Individual; + +function Individual(key, value) { + if (key in root) { + return root[key]; + } + + root[key] = value; + + return value; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],86:[function(require,module,exports){ +'use strict'; + +var Individual = require('./index.js'); + +module.exports = OneVersion; + +function OneVersion(moduleName, version, defaultValue) { + var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName; + var enforceKey = key + '_ENFORCE_SINGLETON'; + + var versionValue = Individual(enforceKey, version); + + if (versionValue !== version) { + throw new Error('Can only have one copy of ' + + moduleName + '.\n' + + 'You already have version ' + versionValue + + ' installed.\n' + + 'This means you cannot install version ' + version); + } + + return Individual(key, defaultValue); +} + +},{"./index.js":85}],87:[function(require,module,exports){ +(function (global){ +var topLevel = typeof global !== 'undefined' ? global : + typeof window !== 'undefined' ? window : {} +var minDoc = require('min-document'); + +if (typeof document !== 'undefined') { + module.exports = document; +} else { + var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; + + if (!doccy) { + doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; + } + + module.exports = doccy; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"min-document":116}],88:[function(require,module,exports){ +"use strict"; + +module.exports = function isObject(x) { + return typeof x === "object" && x !== null; +}; + +},{}],89:[function(require,module,exports){ +var nativeIsArray = Array.isArray +var toString = Object.prototype.toString + +module.exports = nativeIsArray || isArray + +function isArray(obj) { + return toString.call(obj) === "[object Array]" +} + +},{}],90:[function(require,module,exports){ +var patch = require("./vdom/patch.js") + +module.exports = patch + +},{"./vdom/patch.js":95}],91:[function(require,module,exports){ +var isObject = require("is-object") +var isHook = require("../vnode/is-vhook.js") + +module.exports = applyProperties + +function applyProperties(node, props, previous) { + for (var propName in props) { + var propValue = props[propName] + + if (propValue === undefined) { + removeProperty(node, propName, propValue, previous); + } else if (isHook(propValue)) { + removeProperty(node, propName, propValue, previous) + if (propValue.hook) { + propValue.hook(node, + propName, + previous ? previous[propName] : undefined) + } + } else { + if (isObject(propValue)) { + patchObject(node, props, previous, propName, propValue); + } else { + node[propName] = propValue + } + } + } +} + +function removeProperty(node, propName, propValue, previous) { + if (previous) { + var previousValue = previous[propName] + + if (!isHook(previousValue)) { + if (propName === "attributes") { + for (var attrName in previousValue) { + node.removeAttribute(attrName) + } + } else if (propName === "style") { + for (var i in previousValue) { + node.style[i] = "" + } + } else if (typeof previousValue === "string") { + node[propName] = "" + } else { + node[propName] = null + } + } else if (previousValue.unhook) { + previousValue.unhook(node, propName, propValue) + } + } +} + +function patchObject(node, props, previous, propName, propValue) { + var previousValue = previous ? previous[propName] : undefined + + // Set attributes + if (propName === "attributes") { + for (var attrName in propValue) { + var attrValue = propValue[attrName] + + if (attrValue === undefined) { + node.removeAttribute(attrName) + } else { + node.setAttribute(attrName, attrValue) + } + } + + return + } + + if(previousValue && isObject(previousValue) && + getPrototype(previousValue) !== getPrototype(propValue)) { + node[propName] = propValue + return + } + + if (!isObject(node[propName])) { + node[propName] = {} + } + + var replacer = propName === "style" ? "" : undefined + + for (var k in propValue) { + var value = propValue[k] + node[propName][k] = (value === undefined) ? replacer : value + } +} + +function getPrototype(value) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(value) + } else if (value.__proto__) { + return value.__proto__ + } else if (value.constructor) { + return value.constructor.prototype + } +} + +},{"../vnode/is-vhook.js":106,"is-object":88}],92:[function(require,module,exports){ +var document = require("global/document") + +var applyProperties = require("./apply-properties") + +var isVNode = require("../vnode/is-vnode.js") +var isVText = require("../vnode/is-vtext.js") +var isWidget = require("../vnode/is-widget.js") +var handleThunk = require("../vnode/handle-thunk.js") + +module.exports = createElement + +function createElement(vnode, opts) { + var doc = opts ? opts.document || document : document + var warn = opts ? opts.warn : null + + vnode = handleThunk(vnode).a + + if (isWidget(vnode)) { + return vnode.init() + } else if (isVText(vnode)) { + return doc.createTextNode(vnode.text) + } else if (!isVNode(vnode)) { + if (warn) { + warn("Item is not a valid virtual dom node", vnode) + } + return null + } + + var node = (vnode.namespace === null) ? + doc.createElement(vnode.tagName) : + doc.createElementNS(vnode.namespace, vnode.tagName) + + var props = vnode.properties + applyProperties(node, props) + + var children = vnode.children + + for (var i = 0; i < children.length; i++) { + var childNode = createElement(children[i], opts) + if (childNode) { + node.appendChild(childNode) + } + } + + return node +} + +},{"../vnode/handle-thunk.js":104,"../vnode/is-vnode.js":107,"../vnode/is-vtext.js":108,"../vnode/is-widget.js":109,"./apply-properties":91,"global/document":87}],93:[function(require,module,exports){ +// Maps a virtual DOM tree onto a real DOM tree in an efficient manner. +// We don't want to read all of the DOM nodes in the tree so we use +// the in-order tree indexing to eliminate recursion down certain branches. +// We only recurse into a DOM node if we know that it contains a child of +// interest. + +var noChild = {} + +module.exports = domIndex + +function domIndex(rootNode, tree, indices, nodes) { + if (!indices || indices.length === 0) { + return {} + } else { + indices.sort(ascending) + return recurse(rootNode, tree, indices, nodes, 0) + } +} + +function recurse(rootNode, tree, indices, nodes, rootIndex) { + nodes = nodes || {} + + + if (rootNode) { + if (indexInRange(indices, rootIndex, rootIndex)) { + nodes[rootIndex] = rootNode + } + + var vChildren = tree.children + + if (vChildren) { + + var childNodes = rootNode.childNodes + + for (var i = 0; i < tree.children.length; i++) { + rootIndex += 1 + + var vChild = vChildren[i] || noChild + var nextIndex = rootIndex + (vChild.count || 0) + + // skip recursion down the tree if there are no nodes down here + if (indexInRange(indices, rootIndex, nextIndex)) { + recurse(childNodes[i], vChild, indices, nodes, rootIndex) + } + + rootIndex = nextIndex + } + } + } + + return nodes +} + +// Binary search for an index in the interval [left, right] +function indexInRange(indices, left, right) { + if (indices.length === 0) { + return false + } + + var minIndex = 0 + var maxIndex = indices.length - 1 + var currentIndex + var currentItem + + while (minIndex <= maxIndex) { + currentIndex = ((maxIndex + minIndex) / 2) >> 0 + currentItem = indices[currentIndex] + + if (minIndex === maxIndex) { + return currentItem >= left && currentItem <= right + } else if (currentItem < left) { + minIndex = currentIndex + 1 + } else if (currentItem > right) { + maxIndex = currentIndex - 1 + } else { + return true + } + } + + return false; +} + +function ascending(a, b) { + return a > b ? 1 : -1 +} + +},{}],94:[function(require,module,exports){ +var applyProperties = require("./apply-properties") + +var isWidget = require("../vnode/is-widget.js") +var VPatch = require("../vnode/vpatch.js") + +var updateWidget = require("./update-widget") + +module.exports = applyPatch + +function applyPatch(vpatch, domNode, renderOptions) { + var type = vpatch.type + var vNode = vpatch.vNode + var patch = vpatch.patch + + switch (type) { + case VPatch.REMOVE: + return removeNode(domNode, vNode) + case VPatch.INSERT: + return insertNode(domNode, patch, renderOptions) + case VPatch.VTEXT: + return stringPatch(domNode, vNode, patch, renderOptions) + case VPatch.WIDGET: + return widgetPatch(domNode, vNode, patch, renderOptions) + case VPatch.VNODE: + return vNodePatch(domNode, vNode, patch, renderOptions) + case VPatch.ORDER: + reorderChildren(domNode, patch) + return domNode + case VPatch.PROPS: + applyProperties(domNode, patch, vNode.properties) + return domNode + case VPatch.THUNK: + return replaceRoot(domNode, + renderOptions.patch(domNode, patch, renderOptions)) + default: + return domNode + } +} + +function removeNode(domNode, vNode) { + var parentNode = domNode.parentNode + + if (parentNode) { + parentNode.removeChild(domNode) + } + + destroyWidget(domNode, vNode); + + return null +} + +function insertNode(parentNode, vNode, renderOptions) { + var newNode = renderOptions.render(vNode, renderOptions) + + if (parentNode) { + parentNode.appendChild(newNode) + } + + return parentNode +} + +function stringPatch(domNode, leftVNode, vText, renderOptions) { + var newNode + + if (domNode.nodeType === 3) { + domNode.replaceData(0, domNode.length, vText.text) + newNode = domNode + } else { + var parentNode = domNode.parentNode + newNode = renderOptions.render(vText, renderOptions) + + if (parentNode && newNode !== domNode) { + parentNode.replaceChild(newNode, domNode) + } + } + + return newNode +} + +function widgetPatch(domNode, leftVNode, widget, renderOptions) { + var updating = updateWidget(leftVNode, widget) + var newNode + + if (updating) { + newNode = widget.update(leftVNode, domNode) || domNode + } else { + newNode = renderOptions.render(widget, renderOptions) + } + + var parentNode = domNode.parentNode + + if (parentNode && newNode !== domNode) { + parentNode.replaceChild(newNode, domNode) + } + + if (!updating) { + destroyWidget(domNode, leftVNode) + } + + return newNode +} + +function vNodePatch(domNode, leftVNode, vNode, renderOptions) { + var parentNode = domNode.parentNode + var newNode = renderOptions.render(vNode, renderOptions) + + if (parentNode && newNode !== domNode) { + parentNode.replaceChild(newNode, domNode) + } + + return newNode +} + +function destroyWidget(domNode, w) { + if (typeof w.destroy === "function" && isWidget(w)) { + w.destroy(domNode) + } +} + +function reorderChildren(domNode, moves) { + var childNodes = domNode.childNodes + var keyMap = {} + var node + var remove + var insert + + for (var i = 0; i < moves.removes.length; i++) { + remove = moves.removes[i] + node = childNodes[remove.from] + if (remove.key) { + keyMap[remove.key] = node + } + domNode.removeChild(node) + } + + var length = childNodes.length + for (var j = 0; j < moves.inserts.length; j++) { + insert = moves.inserts[j] + node = keyMap[insert.key] + // this is the weirdest bug i've ever seen in webkit + domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to]) + } +} + +function replaceRoot(oldRoot, newRoot) { + if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) { + oldRoot.parentNode.replaceChild(newRoot, oldRoot) + } + + return newRoot; +} + +},{"../vnode/is-widget.js":109,"../vnode/vpatch.js":112,"./apply-properties":91,"./update-widget":96}],95:[function(require,module,exports){ +var document = require("global/document") +var isArray = require("x-is-array") + +var render = require("./create-element") +var domIndex = require("./dom-index") +var patchOp = require("./patch-op") +module.exports = patch + +function patch(rootNode, patches, renderOptions) { + renderOptions = renderOptions || {} + renderOptions.patch = renderOptions.patch || patchRecursive + renderOptions.render = renderOptions.render || render + + return renderOptions.patch(rootNode, patches, renderOptions) +} + +function patchRecursive(rootNode, patches, renderOptions) { + var indices = patchIndices(patches) + + if (indices.length === 0) { + return rootNode + } + + var index = domIndex(rootNode, patches.a, indices) + var ownerDocument = rootNode.ownerDocument + + if (!renderOptions.document && ownerDocument !== document) { + renderOptions.document = ownerDocument + } + + for (var i = 0; i < indices.length; i++) { + var nodeIndex = indices[i] + rootNode = applyPatch(rootNode, + index[nodeIndex], + patches[nodeIndex], + renderOptions) + } + + return rootNode +} + +function applyPatch(rootNode, domNode, patchList, renderOptions) { + if (!domNode) { + return rootNode + } + + var newNode + + if (isArray(patchList)) { + for (var i = 0; i < patchList.length; i++) { + newNode = patchOp(patchList[i], domNode, renderOptions) + + if (domNode === rootNode) { + rootNode = newNode + } + } + } else { + newNode = patchOp(patchList, domNode, renderOptions) + + if (domNode === rootNode) { + rootNode = newNode + } + } + + return rootNode +} + +function patchIndices(patches) { + var indices = [] + + for (var key in patches) { + if (key !== "a") { + indices.push(Number(key)) + } + } + + return indices +} + +},{"./create-element":92,"./dom-index":93,"./patch-op":94,"global/document":87,"x-is-array":89}],96:[function(require,module,exports){ +var isWidget = require("../vnode/is-widget.js") + +module.exports = updateWidget + +function updateWidget(a, b) { + if (isWidget(a) && isWidget(b)) { + if ("name" in a && "name" in b) { + return a.id === b.id + } else { + return a.init === b.init + } + } + + return false +} + +},{"../vnode/is-widget.js":109}],97:[function(require,module,exports){ +'use strict'; + +module.exports = AttributeHook; + +function AttributeHook(namespace, value) { + if (!(this instanceof AttributeHook)) { + return new AttributeHook(namespace, value); + } + + this.namespace = namespace; + this.value = value; +} + +AttributeHook.prototype.hook = function (node, prop, prev) { + if (prev && prev.type === 'AttributeHook' && + prev.value === this.value && + prev.namespace === this.namespace) { + return; + } + + node.setAttributeNS(this.namespace, prop, this.value); +}; + +AttributeHook.prototype.unhook = function (node, prop, next) { + if (next && next.type === 'AttributeHook' && + next.namespace === this.namespace) { + return; + } + + var colonPosition = prop.indexOf(':'); + var localName = colonPosition > -1 ? prop.substr(colonPosition + 1) : prop; + node.removeAttributeNS(this.namespace, localName); +}; + +AttributeHook.prototype.type = 'AttributeHook'; + +},{}],98:[function(require,module,exports){ +'use strict'; + +var EvStore = require('ev-store'); + +module.exports = EvHook; + +function EvHook(value) { + if (!(this instanceof EvHook)) { + return new EvHook(value); + } + + this.value = value; +} + +EvHook.prototype.hook = function (node, propertyName) { + var es = EvStore(node); + var propName = propertyName.substr(3); + + es[propName] = this.value; +}; + +EvHook.prototype.unhook = function(node, propertyName) { + var es = EvStore(node); + var propName = propertyName.substr(3); + + es[propName] = undefined; +}; + +},{"ev-store":84}],99:[function(require,module,exports){ +'use strict'; + +module.exports = SoftSetHook; + +function SoftSetHook(value) { + if (!(this instanceof SoftSetHook)) { + return new SoftSetHook(value); + } + + this.value = value; +} + +SoftSetHook.prototype.hook = function (node, propertyName) { + if (node[propertyName] !== this.value) { + node[propertyName] = this.value; + } +}; + +},{}],100:[function(require,module,exports){ +'use strict'; + +var isArray = require('x-is-array'); + +var VNode = require('../vnode/vnode.js'); +var VText = require('../vnode/vtext.js'); +var isVNode = require('../vnode/is-vnode'); +var isVText = require('../vnode/is-vtext'); +var isWidget = require('../vnode/is-widget'); +var isHook = require('../vnode/is-vhook'); +var isVThunk = require('../vnode/is-thunk'); + +var parseTag = require('./parse-tag.js'); +var softSetHook = require('./hooks/soft-set-hook.js'); +var evHook = require('./hooks/ev-hook.js'); + +module.exports = h; + +function h(tagName, properties, children) { + var childNodes = []; + var tag, props, key, namespace; + + if (!children && isChildren(properties)) { + children = properties; + props = {}; + } + + props = props || properties || {}; + tag = parseTag(tagName, props); + + // support keys + if (props.hasOwnProperty('key')) { + key = props.key; + props.key = undefined; + } + + // support namespace + if (props.hasOwnProperty('namespace')) { + namespace = props.namespace; + props.namespace = undefined; + } + + // fix cursor bug + if (tag === 'INPUT' && + !namespace && + props.hasOwnProperty('value') && + props.value !== undefined && + !isHook(props.value) + ) { + props.value = softSetHook(props.value); + } + + transformProperties(props); + + if (children !== undefined && children !== null) { + addChild(children, childNodes, tag, props); + } + + + return new VNode(tag, props, childNodes, key, namespace); +} + +function addChild(c, childNodes, tag, props) { + if (typeof c === 'string') { + childNodes.push(new VText(c)); + } else if (typeof c === 'number') { + childNodes.push(new VText(String(c))); + } else if (isChild(c)) { + childNodes.push(c); + } else if (isArray(c)) { + for (var i = 0; i < c.length; i++) { + addChild(c[i], childNodes, tag, props); + } + } else if (c === null || c === undefined) { + return; + } else { + throw UnexpectedVirtualElement({ + foreignObject: c, + parentVnode: { + tagName: tag, + properties: props + } + }); + } +} + +function transformProperties(props) { + for (var propName in props) { + if (props.hasOwnProperty(propName)) { + var value = props[propName]; + + if (isHook(value)) { + continue; + } + + if (propName.substr(0, 3) === 'ev-') { + // add ev-foo support + props[propName] = evHook(value); + } + } + } +} + +function isChild(x) { + return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x); +} + +function isChildren(x) { + return typeof x === 'string' || isArray(x) || isChild(x); +} + +function UnexpectedVirtualElement(data) { + var err = new Error(); + + err.type = 'virtual-hyperscript.unexpected.virtual-element'; + err.message = 'Unexpected virtual child passed to h().\n' + + 'Expected a VNode / Vthunk / VWidget / string but:\n' + + 'got:\n' + + errorString(data.foreignObject) + + '.\n' + + 'The parent vnode is:\n' + + errorString(data.parentVnode) + '\n' + + 'Suggested fix: change your `h(..., [ ... ])` callsite.'; + err.foreignObject = data.foreignObject; + err.parentVnode = data.parentVnode; + + return err; +} + +function errorString(obj) { + try { + return JSON.stringify(obj, null, ' '); + } catch (e) { + return String(obj); + } +} + +},{"../vnode/is-thunk":105,"../vnode/is-vhook":106,"../vnode/is-vnode":107,"../vnode/is-vtext":108,"../vnode/is-widget":109,"../vnode/vnode.js":111,"../vnode/vtext.js":113,"./hooks/ev-hook.js":98,"./hooks/soft-set-hook.js":99,"./parse-tag.js":101,"x-is-array":89}],101:[function(require,module,exports){ +'use strict'; + +var split = require('browser-split'); + +var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; +var notClassId = /^\.|#/; + +module.exports = parseTag; + +function parseTag(tag, props) { + if (!tag) { + return 'DIV'; + } + + var noId = !(props.hasOwnProperty('id')); + + var tagParts = split(tag, classIdSplit); + var tagName = null; + + if (notClassId.test(tagParts[1])) { + tagName = 'DIV'; + } + + var classes, part, type, i; + + for (i = 0; i < tagParts.length; i++) { + part = tagParts[i]; + + if (!part) { + continue; + } + + type = part.charAt(0); + + if (!tagName) { + tagName = part; + } else if (type === '.') { + classes = classes || []; + classes.push(part.substring(1, part.length)); + } else if (type === '#' && noId) { + props.id = part.substring(1, part.length); + } + } + + if (classes) { + if (props.className) { + classes.push(props.className); + } + + props.className = classes.join(' '); + } + + return props.namespace ? tagName : tagName.toUpperCase(); +} + +},{"browser-split":83}],102:[function(require,module,exports){ +'use strict'; + +var DEFAULT_NAMESPACE = null; +var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; +var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; +var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; + +// http://www.w3.org/TR/SVGTiny12/attributeTable.html +// http://www.w3.org/TR/SVG/attindex.html +var SVG_PROPERTIES = { + 'about': DEFAULT_NAMESPACE, + 'accent-height': DEFAULT_NAMESPACE, + 'accumulate': DEFAULT_NAMESPACE, + 'additive': DEFAULT_NAMESPACE, + 'alignment-baseline': DEFAULT_NAMESPACE, + 'alphabetic': DEFAULT_NAMESPACE, + 'amplitude': DEFAULT_NAMESPACE, + 'arabic-form': DEFAULT_NAMESPACE, + 'ascent': DEFAULT_NAMESPACE, + 'attributeName': DEFAULT_NAMESPACE, + 'attributeType': DEFAULT_NAMESPACE, + 'azimuth': DEFAULT_NAMESPACE, + 'bandwidth': DEFAULT_NAMESPACE, + 'baseFrequency': DEFAULT_NAMESPACE, + 'baseProfile': DEFAULT_NAMESPACE, + 'baseline-shift': DEFAULT_NAMESPACE, + 'bbox': DEFAULT_NAMESPACE, + 'begin': DEFAULT_NAMESPACE, + 'bias': DEFAULT_NAMESPACE, + 'by': DEFAULT_NAMESPACE, + 'calcMode': DEFAULT_NAMESPACE, + 'cap-height': DEFAULT_NAMESPACE, + 'class': DEFAULT_NAMESPACE, + 'clip': DEFAULT_NAMESPACE, + 'clip-path': DEFAULT_NAMESPACE, + 'clip-rule': DEFAULT_NAMESPACE, + 'clipPathUnits': DEFAULT_NAMESPACE, + 'color': DEFAULT_NAMESPACE, + 'color-interpolation': DEFAULT_NAMESPACE, + 'color-interpolation-filters': DEFAULT_NAMESPACE, + 'color-profile': DEFAULT_NAMESPACE, + 'color-rendering': DEFAULT_NAMESPACE, + 'content': DEFAULT_NAMESPACE, + 'contentScriptType': DEFAULT_NAMESPACE, + 'contentStyleType': DEFAULT_NAMESPACE, + 'cursor': DEFAULT_NAMESPACE, + 'cx': DEFAULT_NAMESPACE, + 'cy': DEFAULT_NAMESPACE, + 'd': DEFAULT_NAMESPACE, + 'datatype': DEFAULT_NAMESPACE, + 'defaultAction': DEFAULT_NAMESPACE, + 'descent': DEFAULT_NAMESPACE, + 'diffuseConstant': DEFAULT_NAMESPACE, + 'direction': DEFAULT_NAMESPACE, + 'display': DEFAULT_NAMESPACE, + 'divisor': DEFAULT_NAMESPACE, + 'dominant-baseline': DEFAULT_NAMESPACE, + 'dur': DEFAULT_NAMESPACE, + 'dx': DEFAULT_NAMESPACE, + 'dy': DEFAULT_NAMESPACE, + 'edgeMode': DEFAULT_NAMESPACE, + 'editable': DEFAULT_NAMESPACE, + 'elevation': DEFAULT_NAMESPACE, + 'enable-background': DEFAULT_NAMESPACE, + 'end': DEFAULT_NAMESPACE, + 'ev:event': EV_NAMESPACE, + 'event': DEFAULT_NAMESPACE, + 'exponent': DEFAULT_NAMESPACE, + 'externalResourcesRequired': DEFAULT_NAMESPACE, + 'fill': DEFAULT_NAMESPACE, + 'fill-opacity': DEFAULT_NAMESPACE, + 'fill-rule': DEFAULT_NAMESPACE, + 'filter': DEFAULT_NAMESPACE, + 'filterRes': DEFAULT_NAMESPACE, + 'filterUnits': DEFAULT_NAMESPACE, + 'flood-color': DEFAULT_NAMESPACE, + 'flood-opacity': DEFAULT_NAMESPACE, + 'focusHighlight': DEFAULT_NAMESPACE, + 'focusable': DEFAULT_NAMESPACE, + 'font-family': DEFAULT_NAMESPACE, + 'font-size': DEFAULT_NAMESPACE, + 'font-size-adjust': DEFAULT_NAMESPACE, + 'font-stretch': DEFAULT_NAMESPACE, + 'font-style': DEFAULT_NAMESPACE, + 'font-variant': DEFAULT_NAMESPACE, + 'font-weight': DEFAULT_NAMESPACE, + 'format': DEFAULT_NAMESPACE, + 'from': DEFAULT_NAMESPACE, + 'fx': DEFAULT_NAMESPACE, + 'fy': DEFAULT_NAMESPACE, + 'g1': DEFAULT_NAMESPACE, + 'g2': DEFAULT_NAMESPACE, + 'glyph-name': DEFAULT_NAMESPACE, + 'glyph-orientation-horizontal': DEFAULT_NAMESPACE, + 'glyph-orientation-vertical': DEFAULT_NAMESPACE, + 'glyphRef': DEFAULT_NAMESPACE, + 'gradientTransform': DEFAULT_NAMESPACE, + 'gradientUnits': DEFAULT_NAMESPACE, + 'handler': DEFAULT_NAMESPACE, + 'hanging': DEFAULT_NAMESPACE, + 'height': DEFAULT_NAMESPACE, + 'horiz-adv-x': DEFAULT_NAMESPACE, + 'horiz-origin-x': DEFAULT_NAMESPACE, + 'horiz-origin-y': DEFAULT_NAMESPACE, + 'id': DEFAULT_NAMESPACE, + 'ideographic': DEFAULT_NAMESPACE, + 'image-rendering': DEFAULT_NAMESPACE, + 'in': DEFAULT_NAMESPACE, + 'in2': DEFAULT_NAMESPACE, + 'initialVisibility': DEFAULT_NAMESPACE, + 'intercept': DEFAULT_NAMESPACE, + 'k': DEFAULT_NAMESPACE, + 'k1': DEFAULT_NAMESPACE, + 'k2': DEFAULT_NAMESPACE, + 'k3': DEFAULT_NAMESPACE, + 'k4': DEFAULT_NAMESPACE, + 'kernelMatrix': DEFAULT_NAMESPACE, + 'kernelUnitLength': DEFAULT_NAMESPACE, + 'kerning': DEFAULT_NAMESPACE, + 'keyPoints': DEFAULT_NAMESPACE, + 'keySplines': DEFAULT_NAMESPACE, + 'keyTimes': DEFAULT_NAMESPACE, + 'lang': DEFAULT_NAMESPACE, + 'lengthAdjust': DEFAULT_NAMESPACE, + 'letter-spacing': DEFAULT_NAMESPACE, + 'lighting-color': DEFAULT_NAMESPACE, + 'limitingConeAngle': DEFAULT_NAMESPACE, + 'local': DEFAULT_NAMESPACE, + 'marker-end': DEFAULT_NAMESPACE, + 'marker-mid': DEFAULT_NAMESPACE, + 'marker-start': DEFAULT_NAMESPACE, + 'markerHeight': DEFAULT_NAMESPACE, + 'markerUnits': DEFAULT_NAMESPACE, + 'markerWidth': DEFAULT_NAMESPACE, + 'mask': DEFAULT_NAMESPACE, + 'maskContentUnits': DEFAULT_NAMESPACE, + 'maskUnits': DEFAULT_NAMESPACE, + 'mathematical': DEFAULT_NAMESPACE, + 'max': DEFAULT_NAMESPACE, + 'media': DEFAULT_NAMESPACE, + 'mediaCharacterEncoding': DEFAULT_NAMESPACE, + 'mediaContentEncodings': DEFAULT_NAMESPACE, + 'mediaSize': DEFAULT_NAMESPACE, + 'mediaTime': DEFAULT_NAMESPACE, + 'method': DEFAULT_NAMESPACE, + 'min': DEFAULT_NAMESPACE, + 'mode': DEFAULT_NAMESPACE, + 'name': DEFAULT_NAMESPACE, + 'nav-down': DEFAULT_NAMESPACE, + 'nav-down-left': DEFAULT_NAMESPACE, + 'nav-down-right': DEFAULT_NAMESPACE, + 'nav-left': DEFAULT_NAMESPACE, + 'nav-next': DEFAULT_NAMESPACE, + 'nav-prev': DEFAULT_NAMESPACE, + 'nav-right': DEFAULT_NAMESPACE, + 'nav-up': DEFAULT_NAMESPACE, + 'nav-up-left': DEFAULT_NAMESPACE, + 'nav-up-right': DEFAULT_NAMESPACE, + 'numOctaves': DEFAULT_NAMESPACE, + 'observer': DEFAULT_NAMESPACE, + 'offset': DEFAULT_NAMESPACE, + 'opacity': DEFAULT_NAMESPACE, + 'operator': DEFAULT_NAMESPACE, + 'order': DEFAULT_NAMESPACE, + 'orient': DEFAULT_NAMESPACE, + 'orientation': DEFAULT_NAMESPACE, + 'origin': DEFAULT_NAMESPACE, + 'overflow': DEFAULT_NAMESPACE, + 'overlay': DEFAULT_NAMESPACE, + 'overline-position': DEFAULT_NAMESPACE, + 'overline-thickness': DEFAULT_NAMESPACE, + 'panose-1': DEFAULT_NAMESPACE, + 'path': DEFAULT_NAMESPACE, + 'pathLength': DEFAULT_NAMESPACE, + 'patternContentUnits': DEFAULT_NAMESPACE, + 'patternTransform': DEFAULT_NAMESPACE, + 'patternUnits': DEFAULT_NAMESPACE, + 'phase': DEFAULT_NAMESPACE, + 'playbackOrder': DEFAULT_NAMESPACE, + 'pointer-events': DEFAULT_NAMESPACE, + 'points': DEFAULT_NAMESPACE, + 'pointsAtX': DEFAULT_NAMESPACE, + 'pointsAtY': DEFAULT_NAMESPACE, + 'pointsAtZ': DEFAULT_NAMESPACE, + 'preserveAlpha': DEFAULT_NAMESPACE, + 'preserveAspectRatio': DEFAULT_NAMESPACE, + 'primitiveUnits': DEFAULT_NAMESPACE, + 'propagate': DEFAULT_NAMESPACE, + 'property': DEFAULT_NAMESPACE, + 'r': DEFAULT_NAMESPACE, + 'radius': DEFAULT_NAMESPACE, + 'refX': DEFAULT_NAMESPACE, + 'refY': DEFAULT_NAMESPACE, + 'rel': DEFAULT_NAMESPACE, + 'rendering-intent': DEFAULT_NAMESPACE, + 'repeatCount': DEFAULT_NAMESPACE, + 'repeatDur': DEFAULT_NAMESPACE, + 'requiredExtensions': DEFAULT_NAMESPACE, + 'requiredFeatures': DEFAULT_NAMESPACE, + 'requiredFonts': DEFAULT_NAMESPACE, + 'requiredFormats': DEFAULT_NAMESPACE, + 'resource': DEFAULT_NAMESPACE, + 'restart': DEFAULT_NAMESPACE, + 'result': DEFAULT_NAMESPACE, + 'rev': DEFAULT_NAMESPACE, + 'role': DEFAULT_NAMESPACE, + 'rotate': DEFAULT_NAMESPACE, + 'rx': DEFAULT_NAMESPACE, + 'ry': DEFAULT_NAMESPACE, + 'scale': DEFAULT_NAMESPACE, + 'seed': DEFAULT_NAMESPACE, + 'shape-rendering': DEFAULT_NAMESPACE, + 'slope': DEFAULT_NAMESPACE, + 'snapshotTime': DEFAULT_NAMESPACE, + 'spacing': DEFAULT_NAMESPACE, + 'specularConstant': DEFAULT_NAMESPACE, + 'specularExponent': DEFAULT_NAMESPACE, + 'spreadMethod': DEFAULT_NAMESPACE, + 'startOffset': DEFAULT_NAMESPACE, + 'stdDeviation': DEFAULT_NAMESPACE, + 'stemh': DEFAULT_NAMESPACE, + 'stemv': DEFAULT_NAMESPACE, + 'stitchTiles': DEFAULT_NAMESPACE, + 'stop-color': DEFAULT_NAMESPACE, + 'stop-opacity': DEFAULT_NAMESPACE, + 'strikethrough-position': DEFAULT_NAMESPACE, + 'strikethrough-thickness': DEFAULT_NAMESPACE, + 'string': DEFAULT_NAMESPACE, + 'stroke': DEFAULT_NAMESPACE, + 'stroke-dasharray': DEFAULT_NAMESPACE, + 'stroke-dashoffset': DEFAULT_NAMESPACE, + 'stroke-linecap': DEFAULT_NAMESPACE, + 'stroke-linejoin': DEFAULT_NAMESPACE, + 'stroke-miterlimit': DEFAULT_NAMESPACE, + 'stroke-opacity': DEFAULT_NAMESPACE, + 'stroke-width': DEFAULT_NAMESPACE, + 'surfaceScale': DEFAULT_NAMESPACE, + 'syncBehavior': DEFAULT_NAMESPACE, + 'syncBehaviorDefault': DEFAULT_NAMESPACE, + 'syncMaster': DEFAULT_NAMESPACE, + 'syncTolerance': DEFAULT_NAMESPACE, + 'syncToleranceDefault': DEFAULT_NAMESPACE, + 'systemLanguage': DEFAULT_NAMESPACE, + 'tableValues': DEFAULT_NAMESPACE, + 'target': DEFAULT_NAMESPACE, + 'targetX': DEFAULT_NAMESPACE, + 'targetY': DEFAULT_NAMESPACE, + 'text-anchor': DEFAULT_NAMESPACE, + 'text-decoration': DEFAULT_NAMESPACE, + 'text-rendering': DEFAULT_NAMESPACE, + 'textLength': DEFAULT_NAMESPACE, + 'timelineBegin': DEFAULT_NAMESPACE, + 'title': DEFAULT_NAMESPACE, + 'to': DEFAULT_NAMESPACE, + 'transform': DEFAULT_NAMESPACE, + 'transformBehavior': DEFAULT_NAMESPACE, + 'type': DEFAULT_NAMESPACE, + 'typeof': DEFAULT_NAMESPACE, + 'u1': DEFAULT_NAMESPACE, + 'u2': DEFAULT_NAMESPACE, + 'underline-position': DEFAULT_NAMESPACE, + 'underline-thickness': DEFAULT_NAMESPACE, + 'unicode': DEFAULT_NAMESPACE, + 'unicode-bidi': DEFAULT_NAMESPACE, + 'unicode-range': DEFAULT_NAMESPACE, + 'units-per-em': DEFAULT_NAMESPACE, + 'v-alphabetic': DEFAULT_NAMESPACE, + 'v-hanging': DEFAULT_NAMESPACE, + 'v-ideographic': DEFAULT_NAMESPACE, + 'v-mathematical': DEFAULT_NAMESPACE, + 'values': DEFAULT_NAMESPACE, + 'version': DEFAULT_NAMESPACE, + 'vert-adv-y': DEFAULT_NAMESPACE, + 'vert-origin-x': DEFAULT_NAMESPACE, + 'vert-origin-y': DEFAULT_NAMESPACE, + 'viewBox': DEFAULT_NAMESPACE, + 'viewTarget': DEFAULT_NAMESPACE, + 'visibility': DEFAULT_NAMESPACE, + 'width': DEFAULT_NAMESPACE, + 'widths': DEFAULT_NAMESPACE, + 'word-spacing': DEFAULT_NAMESPACE, + 'writing-mode': DEFAULT_NAMESPACE, + 'x': DEFAULT_NAMESPACE, + 'x-height': DEFAULT_NAMESPACE, + 'x1': DEFAULT_NAMESPACE, + 'x2': DEFAULT_NAMESPACE, + 'xChannelSelector': DEFAULT_NAMESPACE, + 'xlink:actuate': XLINK_NAMESPACE, + 'xlink:arcrole': XLINK_NAMESPACE, + 'xlink:href': XLINK_NAMESPACE, + 'xlink:role': XLINK_NAMESPACE, + 'xlink:show': XLINK_NAMESPACE, + 'xlink:title': XLINK_NAMESPACE, + 'xlink:type': XLINK_NAMESPACE, + 'xml:base': XML_NAMESPACE, + 'xml:id': XML_NAMESPACE, + 'xml:lang': XML_NAMESPACE, + 'xml:space': XML_NAMESPACE, + 'y': DEFAULT_NAMESPACE, + 'y1': DEFAULT_NAMESPACE, + 'y2': DEFAULT_NAMESPACE, + 'yChannelSelector': DEFAULT_NAMESPACE, + 'z': DEFAULT_NAMESPACE, + 'zoomAndPan': DEFAULT_NAMESPACE +}; + +module.exports = SVGAttributeNamespace; + +function SVGAttributeNamespace(value) { + if (SVG_PROPERTIES.hasOwnProperty(value)) { + return SVG_PROPERTIES[value]; + } +} + +},{}],103:[function(require,module,exports){ +'use strict'; + +var isArray = require('x-is-array'); + +var h = require('./index.js'); + + +var SVGAttributeNamespace = require('./svg-attribute-namespace'); +var attributeHook = require('./hooks/attribute-hook'); + +var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; + +module.exports = svg; + +function svg(tagName, properties, children) { + if (!children && isChildren(properties)) { + children = properties; + properties = {}; + } + + properties = properties || {}; + + // set namespace for svg + properties.namespace = SVG_NAMESPACE; + + var attributes = properties.attributes || (properties.attributes = {}); + + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var namespace = SVGAttributeNamespace(key); + + if (namespace === undefined) { // not a svg attribute + continue; + } + + var value = properties[key]; + + if (typeof value !== 'string' && + typeof value !== 'number' && + typeof value !== 'boolean' + ) { + continue; + } + + if (namespace !== null) { // namespaced attribute + properties[key] = attributeHook(namespace, value); + continue; + } + + attributes[key] = value + properties[key] = undefined + } + + return h(tagName, properties, children); +} + +function isChildren(x) { + return typeof x === 'string' || isArray(x); +} + +},{"./hooks/attribute-hook":97,"./index.js":100,"./svg-attribute-namespace":102,"x-is-array":89}],104:[function(require,module,exports){ +var isVNode = require("./is-vnode") +var isVText = require("./is-vtext") +var isWidget = require("./is-widget") +var isThunk = require("./is-thunk") + +module.exports = handleThunk + +function handleThunk(a, b) { + var renderedA = a + var renderedB = b + + if (isThunk(b)) { + renderedB = renderThunk(b, a) + } + + if (isThunk(a)) { + renderedA = renderThunk(a, null) + } + + return { + a: renderedA, + b: renderedB + } +} + +function renderThunk(thunk, previous) { + var renderedThunk = thunk.vnode + + if (!renderedThunk) { + renderedThunk = thunk.vnode = thunk.render(previous) + } + + if (!(isVNode(renderedThunk) || + isVText(renderedThunk) || + isWidget(renderedThunk))) { + throw new Error("thunk did not return a valid node"); + } + + return renderedThunk +} + +},{"./is-thunk":105,"./is-vnode":107,"./is-vtext":108,"./is-widget":109}],105:[function(require,module,exports){ +module.exports = isThunk + +function isThunk(t) { + return t && t.type === "Thunk" +} + +},{}],106:[function(require,module,exports){ +module.exports = isHook + +function isHook(hook) { + return hook && + (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") || + typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook")) +} + +},{}],107:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualNode + +function isVirtualNode(x) { + return x && x.type === "VirtualNode" && x.version === version +} + +},{"./version":110}],108:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualText + +function isVirtualText(x) { + return x && x.type === "VirtualText" && x.version === version +} + +},{"./version":110}],109:[function(require,module,exports){ +module.exports = isWidget + +function isWidget(w) { + return w && w.type === "Widget" +} + +},{}],110:[function(require,module,exports){ +module.exports = "2" + +},{}],111:[function(require,module,exports){ +var version = require("./version") +var isVNode = require("./is-vnode") +var isWidget = require("./is-widget") +var isThunk = require("./is-thunk") +var isVHook = require("./is-vhook") + +module.exports = VirtualNode + +var noProperties = {} +var noChildren = [] + +function VirtualNode(tagName, properties, children, key, namespace) { + this.tagName = tagName + this.properties = properties || noProperties + this.children = children || noChildren + this.key = key != null ? String(key) : undefined + this.namespace = (typeof namespace === "string") ? namespace : null + + var count = (children && children.length) || 0 + var descendants = 0 + var hasWidgets = false + var hasThunks = false + var descendantHooks = false + var hooks + + for (var propName in properties) { + if (properties.hasOwnProperty(propName)) { + var property = properties[propName] + if (isVHook(property) && property.unhook) { + if (!hooks) { + hooks = {} + } + + hooks[propName] = property + } + } + } + + for (var i = 0; i < count; i++) { + var child = children[i] + if (isVNode(child)) { + descendants += child.count || 0 + + if (!hasWidgets && child.hasWidgets) { + hasWidgets = true + } + + if (!hasThunks && child.hasThunks) { + hasThunks = true + } + + if (!descendantHooks && (child.hooks || child.descendantHooks)) { + descendantHooks = true + } + } else if (!hasWidgets && isWidget(child)) { + if (typeof child.destroy === "function") { + hasWidgets = true + } + } else if (!hasThunks && isThunk(child)) { + hasThunks = true; + } + } + + this.count = count + descendants + this.hasWidgets = hasWidgets + this.hasThunks = hasThunks + this.hooks = hooks + this.descendantHooks = descendantHooks +} + +VirtualNode.prototype.version = version +VirtualNode.prototype.type = "VirtualNode" + +},{"./is-thunk":105,"./is-vhook":106,"./is-vnode":107,"./is-widget":109,"./version":110}],112:[function(require,module,exports){ +var version = require("./version") + +VirtualPatch.NONE = 0 +VirtualPatch.VTEXT = 1 +VirtualPatch.VNODE = 2 +VirtualPatch.WIDGET = 3 +VirtualPatch.PROPS = 4 +VirtualPatch.ORDER = 5 +VirtualPatch.INSERT = 6 +VirtualPatch.REMOVE = 7 +VirtualPatch.THUNK = 8 + +module.exports = VirtualPatch + +function VirtualPatch(type, vNode, patch) { + this.type = Number(type) + this.vNode = vNode + this.patch = patch +} + +VirtualPatch.prototype.version = version +VirtualPatch.prototype.type = "VirtualPatch" + +},{"./version":110}],113:[function(require,module,exports){ +var version = require("./version") + +module.exports = VirtualText + +function VirtualText(text) { + this.text = String(text) +} + +VirtualText.prototype.version = version +VirtualText.prototype.type = "VirtualText" + +},{"./version":110}],114:[function(require,module,exports){ +var isObject = require("is-object") +var isHook = require("../vnode/is-vhook") + +module.exports = diffProps + +function diffProps(a, b) { + var diff + + for (var aKey in a) { + if (!(aKey in b)) { + diff = diff || {} + diff[aKey] = undefined + } + + var aValue = a[aKey] + var bValue = b[aKey] + + if (aValue === bValue) { + continue + } else if (isObject(aValue) && isObject(bValue)) { + if (getPrototype(bValue) !== getPrototype(aValue)) { + diff = diff || {} + diff[aKey] = bValue + } else if (isHook(bValue)) { + diff = diff || {} + diff[aKey] = bValue + } else { + var objectDiff = diffProps(aValue, bValue) + if (objectDiff) { + diff = diff || {} + diff[aKey] = objectDiff + } + } + } else { + diff = diff || {} + diff[aKey] = bValue + } + } + + for (var bKey in b) { + if (!(bKey in a)) { + diff = diff || {} + diff[bKey] = b[bKey] + } + } + + return diff +} + +function getPrototype(value) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(value) + } else if (value.__proto__) { + return value.__proto__ + } else if (value.constructor) { + return value.constructor.prototype + } +} + +},{"../vnode/is-vhook":106,"is-object":88}],115:[function(require,module,exports){ +var isArray = require("x-is-array") + +var VPatch = require("../vnode/vpatch") +var isVNode = require("../vnode/is-vnode") +var isVText = require("../vnode/is-vtext") +var isWidget = require("../vnode/is-widget") +var isThunk = require("../vnode/is-thunk") +var handleThunk = require("../vnode/handle-thunk") + +var diffProps = require("./diff-props") + +module.exports = diff + +function diff(a, b) { + var patch = { a: a } + walk(a, b, patch, 0) + return patch +} + +function walk(a, b, patch, index) { + if (a === b) { + return + } + + var apply = patch[index] + var applyClear = false + + if (isThunk(a) || isThunk(b)) { + thunks(a, b, patch, index) + } else if (b == null) { + + // If a is a widget we will add a remove patch for it + // Otherwise any child widgets/hooks must be destroyed. + // This prevents adding two remove patches for a widget. + if (!isWidget(a)) { + clearState(a, patch, index) + apply = patch[index] + } + + apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b)) + } else if (isVNode(b)) { + if (isVNode(a)) { + if (a.tagName === b.tagName && + a.namespace === b.namespace && + a.key === b.key) { + var propsPatch = diffProps(a.properties, b.properties) + if (propsPatch) { + apply = appendPatch(apply, + new VPatch(VPatch.PROPS, a, propsPatch)) + } + apply = diffChildren(a, b, patch, apply, index) + } else { + apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) + applyClear = true + } + } else { + apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) + applyClear = true + } + } else if (isVText(b)) { + if (!isVText(a)) { + apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) + applyClear = true + } else if (a.text !== b.text) { + apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) + } + } else if (isWidget(b)) { + if (!isWidget(a)) { + applyClear = true + } + + apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) + } + + if (apply) { + patch[index] = apply + } + + if (applyClear) { + clearState(a, patch, index) + } +} + +function diffChildren(a, b, patch, apply, index) { + var aChildren = a.children + var orderedSet = reorder(aChildren, b.children) + var bChildren = orderedSet.children + + var aLen = aChildren.length + var bLen = bChildren.length + var len = aLen > bLen ? aLen : bLen + + for (var i = 0; i < len; i++) { + var leftNode = aChildren[i] + var rightNode = bChildren[i] + index += 1 + + if (!leftNode) { + if (rightNode) { + // Excess nodes in b need to be added + apply = appendPatch(apply, + new VPatch(VPatch.INSERT, null, rightNode)) + } + } else { + walk(leftNode, rightNode, patch, index) + } + + if (isVNode(leftNode) && leftNode.count) { + index += leftNode.count + } + } + + if (orderedSet.moves) { + // Reorder nodes last + apply = appendPatch(apply, new VPatch( + VPatch.ORDER, + a, + orderedSet.moves + )) + } + + return apply +} + +function clearState(vNode, patch, index) { + // TODO: Make this a single walk, not two + unhook(vNode, patch, index) + destroyWidgets(vNode, patch, index) +} + +// Patch records for all destroyed widgets must be added because we need +// a DOM node reference for the destroy function +function destroyWidgets(vNode, patch, index) { + if (isWidget(vNode)) { + if (typeof vNode.destroy === "function") { + patch[index] = appendPatch( + patch[index], + new VPatch(VPatch.REMOVE, vNode, null) + ) + } + } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) { + var children = vNode.children + var len = children.length + for (var i = 0; i < len; i++) { + var child = children[i] + index += 1 + + destroyWidgets(child, patch, index) + + if (isVNode(child) && child.count) { + index += child.count + } + } + } else if (isThunk(vNode)) { + thunks(vNode, null, patch, index) + } +} + +// Create a sub-patch for thunks +function thunks(a, b, patch, index) { + var nodes = handleThunk(a, b) + var thunkPatch = diff(nodes.a, nodes.b) + if (hasPatches(thunkPatch)) { + patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) + } +} + +function hasPatches(patch) { + for (var index in patch) { + if (index !== "a") { + return true + } + } + + return false +} + +// Execute hooks when two nodes are identical +function unhook(vNode, patch, index) { + if (isVNode(vNode)) { + if (vNode.hooks) { + patch[index] = appendPatch( + patch[index], + new VPatch( + VPatch.PROPS, + vNode, + undefinedKeys(vNode.hooks) + ) + ) + } + + if (vNode.descendantHooks || vNode.hasThunks) { + var children = vNode.children + var len = children.length + for (var i = 0; i < len; i++) { + var child = children[i] + index += 1 + + unhook(child, patch, index) + + if (isVNode(child) && child.count) { + index += child.count + } + } + } + } else if (isThunk(vNode)) { + thunks(vNode, null, patch, index) + } +} + +function undefinedKeys(obj) { + var result = {} + + for (var key in obj) { + result[key] = undefined + } + + return result +} + +// List diff, naive left to right reordering +function reorder(aChildren, bChildren) { + // O(M) time, O(M) memory + var bChildIndex = keyIndex(bChildren) + var bKeys = bChildIndex.keys + var bFree = bChildIndex.free + + if (bFree.length === bChildren.length) { + return { + children: bChildren, + moves: null + } + } + + // O(N) time, O(N) memory + var aChildIndex = keyIndex(aChildren) + var aKeys = aChildIndex.keys + var aFree = aChildIndex.free + + if (aFree.length === aChildren.length) { + return { + children: bChildren, + moves: null + } + } + + // O(MAX(N, M)) memory + var newChildren = [] + + var freeIndex = 0 + var freeCount = bFree.length + var deletedItems = 0 + + // Iterate through a and match a node in b + // O(N) time, + for (var i = 0 ; i < aChildren.length; i++) { + var aItem = aChildren[i] + var itemIndex + + if (aItem.key) { + if (bKeys.hasOwnProperty(aItem.key)) { + // Match up the old keys + itemIndex = bKeys[aItem.key] + newChildren.push(bChildren[itemIndex]) + + } else { + // Remove old keyed items + itemIndex = i - deletedItems++ + newChildren.push(null) + } + } else { + // Match the item in a with the next free item in b + if (freeIndex < freeCount) { + itemIndex = bFree[freeIndex++] + newChildren.push(bChildren[itemIndex]) + } else { + // There are no free items in b to match with + // the free items in a, so the extra free nodes + // are deleted. + itemIndex = i - deletedItems++ + newChildren.push(null) + } + } + } + + var lastFreeIndex = freeIndex >= bFree.length ? + bChildren.length : + bFree[freeIndex] + + // Iterate through b and append any new keys + // O(M) time + for (var j = 0; j < bChildren.length; j++) { + var newItem = bChildren[j] + + if (newItem.key) { + if (!aKeys.hasOwnProperty(newItem.key)) { + // Add any new keyed items + // We are adding new items to the end and then sorting them + // in place. In future we should insert new items in place. + newChildren.push(newItem) + } + } else if (j >= lastFreeIndex) { + // Add any leftover non-keyed items + newChildren.push(newItem) + } + } + + var simulate = newChildren.slice() + var simulateIndex = 0 + var removes = [] + var inserts = [] + var simulateItem + + for (var k = 0; k < bChildren.length;) { + var wantedItem = bChildren[k] + simulateItem = simulate[simulateIndex] + + // remove items + while (simulateItem === null && simulate.length) { + removes.push(remove(simulate, simulateIndex, null)) + simulateItem = simulate[simulateIndex] + } + + if (!simulateItem || simulateItem.key !== wantedItem.key) { + // if we need a key in this position... + if (wantedItem.key) { + if (simulateItem && simulateItem.key) { + // if an insert doesn't put this key in place, it needs to move + if (bKeys[simulateItem.key] !== k + 1) { + removes.push(remove(simulate, simulateIndex, simulateItem.key)) + simulateItem = simulate[simulateIndex] + // if the remove didn't put the wanted item in place, we need to insert it + if (!simulateItem || simulateItem.key !== wantedItem.key) { + inserts.push({key: wantedItem.key, to: k}) + } + // items are matching, so skip ahead + else { + simulateIndex++ + } + } + else { + inserts.push({key: wantedItem.key, to: k}) + } + } + else { + inserts.push({key: wantedItem.key, to: k}) + } + k++ + } + // a key in simulate has no matching wanted key, remove it + else if (simulateItem && simulateItem.key) { + removes.push(remove(simulate, simulateIndex, simulateItem.key)) + } + } + else { + simulateIndex++ + k++ + } + } + + // remove all the remaining nodes from simulate + while(simulateIndex < simulate.length) { + simulateItem = simulate[simulateIndex] + removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) + } + + // If the only moves we have are deletes then we can just + // let the delete patch remove these items. + if (removes.length === deletedItems && !inserts.length) { + return { + children: newChildren, + moves: null + } + } + + return { + children: newChildren, + moves: { + removes: removes, + inserts: inserts + } + } +} + +function remove(arr, index, key) { + arr.splice(index, 1) + + return { + from: index, + key: key + } +} + +function keyIndex(children) { + var keys = {} + var free = [] + var length = children.length + + for (var i = 0; i < length; i++) { + var child = children[i] + + if (child.key) { + keys[child.key] = i + } else { + free.push(i) + } + } + + return { + keys: keys, // A hash of key name to index + free: free // An array of unkeyed item indices + } +} + +function appendPatch(apply, patch) { + if (apply) { + if (isArray(apply)) { + apply.push(patch) + } else { + apply = [apply, patch] + } + + return apply + } else { + return patch + } +} + +},{"../vnode/handle-thunk":104,"../vnode/is-thunk":105,"../vnode/is-vnode":107,"../vnode/is-vtext":108,"../vnode/is-widget":109,"../vnode/vpatch":112,"./diff-props":114,"x-is-array":89}],116:[function(require,module,exports){ + +},{}],117:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = setTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + clearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + setTimeout(drainQueue, 0); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],118:[function(require,module,exports){ +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.Immutable = factory(); +}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; + + function createClass(ctor, superClass) { + if (superClass) { + ctor.prototype = Object.create(superClass.prototype); + } + ctor.prototype.constructor = ctor; + } + + function Iterable(value) { + return isIterable(value) ? value : Seq(value); + } + + + createClass(KeyedIterable, Iterable); + function KeyedIterable(value) { + return isKeyed(value) ? value : KeyedSeq(value); + } + + + createClass(IndexedIterable, Iterable); + function IndexedIterable(value) { + return isIndexed(value) ? value : IndexedSeq(value); + } + + + createClass(SetIterable, Iterable); + function SetIterable(value) { + return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); + } + + + + function isIterable(maybeIterable) { + return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); + } + + function isKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); + } + + function isIndexed(maybeIndexed) { + return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); + } + + function isAssociative(maybeAssociative) { + return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); + } + + function isOrdered(maybeOrdered) { + return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); + } + + Iterable.isIterable = isIterable; + Iterable.isKeyed = isKeyed; + Iterable.isIndexed = isIndexed; + Iterable.isAssociative = isAssociative; + Iterable.isOrdered = isOrdered; + + Iterable.Keyed = KeyedIterable; + Iterable.Indexed = IndexedIterable; + Iterable.Set = SetIterable; + + + var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + // Used for setting prototype methods that IE8 chokes on. + var DELETE = 'delete'; + + // Constants describing the size of trie nodes. + var SHIFT = 5; // Resulted in best performance after ______? + var SIZE = 1 << SHIFT; + var MASK = SIZE - 1; + + // A consistent shared value representing "not set" which equals nothing other + // than itself, and nothing that could be provided externally. + var NOT_SET = {}; + + // Boolean references, Rough equivalent of `bool &`. + var CHANGE_LENGTH = { value: false }; + var DID_ALTER = { value: false }; + + function MakeRef(ref) { + ref.value = false; + return ref; + } + + function SetRef(ref) { + ref && (ref.value = true); + } + + // A function which returns a value representing an "owner" for transient writes + // to tries. The return value will only ever equal itself, and will not equal + // the return of any subsequent call of this function. + function OwnerID() {} + + // http://jsperf.com/copy-array-inline + function arrCopy(arr, offset) { + offset = offset || 0; + var len = Math.max(0, arr.length - offset); + var newArr = new Array(len); + for (var ii = 0; ii < len; ii++) { + newArr[ii] = arr[ii + offset]; + } + return newArr; + } + + function ensureSize(iter) { + if (iter.size === undefined) { + iter.size = iter.__iterate(returnTrue); + } + return iter.size; + } + + function wrapIndex(iter, index) { + // This implements "is array index" which the ECMAString spec defines as: + // + // A String property name P is an array index if and only if + // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal + // to 2^32−1. + // + // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects + if (typeof index !== 'number') { + var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 + if ('' + uint32Index !== index || uint32Index === 4294967295) { + return NaN; + } + index = uint32Index; + } + return index < 0 ? ensureSize(iter) + index : index; + } + + function returnTrue() { + return true; + } + + function wholeSlice(begin, end, size) { + return (begin === 0 || (size !== undefined && begin <= -size)) && + (end === undefined || (size !== undefined && end >= size)); + } + + function resolveBegin(begin, size) { + return resolveIndex(begin, size, 0); + } + + function resolveEnd(end, size) { + return resolveIndex(end, size, size); + } + + function resolveIndex(index, size, defaultIndex) { + return index === undefined ? + defaultIndex : + index < 0 ? + Math.max(0, size + index) : + size === undefined ? + index : + Math.min(size, index); + } + + /* global Symbol */ + + var ITERATE_KEYS = 0; + var ITERATE_VALUES = 1; + var ITERATE_ENTRIES = 2; + + var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + + var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; + + + function Iterator(next) { + this.next = next; + } + + Iterator.prototype.toString = function() { + return '[Iterator]'; + }; + + + Iterator.KEYS = ITERATE_KEYS; + Iterator.VALUES = ITERATE_VALUES; + Iterator.ENTRIES = ITERATE_ENTRIES; + + Iterator.prototype.inspect = + Iterator.prototype.toSource = function () { return this.toString(); } + Iterator.prototype[ITERATOR_SYMBOL] = function () { + return this; + }; + + + function iteratorValue(type, k, v, iteratorResult) { + var value = type === 0 ? k : type === 1 ? v : [k, v]; + iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { + value: value, done: false + }); + return iteratorResult; + } + + function iteratorDone() { + return { value: undefined, done: true }; + } + + function hasIterator(maybeIterable) { + return !!getIteratorFn(maybeIterable); + } + + function isIterator(maybeIterator) { + return maybeIterator && typeof maybeIterator.next === 'function'; + } + + function getIterator(iterable) { + var iteratorFn = getIteratorFn(iterable); + return iteratorFn && iteratorFn.call(iterable); + } + + function getIteratorFn(iterable) { + var iteratorFn = iterable && ( + (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || + iterable[FAUX_ITERATOR_SYMBOL] + ); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + function isArrayLike(value) { + return value && typeof value.length === 'number'; + } + + createClass(Seq, Iterable); + function Seq(value) { + return value === null || value === undefined ? emptySequence() : + isIterable(value) ? value.toSeq() : seqFromValue(value); + } + + Seq.of = function(/*...values*/) { + return Seq(arguments); + }; + + Seq.prototype.toSeq = function() { + return this; + }; + + Seq.prototype.toString = function() { + return this.__toString('Seq {', '}'); + }; + + Seq.prototype.cacheResult = function() { + if (!this._cache && this.__iterateUncached) { + this._cache = this.entrySeq().toArray(); + this.size = this._cache.length; + } + return this; + }; + + // abstract __iterateUncached(fn, reverse) + + Seq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, true); + }; + + // abstract __iteratorUncached(type, reverse) + + Seq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, true); + }; + + + + createClass(KeyedSeq, Seq); + function KeyedSeq(value) { + return value === null || value === undefined ? + emptySequence().toKeyedSeq() : + isIterable(value) ? + (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : + keyedSeqFromValue(value); + } + + KeyedSeq.prototype.toKeyedSeq = function() { + return this; + }; + + + + createClass(IndexedSeq, Seq); + function IndexedSeq(value) { + return value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); + } + + IndexedSeq.of = function(/*...values*/) { + return IndexedSeq(arguments); + }; + + IndexedSeq.prototype.toIndexedSeq = function() { + return this; + }; + + IndexedSeq.prototype.toString = function() { + return this.__toString('Seq [', ']'); + }; + + IndexedSeq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, false); + }; + + IndexedSeq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, false); + }; + + + + createClass(SetSeq, Seq); + function SetSeq(value) { + return ( + value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value + ).toSetSeq(); + } + + SetSeq.of = function(/*...values*/) { + return SetSeq(arguments); + }; + + SetSeq.prototype.toSetSeq = function() { + return this; + }; + + + + Seq.isSeq = isSeq; + Seq.Keyed = KeyedSeq; + Seq.Set = SetSeq; + Seq.Indexed = IndexedSeq; + + var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; + + Seq.prototype[IS_SEQ_SENTINEL] = true; + + + + createClass(ArraySeq, IndexedSeq); + function ArraySeq(array) { + this._array = array; + this.size = array.length; + } + + ArraySeq.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; + }; + + ArraySeq.prototype.__iterate = function(fn, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ArraySeq.prototype.__iterator = function(type, reverse) { + var array = this._array; + var maxIndex = array.length - 1; + var ii = 0; + return new Iterator(function() + {return ii > maxIndex ? + iteratorDone() : + iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} + ); + }; + + + + createClass(ObjectSeq, KeyedSeq); + function ObjectSeq(object) { + var keys = Object.keys(object); + this._object = object; + this._keys = keys; + this.size = keys.length; + } + + ObjectSeq.prototype.get = function(key, notSetValue) { + if (notSetValue !== undefined && !this.has(key)) { + return notSetValue; + } + return this._object[key]; + }; + + ObjectSeq.prototype.has = function(key) { + return this._object.hasOwnProperty(key); + }; + + ObjectSeq.prototype.__iterate = function(fn, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var key = keys[reverse ? maxIndex - ii : ii]; + if (fn(object[key], key, this) === false) { + return ii + 1; + } + } + return ii; + }; + + ObjectSeq.prototype.__iterator = function(type, reverse) { + var object = this._object; + var keys = this._keys; + var maxIndex = keys.length - 1; + var ii = 0; + return new Iterator(function() { + var key = keys[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, key, object[key]); + }); + }; + + ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(IterableSeq, IndexedSeq); + function IterableSeq(iterable) { + this._iterable = iterable; + this.size = iterable.length || iterable.size; + } + + IterableSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + var iterations = 0; + if (isIterator(iterator)) { + var step; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + } + return iterations; + }; + + IterableSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterable = this._iterable; + var iterator = getIterator(iterable); + if (!isIterator(iterator)) { + return new Iterator(iteratorDone); + } + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : iteratorValue(type, iterations++, step.value); + }); + }; + + + + createClass(IteratorSeq, IndexedSeq); + function IteratorSeq(iterator) { + this._iterator = iterator; + this._iteratorCache = []; + } + + IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + while (iterations < cache.length) { + if (fn(cache[iterations], iterations++, this) === false) { + return iterations; + } + } + var step; + while (!(step = iterator.next()).done) { + var val = step.value; + cache[iterations] = val; + if (fn(val, iterations++, this) === false) { + break; + } + } + return iterations; + }; + + IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = this._iterator; + var cache = this._iteratorCache; + var iterations = 0; + return new Iterator(function() { + if (iterations >= cache.length) { + var step = iterator.next(); + if (step.done) { + return step; + } + cache[iterations] = step.value; + } + return iteratorValue(type, iterations, cache[iterations++]); + }); + }; + + + + + // # pragma Helper functions + + function isSeq(maybeSeq) { + return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); + } + + var EMPTY_SEQ; + + function emptySequence() { + return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); + } + + function keyedSeqFromValue(value) { + var seq = + Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : + isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : + hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : + typeof value === 'object' ? new ObjectSeq(value) : + undefined; + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of [k, v] entries, '+ + 'or keyed object: ' + value + ); + } + return seq; + } + + function indexedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values: ' + value + ); + } + return seq; + } + + function seqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value) || + (typeof value === 'object' && new ObjectSeq(value)); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values, or keyed object: ' + value + ); + } + return seq; + } + + function maybeIndexedSeqFromValue(value) { + return ( + isArrayLike(value) ? new ArraySeq(value) : + isIterator(value) ? new IteratorSeq(value) : + hasIterator(value) ? new IterableSeq(value) : + undefined + ); + } + + function seqIterate(seq, fn, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + for (var ii = 0; ii <= maxIndex; ii++) { + var entry = cache[reverse ? maxIndex - ii : ii]; + if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { + return ii + 1; + } + } + return ii; + } + return seq.__iterateUncached(fn, reverse); + } + + function seqIterator(seq, type, reverse, useKeys) { + var cache = seq._cache; + if (cache) { + var maxIndex = cache.length - 1; + var ii = 0; + return new Iterator(function() { + var entry = cache[reverse ? maxIndex - ii : ii]; + return ii++ > maxIndex ? + iteratorDone() : + iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); + }); + } + return seq.__iteratorUncached(type, reverse); + } + + function fromJS(json, converter) { + return converter ? + fromJSWith(converter, json, '', {'': json}) : + fromJSDefault(json); + } + + function fromJSWith(converter, json, key, parentJSON) { + if (Array.isArray(json)) { + return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + if (isPlainObj(json)) { + return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + } + return json; + } + + function fromJSDefault(json) { + if (Array.isArray(json)) { + return IndexedSeq(json).map(fromJSDefault).toList(); + } + if (isPlainObj(json)) { + return KeyedSeq(json).map(fromJSDefault).toMap(); + } + return json; + } + + function isPlainObj(value) { + return value && (value.constructor === Object || value.constructor === undefined); + } + + /** + * An extension of the "same-value" algorithm as [described for use by ES6 Map + * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) + * + * NaN is considered the same as NaN, however -0 and 0 are considered the same + * value, which is different from the algorithm described by + * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * This is extended further to allow Objects to describe the values they + * represent, by way of `valueOf` or `equals` (and `hashCode`). + * + * Note: because of this extension, the key equality of Immutable.Map and the + * value equality of Immutable.Set will differ from ES6 Map and Set. + * + * ### Defining custom values + * + * The easiest way to describe the value an object represents is by implementing + * `valueOf`. For example, `Date` represents a value by returning a unix + * timestamp for `valueOf`: + * + * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... + * var date2 = new Date(1234567890000); + * date1.valueOf(); // 1234567890000 + * assert( date1 !== date2 ); + * assert( Immutable.is( date1, date2 ) ); + * + * Note: overriding `valueOf` may have other implications if you use this object + * where JavaScript expects a primitive, such as implicit string coercion. + * + * For more complex types, especially collections, implementing `valueOf` may + * not be performant. An alternative is to implement `equals` and `hashCode`. + * + * `equals` takes another object, presumably of similar type, and returns true + * if the it is equal. Equality is symmetrical, so the same result should be + * returned if this and the argument are flipped. + * + * assert( a.equals(b) === b.equals(a) ); + * + * `hashCode` returns a 32bit integer number representing the object which will + * be used to determine how to store the value object in a Map or Set. You must + * provide both or neither methods, one must not exist without the other. + * + * Also, an important relationship between these methods must be upheld: if two + * values are equal, they *must* return the same hashCode. If the values are not + * equal, they might have the same hashCode; this is called a hash collision, + * and while undesirable for performance reasons, it is acceptable. + * + * if (a.equals(b)) { + * assert( a.hashCode() === b.hashCode() ); + * } + * + * All Immutable collections implement `equals` and `hashCode`. + * + */ + function is(valueA, valueB) { + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + if (typeof valueA.valueOf === 'function' && + typeof valueB.valueOf === 'function') { + valueA = valueA.valueOf(); + valueB = valueB.valueOf(); + if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { + return true; + } + if (!valueA || !valueB) { + return false; + } + } + if (typeof valueA.equals === 'function' && + typeof valueB.equals === 'function' && + valueA.equals(valueB)) { + return true; + } + return false; + } + + function deepEqual(a, b) { + if (a === b) { + return true; + } + + if ( + !isIterable(b) || + a.size !== undefined && b.size !== undefined && a.size !== b.size || + a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || + isKeyed(a) !== isKeyed(b) || + isIndexed(a) !== isIndexed(b) || + isOrdered(a) !== isOrdered(b) + ) { + return false; + } + + if (a.size === 0 && b.size === 0) { + return true; + } + + var notAssociative = !isAssociative(a); + + if (isOrdered(a)) { + var entries = a.entries(); + return b.every(function(v, k) { + var entry = entries.next().value; + return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); + }) && entries.next().done; + } + + var flipped = false; + + if (a.size === undefined) { + if (b.size === undefined) { + if (typeof a.cacheResult === 'function') { + a.cacheResult(); + } + } else { + flipped = true; + var _ = a; + a = b; + b = _; + } + } + + var allEqual = true; + var bSize = b.__iterate(function(v, k) { + if (notAssociative ? !a.has(v) : + flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { + allEqual = false; + return false; + } + }); + + return allEqual && a.size === bSize; + } + + createClass(Repeat, IndexedSeq); + + function Repeat(value, times) { + if (!(this instanceof Repeat)) { + return new Repeat(value, times); + } + this._value = value; + this.size = times === undefined ? Infinity : Math.max(0, times); + if (this.size === 0) { + if (EMPTY_REPEAT) { + return EMPTY_REPEAT; + } + EMPTY_REPEAT = this; + } + } + + Repeat.prototype.toString = function() { + if (this.size === 0) { + return 'Repeat []'; + } + return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }; + + Repeat.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._value : notSetValue; + }; + + Repeat.prototype.includes = function(searchValue) { + return is(this._value, searchValue); + }; + + Repeat.prototype.slice = function(begin, end) { + var size = this.size; + return wholeSlice(begin, end, size) ? this : + new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); + }; + + Repeat.prototype.reverse = function() { + return this; + }; + + Repeat.prototype.indexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return 0; + } + return -1; + }; + + Repeat.prototype.lastIndexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return this.size; + } + return -1; + }; + + Repeat.prototype.__iterate = function(fn, reverse) { + for (var ii = 0; ii < this.size; ii++) { + if (fn(this._value, ii, this) === false) { + return ii + 1; + } + } + return ii; + }; + + Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; + var ii = 0; + return new Iterator(function() + {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} + ); + }; + + Repeat.prototype.equals = function(other) { + return other instanceof Repeat ? + is(this._value, other._value) : + deepEqual(other); + }; + + + var EMPTY_REPEAT; + + function invariant(condition, error) { + if (!condition) throw new Error(error); + } + + createClass(Range, IndexedSeq); + + function Range(start, end, step) { + if (!(this instanceof Range)) { + return new Range(start, end, step); + } + invariant(step !== 0, 'Cannot step a Range by 0'); + start = start || 0; + if (end === undefined) { + end = Infinity; + } + step = step === undefined ? 1 : Math.abs(step); + if (end < start) { + step = -step; + } + this._start = start; + this._end = end; + this._step = step; + this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); + if (this.size === 0) { + if (EMPTY_RANGE) { + return EMPTY_RANGE; + } + EMPTY_RANGE = this; + } + } + + Range.prototype.toString = function() { + if (this.size === 0) { + return 'Range []'; + } + return 'Range [ ' + + this._start + '...' + this._end + + (this._step > 1 ? ' by ' + this._step : '') + + ' ]'; + }; + + Range.prototype.get = function(index, notSetValue) { + return this.has(index) ? + this._start + wrapIndex(this, index) * this._step : + notSetValue; + }; + + Range.prototype.includes = function(searchValue) { + var possibleIndex = (searchValue - this._start) / this._step; + return possibleIndex >= 0 && + possibleIndex < this.size && + possibleIndex === Math.floor(possibleIndex); + }; + + Range.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + begin = resolveBegin(begin, this.size); + end = resolveEnd(end, this.size); + if (end <= begin) { + return new Range(0, 0); + } + return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); + }; + + Range.prototype.indexOf = function(searchValue) { + var offsetValue = searchValue - this._start; + if (offsetValue % this._step === 0) { + var index = offsetValue / this._step; + if (index >= 0 && index < this.size) { + return index + } + } + return -1; + }; + + Range.prototype.lastIndexOf = function(searchValue) { + return this.indexOf(searchValue); + }; + + Range.prototype.__iterate = function(fn, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + for (var ii = 0; ii <= maxIndex; ii++) { + if (fn(value, ii, this) === false) { + return ii + 1; + } + value += reverse ? -step : step; + } + return ii; + }; + + Range.prototype.__iterator = function(type, reverse) { + var maxIndex = this.size - 1; + var step = this._step; + var value = reverse ? this._start + maxIndex * step : this._start; + var ii = 0; + return new Iterator(function() { + var v = value; + value += reverse ? -step : step; + return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); + }); + }; + + Range.prototype.equals = function(other) { + return other instanceof Range ? + this._start === other._start && + this._end === other._end && + this._step === other._step : + deepEqual(this, other); + }; + + + var EMPTY_RANGE; + + createClass(Collection, Iterable); + function Collection() { + throw TypeError('Abstract'); + } + + + createClass(KeyedCollection, Collection);function KeyedCollection() {} + + createClass(IndexedCollection, Collection);function IndexedCollection() {} + + createClass(SetCollection, Collection);function SetCollection() {} + + + Collection.Keyed = KeyedCollection; + Collection.Indexed = IndexedCollection; + Collection.Set = SetCollection; + + var imul = + typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? + Math.imul : + function imul(a, b) { + a = a | 0; // int + b = b | 0; // int + var c = a & 0xffff; + var d = b & 0xffff; + // Shift by 0 fixes the sign on the high part. + return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int + }; + + // v8 has an optimization for storing 31-bit signed numbers. + // Values which have either 00 or 11 as the high order bits qualify. + // This function drops the highest order bit in a signed number, maintaining + // the sign bit. + function smi(i32) { + return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); + } + + function hash(o) { + if (o === false || o === null || o === undefined) { + return 0; + } + if (typeof o.valueOf === 'function') { + o = o.valueOf(); + if (o === false || o === null || o === undefined) { + return 0; + } + } + if (o === true) { + return 1; + } + var type = typeof o; + if (type === 'number') { + var h = o | 0; + if (h !== o) { + h ^= o * 0xFFFFFFFF; + } + while (o > 0xFFFFFFFF) { + o /= 0xFFFFFFFF; + h ^= o; + } + return smi(h); + } + if (type === 'string') { + return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); + } + if (typeof o.hashCode === 'function') { + return o.hashCode(); + } + if (type === 'object') { + return hashJSObj(o); + } + if (typeof o.toString === 'function') { + return hashString(o.toString()); + } + throw new Error('Value type ' + type + ' cannot be hashed.'); + } + + function cachedHashString(string) { + var hash = stringHashCache[string]; + if (hash === undefined) { + hash = hashString(string); + if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { + STRING_HASH_CACHE_SIZE = 0; + stringHashCache = {}; + } + STRING_HASH_CACHE_SIZE++; + stringHashCache[string] = hash; + } + return hash; + } + + // http://jsperf.com/hashing-strings + function hashString(string) { + // This is the hash from JVM + // The hash code for a string is computed as + // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], + // where s[i] is the ith character of the string and n is the length of + // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 + // (exclusive) by dropping high bits. + var hash = 0; + for (var ii = 0; ii < string.length; ii++) { + hash = 31 * hash + string.charCodeAt(ii) | 0; + } + return smi(hash); + } + + function hashJSObj(obj) { + var hash; + if (usingWeakMap) { + hash = weakMap.get(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = obj[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + if (!canDefineProperty) { + hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; + if (hash !== undefined) { + return hash; + } + + hash = getIENodeHash(obj); + if (hash !== undefined) { + return hash; + } + } + + hash = ++objHashUID; + if (objHashUID & 0x40000000) { + objHashUID = 0; + } + + if (usingWeakMap) { + weakMap.set(obj, hash); + } else if (isExtensible !== undefined && isExtensible(obj) === false) { + throw new Error('Non-extensible objects are not allowed as keys.'); + } else if (canDefineProperty) { + Object.defineProperty(obj, UID_HASH_KEY, { + 'enumerable': false, + 'configurable': false, + 'writable': false, + 'value': hash + }); + } else if (obj.propertyIsEnumerable !== undefined && + obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { + // Since we can't define a non-enumerable property on the object + // we'll hijack one of the less-used non-enumerable properties to + // save our hash on it. Since this is a function it will not show up in + // `JSON.stringify` which is what we want. + obj.propertyIsEnumerable = function() { + return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); + }; + obj.propertyIsEnumerable[UID_HASH_KEY] = hash; + } else if (obj.nodeType !== undefined) { + // At this point we couldn't get the IE `uniqueID` to use as a hash + // and we couldn't use a non-enumerable property to exploit the + // dontEnum bug so we simply add the `UID_HASH_KEY` on the node + // itself. + obj[UID_HASH_KEY] = hash; + } else { + throw new Error('Unable to set a non-enumerable property on object.'); + } + + return hash; + } + + // Get references to ES5 object methods. + var isExtensible = Object.isExtensible; + + // True if Object.defineProperty works as expected. IE8 fails this test. + var canDefineProperty = (function() { + try { + Object.defineProperty({}, '@', {}); + return true; + } catch (e) { + return false; + } + }()); + + // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it + // and avoid memory leaks from the IE cloneNode bug. + function getIENodeHash(node) { + if (node && node.nodeType > 0) { + switch (node.nodeType) { + case 1: // Element + return node.uniqueID; + case 9: // Document + return node.documentElement && node.documentElement.uniqueID; + } + } + } + + // If possible, use a WeakMap. + var usingWeakMap = typeof WeakMap === 'function'; + var weakMap; + if (usingWeakMap) { + weakMap = new WeakMap(); + } + + var objHashUID = 0; + + var UID_HASH_KEY = '__immutablehash__'; + if (typeof Symbol === 'function') { + UID_HASH_KEY = Symbol(UID_HASH_KEY); + } + + var STRING_HASH_CACHE_MIN_STRLEN = 16; + var STRING_HASH_CACHE_MAX_SIZE = 255; + var STRING_HASH_CACHE_SIZE = 0; + var stringHashCache = {}; + + function assertNotInfinite(size) { + invariant( + size !== Infinity, + 'Cannot perform this action with an infinite size.' + ); + } + + createClass(Map, KeyedCollection); + + // @pragma Construction + + function Map(value) { + return value === null || value === undefined ? emptyMap() : + isMap(value) && !isOrdered(value) ? value : + emptyMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + Map.prototype.toString = function() { + return this.__toString('Map {', '}'); + }; + + // @pragma Access + + Map.prototype.get = function(k, notSetValue) { + return this._root ? + this._root.get(0, undefined, k, notSetValue) : + notSetValue; + }; + + // @pragma Modification + + Map.prototype.set = function(k, v) { + return updateMap(this, k, v); + }; + + Map.prototype.setIn = function(keyPath, v) { + return this.updateIn(keyPath, NOT_SET, function() {return v}); + }; + + Map.prototype.remove = function(k) { + return updateMap(this, k, NOT_SET); + }; + + Map.prototype.deleteIn = function(keyPath) { + return this.updateIn(keyPath, function() {return NOT_SET}); + }; + + Map.prototype.update = function(k, notSetValue, updater) { + return arguments.length === 1 ? + k(this) : + this.updateIn([k], notSetValue, updater); + }; + + Map.prototype.updateIn = function(keyPath, notSetValue, updater) { + if (!updater) { + updater = notSetValue; + notSetValue = undefined; + } + var updatedValue = updateInDeepMap( + this, + forceIterator(keyPath), + notSetValue, + updater + ); + return updatedValue === NOT_SET ? undefined : updatedValue; + }; + + Map.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._root = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyMap(); + }; + + // @pragma Composition + + Map.prototype.merge = function(/*...iters*/) { + return mergeIntoMapWith(this, undefined, arguments); + }; + + Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, merger, iters); + }; + + Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.merge === 'function' ? + m.merge.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoMapWith(this, deepMerger, arguments); + }; + + Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, deepMergerWith(merger), iters); + }; + + Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); + return this.updateIn( + keyPath, + emptyMap(), + function(m ) {return typeof m.mergeDeep === 'function' ? + m.mergeDeep.apply(m, iters) : + iters[iters.length - 1]} + ); + }; + + Map.prototype.sort = function(comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator)); + }; + + Map.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator, mapper)); + }; + + // @pragma Mutability + + Map.prototype.withMutations = function(fn) { + var mutable = this.asMutable(); + fn(mutable); + return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; + }; + + Map.prototype.asMutable = function() { + return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); + }; + + Map.prototype.asImmutable = function() { + return this.__ensureOwner(); + }; + + Map.prototype.wasAltered = function() { + return this.__altered; + }; + + Map.prototype.__iterator = function(type, reverse) { + return new MapIterator(this, type, reverse); + }; + + Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + this._root && this._root.iterate(function(entry ) { + iterations++; + return fn(entry[1], entry[0], this$0); + }, reverse); + return iterations; + }; + + Map.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeMap(this.size, this._root, ownerID, this.__hash); + }; + + + function isMap(maybeMap) { + return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); + } + + Map.isMap = isMap; + + var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + + var MapPrototype = Map.prototype; + MapPrototype[IS_MAP_SENTINEL] = true; + MapPrototype[DELETE] = MapPrototype.remove; + MapPrototype.removeIn = MapPrototype.deleteIn; + + + // #pragma Trie Nodes + + + + function ArrayMapNode(ownerID, entries) { + this.ownerID = ownerID; + this.entries = entries; + } + + ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && entries.length === 1) { + return; // undefined + } + + if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { + return createNodes(ownerID, entries, key, value); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new ArrayMapNode(ownerID, newEntries); + }; + + + + + function BitmapIndexedNode(ownerID, bitmap, nodes) { + this.ownerID = ownerID; + this.bitmap = bitmap; + this.nodes = nodes; + } + + BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); + var bitmap = this.bitmap; + return (bitmap & bit) === 0 ? notSetValue : + this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); + }; + + BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var bit = 1 << keyHashFrag; + var bitmap = this.bitmap; + var exists = (bitmap & bit) !== 0; + + if (!exists && value === NOT_SET) { + return this; + } + + var idx = popCount(bitmap & (bit - 1)); + var nodes = this.nodes; + var node = exists ? nodes[idx] : undefined; + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + + if (newNode === node) { + return this; + } + + if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { + return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); + } + + if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { + return nodes[idx ^ 1]; + } + + if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { + return newNode; + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; + var newNodes = exists ? newNode ? + setIn(nodes, idx, newNode, isEditable) : + spliceOut(nodes, idx, isEditable) : + spliceIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.bitmap = newBitmap; + this.nodes = newNodes; + return this; + } + + return new BitmapIndexedNode(ownerID, newBitmap, newNodes); + }; + + + + + function HashArrayMapNode(ownerID, count, nodes) { + this.ownerID = ownerID; + this.count = count; + this.nodes = nodes; + } + + HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var node = this.nodes[idx]; + return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; + }; + + HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var removed = value === NOT_SET; + var nodes = this.nodes; + var node = nodes[idx]; + + if (removed && !node) { + return this; + } + + var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); + if (newNode === node) { + return this; + } + + var newCount = this.count; + if (!node) { + newCount++; + } else if (!newNode) { + newCount--; + if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { + return packNodes(ownerID, nodes, newCount, idx); + } + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newNodes = setIn(nodes, idx, newNode, isEditable); + + if (isEditable) { + this.count = newCount; + this.nodes = newNodes; + return this; + } + + return new HashArrayMapNode(ownerID, newCount, newNodes); + }; + + + + + function HashCollisionNode(ownerID, keyHash, entries) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entries = entries; + } + + HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { + var entries = this.entries; + for (var ii = 0, len = entries.length; ii < len; ii++) { + if (is(key, entries[ii][0])) { + return entries[ii][1]; + } + } + return notSetValue; + }; + + HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } + + var removed = value === NOT_SET; + + if (keyHash !== this.keyHash) { + if (removed) { + return this; + } + SetRef(didAlter); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); + } + + var entries = this.entries; + var idx = 0; + for (var len = entries.length; idx < len; idx++) { + if (is(key, entries[idx][0])) { + break; + } + } + var exists = idx < len; + + if (exists ? entries[idx][1] === value : removed) { + return this; + } + + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); + + if (removed && len === 2) { + return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); + } + + var isEditable = ownerID && ownerID === this.ownerID; + var newEntries = isEditable ? entries : arrCopy(entries); + + if (exists) { + if (removed) { + idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + } else { + newEntries[idx] = [key, value]; + } + } else { + newEntries.push([key, value]); + } + + if (isEditable) { + this.entries = newEntries; + return this; + } + + return new HashCollisionNode(ownerID, this.keyHash, newEntries); + }; + + + + + function ValueNode(ownerID, keyHash, entry) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entry = entry; + } + + ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { + return is(key, this.entry[0]) ? this.entry[1] : notSetValue; + }; + + ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + var removed = value === NOT_SET; + var keyMatch = is(key, this.entry[0]); + if (keyMatch ? value === this.entry[1] : removed) { + return this; + } + + SetRef(didAlter); + + if (removed) { + SetRef(didChangeSize); + return; // undefined + } + + if (keyMatch) { + if (ownerID && ownerID === this.ownerID) { + this.entry[1] = value; + return this; + } + return new ValueNode(ownerID, this.keyHash, [key, value]); + } + + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); + }; + + + + // #pragma Iterators + + ArrayMapNode.prototype.iterate = + HashCollisionNode.prototype.iterate = function (fn, reverse) { + var entries = this.entries; + for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { + if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { + return false; + } + } + } + + BitmapIndexedNode.prototype.iterate = + HashArrayMapNode.prototype.iterate = function (fn, reverse) { + var nodes = this.nodes; + for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { + var node = nodes[reverse ? maxIndex - ii : ii]; + if (node && node.iterate(fn, reverse) === false) { + return false; + } + } + } + + ValueNode.prototype.iterate = function (fn, reverse) { + return fn(this.entry); + } + + createClass(MapIterator, Iterator); + + function MapIterator(map, type, reverse) { + this._type = type; + this._reverse = reverse; + this._stack = map._root && mapIteratorFrame(map._root); + } + + MapIterator.prototype.next = function() { + var type = this._type; + var stack = this._stack; + while (stack) { + var node = stack.node; + var index = stack.index++; + var maxIndex; + if (node.entry) { + if (index === 0) { + return mapIteratorValue(type, node.entry); + } + } else if (node.entries) { + maxIndex = node.entries.length - 1; + if (index <= maxIndex) { + return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); + } + } else { + maxIndex = node.nodes.length - 1; + if (index <= maxIndex) { + var subNode = node.nodes[this._reverse ? maxIndex - index : index]; + if (subNode) { + if (subNode.entry) { + return mapIteratorValue(type, subNode.entry); + } + stack = this._stack = mapIteratorFrame(subNode, stack); + } + continue; + } + } + stack = this._stack = this._stack.__prev; + } + return iteratorDone(); + }; + + + function mapIteratorValue(type, entry) { + return iteratorValue(type, entry[0], entry[1]); + } + + function mapIteratorFrame(node, prev) { + return { + node: node, + index: 0, + __prev: prev + }; + } + + function makeMap(size, root, ownerID, hash) { + var map = Object.create(MapPrototype); + map.size = size; + map._root = root; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_MAP; + function emptyMap() { + return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); + } + + function updateMap(map, k, v) { + var newRoot; + var newSize; + if (!map._root) { + if (v === NOT_SET) { + return map; + } + newSize = 1; + newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); + } else { + var didChangeSize = MakeRef(CHANGE_LENGTH); + var didAlter = MakeRef(DID_ALTER); + newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); + if (!didAlter.value) { + return map; + } + newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); + } + if (map.__ownerID) { + map.size = newSize; + map._root = newRoot; + map.__hash = undefined; + map.__altered = true; + return map; + } + return newRoot ? makeMap(newSize, newRoot) : emptyMap(); + } + + function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (!node) { + if (value === NOT_SET) { + return node; + } + SetRef(didAlter); + SetRef(didChangeSize); + return new ValueNode(ownerID, keyHash, [key, value]); + } + return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); + } + + function isLeafNode(node) { + return node.constructor === ValueNode || node.constructor === HashCollisionNode; + } + + function mergeIntoNode(node, ownerID, shift, keyHash, entry) { + if (node.keyHash === keyHash) { + return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); + } + + var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; + var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + + var newNode; + var nodes = idx1 === idx2 ? + [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : + ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); + + return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); + } + + function createNodes(ownerID, entries, key, value) { + if (!ownerID) { + ownerID = new OwnerID(); + } + var node = new ValueNode(ownerID, hash(key), [key, value]); + for (var ii = 0; ii < entries.length; ii++) { + var entry = entries[ii]; + node = node.update(ownerID, 0, undefined, entry[0], entry[1]); + } + return node; + } + + function packNodes(ownerID, nodes, count, excluding) { + var bitmap = 0; + var packedII = 0; + var packedNodes = new Array(count); + for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { + var node = nodes[ii]; + if (node !== undefined && ii !== excluding) { + bitmap |= bit; + packedNodes[packedII++] = node; + } + } + return new BitmapIndexedNode(ownerID, bitmap, packedNodes); + } + + function expandNodes(ownerID, nodes, bitmap, including, node) { + var count = 0; + var expandedNodes = new Array(SIZE); + for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { + expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; + } + expandedNodes[including] = node; + return new HashArrayMapNode(ownerID, count + 1, expandedNodes); + } + + function mergeIntoMapWith(map, merger, iterables) { + var iters = []; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = KeyedIterable(value); + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + return mergeIntoCollectionWith(map, merger, iters); + } + + function deepMerger(existing, value, key) { + return existing && existing.mergeDeep && isIterable(value) ? + existing.mergeDeep(value) : + is(existing, value) ? existing : value; + } + + function deepMergerWith(merger) { + return function(existing, value, key) { + if (existing && existing.mergeDeepWith && isIterable(value)) { + return existing.mergeDeepWith(merger, value); + } + var nextValue = merger(existing, value, key); + return is(existing, nextValue) ? existing : nextValue; + }; + } + + function mergeIntoCollectionWith(collection, merger, iters) { + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return collection; + } + if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { + return collection.constructor(iters[0]); + } + return collection.withMutations(function(collection ) { + var mergeIntoMap = merger ? + function(value, key) { + collection.update(key, NOT_SET, function(existing ) + {return existing === NOT_SET ? value : merger(existing, value, key)} + ); + } : + function(value, key) { + collection.set(key, value); + } + for (var ii = 0; ii < iters.length; ii++) { + iters[ii].forEach(mergeIntoMap); + } + }); + } + + function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { + var isNotSet = existing === NOT_SET; + var step = keyPathIter.next(); + if (step.done) { + var existingValue = isNotSet ? notSetValue : existing; + var newValue = updater(existingValue); + return newValue === existingValue ? existing : newValue; + } + invariant( + isNotSet || (existing && existing.set), + 'invalid keyPath' + ); + var key = step.value; + var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); + var nextUpdated = updateInDeepMap( + nextExisting, + keyPathIter, + notSetValue, + updater + ); + return nextUpdated === nextExisting ? existing : + nextUpdated === NOT_SET ? existing.remove(key) : + (isNotSet ? emptyMap() : existing).set(key, nextUpdated); + } + + function popCount(x) { + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0f0f0f0f; + x = x + (x >> 8); + x = x + (x >> 16); + return x & 0x7f; + } + + function setIn(array, idx, val, canEdit) { + var newArray = canEdit ? array : arrCopy(array); + newArray[idx] = val; + return newArray; + } + + function spliceIn(array, idx, val, canEdit) { + var newLen = array.length + 1; + if (canEdit && idx + 1 === newLen) { + array[idx] = val; + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + newArray[ii] = val; + after = -1; + } else { + newArray[ii] = array[ii + after]; + } + } + return newArray; + } + + function spliceOut(array, idx, canEdit) { + var newLen = array.length - 1; + if (canEdit && idx === newLen) { + array.pop(); + return array; + } + var newArray = new Array(newLen); + var after = 0; + for (var ii = 0; ii < newLen; ii++) { + if (ii === idx) { + after = 1; + } + newArray[ii] = array[ii + after]; + } + return newArray; + } + + var MAX_ARRAY_MAP_SIZE = SIZE / 4; + var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; + var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; + + createClass(List, IndexedCollection); + + // @pragma Construction + + function List(value) { + var empty = emptyList(); + if (value === null || value === undefined) { + return empty; + } + if (isList(value)) { + return value; + } + var iter = IndexedIterable(value); + var size = iter.size; + if (size === 0) { + return empty; + } + assertNotInfinite(size); + if (size > 0 && size < SIZE) { + return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); + } + return empty.withMutations(function(list ) { + list.setSize(size); + iter.forEach(function(v, i) {return list.set(i, v)}); + }); + } + + List.of = function(/*...values*/) { + return this(arguments); + }; + + List.prototype.toString = function() { + return this.__toString('List [', ']'); + }; + + // @pragma Access + + List.prototype.get = function(index, notSetValue) { + index = wrapIndex(this, index); + if (index >= 0 && index < this.size) { + index += this._origin; + var node = listNodeFor(this, index); + return node && node.array[index & MASK]; + } + return notSetValue; + }; + + // @pragma Modification + + List.prototype.set = function(index, value) { + return updateList(this, index, value); + }; + + List.prototype.remove = function(index) { + return !this.has(index) ? this : + index === 0 ? this.shift() : + index === this.size - 1 ? this.pop() : + this.splice(index, 1); + }; + + List.prototype.insert = function(index, value) { + return this.splice(index, 0, value); + }; + + List.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = this._origin = this._capacity = 0; + this._level = SHIFT; + this._root = this._tail = null; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyList(); + }; + + List.prototype.push = function(/*...values*/) { + var values = arguments; + var oldSize = this.size; + return this.withMutations(function(list ) { + setListBounds(list, 0, oldSize + values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(oldSize + ii, values[ii]); + } + }); + }; + + List.prototype.pop = function() { + return setListBounds(this, 0, -1); + }; + + List.prototype.unshift = function(/*...values*/) { + var values = arguments; + return this.withMutations(function(list ) { + setListBounds(list, -values.length); + for (var ii = 0; ii < values.length; ii++) { + list.set(ii, values[ii]); + } + }); + }; + + List.prototype.shift = function() { + return setListBounds(this, 1); + }; + + // @pragma Composition + + List.prototype.merge = function(/*...iters*/) { + return mergeIntoListWith(this, undefined, arguments); + }; + + List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, merger, iters); + }; + + List.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoListWith(this, deepMerger, arguments); + }; + + List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, deepMergerWith(merger), iters); + }; + + List.prototype.setSize = function(size) { + return setListBounds(this, 0, size); + }; + + // @pragma Iteration + + List.prototype.slice = function(begin, end) { + var size = this.size; + if (wholeSlice(begin, end, size)) { + return this; + } + return setListBounds( + this, + resolveBegin(begin, size), + resolveEnd(end, size) + ); + }; + + List.prototype.__iterator = function(type, reverse) { + var index = 0; + var values = iterateList(this, reverse); + return new Iterator(function() { + var value = values(); + return value === DONE ? + iteratorDone() : + iteratorValue(type, index++, value); + }); + }; + + List.prototype.__iterate = function(fn, reverse) { + var index = 0; + var values = iterateList(this, reverse); + var value; + while ((value = values()) !== DONE) { + if (fn(value, index++, this) === false) { + break; + } + } + return index; + }; + + List.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + return this; + } + return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); + }; + + + function isList(maybeList) { + return !!(maybeList && maybeList[IS_LIST_SENTINEL]); + } + + List.isList = isList; + + var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; + + var ListPrototype = List.prototype; + ListPrototype[IS_LIST_SENTINEL] = true; + ListPrototype[DELETE] = ListPrototype.remove; + ListPrototype.setIn = MapPrototype.setIn; + ListPrototype.deleteIn = + ListPrototype.removeIn = MapPrototype.removeIn; + ListPrototype.update = MapPrototype.update; + ListPrototype.updateIn = MapPrototype.updateIn; + ListPrototype.mergeIn = MapPrototype.mergeIn; + ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + ListPrototype.withMutations = MapPrototype.withMutations; + ListPrototype.asMutable = MapPrototype.asMutable; + ListPrototype.asImmutable = MapPrototype.asImmutable; + ListPrototype.wasAltered = MapPrototype.wasAltered; + + + + function VNode(array, ownerID) { + this.array = array; + this.ownerID = ownerID; + } + + // TODO: seems like these methods are very similar + + VNode.prototype.removeBefore = function(ownerID, level, index) { + if (index === level ? 1 << level : 0 || this.array.length === 0) { + return this; + } + var originIndex = (index >>> level) & MASK; + if (originIndex >= this.array.length) { + return new VNode([], ownerID); + } + var removingFirst = originIndex === 0; + var newChild; + if (level > 0) { + var oldChild = this.array[originIndex]; + newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); + if (newChild === oldChild && removingFirst) { + return this; + } + } + if (removingFirst && !newChild) { + return this; + } + var editable = editableVNode(this, ownerID); + if (!removingFirst) { + for (var ii = 0; ii < originIndex; ii++) { + editable.array[ii] = undefined; + } + } + if (newChild) { + editable.array[originIndex] = newChild; + } + return editable; + }; + + VNode.prototype.removeAfter = function(ownerID, level, index) { + if (index === (level ? 1 << level : 0) || this.array.length === 0) { + return this; + } + var sizeIndex = ((index - 1) >>> level) & MASK; + if (sizeIndex >= this.array.length) { + return this; + } + + var newChild; + if (level > 0) { + var oldChild = this.array[sizeIndex]; + newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); + if (newChild === oldChild && sizeIndex === this.array.length - 1) { + return this; + } + } + + var editable = editableVNode(this, ownerID); + editable.array.splice(sizeIndex + 1); + if (newChild) { + editable.array[sizeIndex] = newChild; + } + return editable; + }; + + + + var DONE = {}; + + function iterateList(list, reverse) { + var left = list._origin; + var right = list._capacity; + var tailPos = getTailOffset(right); + var tail = list._tail; + + return iterateNodeOrLeaf(list._root, list._level, 0); + + function iterateNodeOrLeaf(node, level, offset) { + return level === 0 ? + iterateLeaf(node, offset) : + iterateNode(node, level, offset); + } + + function iterateLeaf(node, offset) { + var array = offset === tailPos ? tail && tail.array : node && node.array; + var from = offset > left ? 0 : left - offset; + var to = right - offset; + if (to > SIZE) { + to = SIZE; + } + return function() { + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + return array && array[idx]; + }; + } + + function iterateNode(node, level, offset) { + var values; + var array = node && node.array; + var from = offset > left ? 0 : (left - offset) >> level; + var to = ((right - offset) >> level) + 1; + if (to > SIZE) { + to = SIZE; + } + return function() { + do { + if (values) { + var value = values(); + if (value !== DONE) { + return value; + } + values = null; + } + if (from === to) { + return DONE; + } + var idx = reverse ? --to : from++; + values = iterateNodeOrLeaf( + array && array[idx], level - SHIFT, offset + (idx << level) + ); + } while (true); + }; + } + } + + function makeList(origin, capacity, level, root, tail, ownerID, hash) { + var list = Object.create(ListPrototype); + list.size = capacity - origin; + list._origin = origin; + list._capacity = capacity; + list._level = level; + list._root = root; + list._tail = tail; + list.__ownerID = ownerID; + list.__hash = hash; + list.__altered = false; + return list; + } + + var EMPTY_LIST; + function emptyList() { + return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); + } + + function updateList(list, index, value) { + index = wrapIndex(list, index); + + if (index !== index) { + return list; + } + + if (index >= list.size || index < 0) { + return list.withMutations(function(list ) { + index < 0 ? + setListBounds(list, index).set(0, value) : + setListBounds(list, 0, index + 1).set(index, value) + }); + } + + index += list._origin; + + var newTail = list._tail; + var newRoot = list._root; + var didAlter = MakeRef(DID_ALTER); + if (index >= getTailOffset(list._capacity)) { + newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); + } else { + newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); + } + + if (!didAlter.value) { + return list; + } + + if (list.__ownerID) { + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(list._origin, list._capacity, list._level, newRoot, newTail); + } + + function updateVNode(node, ownerID, level, index, value, didAlter) { + var idx = (index >>> level) & MASK; + var nodeHas = node && idx < node.array.length; + if (!nodeHas && value === undefined) { + return node; + } + + var newNode; + + if (level > 0) { + var lowerNode = node && node.array[idx]; + var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); + if (newLowerNode === lowerNode) { + return node; + } + newNode = editableVNode(node, ownerID); + newNode.array[idx] = newLowerNode; + return newNode; + } + + if (nodeHas && node.array[idx] === value) { + return node; + } + + SetRef(didAlter); + + newNode = editableVNode(node, ownerID); + if (value === undefined && idx === newNode.array.length - 1) { + newNode.array.pop(); + } else { + newNode.array[idx] = value; + } + return newNode; + } + + function editableVNode(node, ownerID) { + if (ownerID && node && ownerID === node.ownerID) { + return node; + } + return new VNode(node ? node.array.slice() : [], ownerID); + } + + function listNodeFor(list, rawIndex) { + if (rawIndex >= getTailOffset(list._capacity)) { + return list._tail; + } + if (rawIndex < 1 << (list._level + SHIFT)) { + var node = list._root; + var level = list._level; + while (node && level > 0) { + node = node.array[(rawIndex >>> level) & MASK]; + level -= SHIFT; + } + return node; + } + } + + function setListBounds(list, begin, end) { + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + var owner = list.__ownerID || new OwnerID(); + var oldOrigin = list._origin; + var oldCapacity = list._capacity; + var newOrigin = oldOrigin + begin; + var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; + if (newOrigin === oldOrigin && newCapacity === oldCapacity) { + return list; + } + + // If it's going to end after it starts, it's empty. + if (newOrigin >= newCapacity) { + return list.clear(); + } + + var newLevel = list._level; + var newRoot = list._root; + + // New origin might need creating a higher root. + var offsetShift = 0; + while (newOrigin + offsetShift < 0) { + newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); + newLevel += SHIFT; + offsetShift += 1 << newLevel; + } + if (offsetShift) { + newOrigin += offsetShift; + oldOrigin += offsetShift; + newCapacity += offsetShift; + oldCapacity += offsetShift; + } + + var oldTailOffset = getTailOffset(oldCapacity); + var newTailOffset = getTailOffset(newCapacity); + + // New size might need creating a higher root. + while (newTailOffset >= 1 << (newLevel + SHIFT)) { + newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); + newLevel += SHIFT; + } + + // Locate or create the new tail. + var oldTail = list._tail; + var newTail = newTailOffset < oldTailOffset ? + listNodeFor(list, newCapacity - 1) : + newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; + + // Merge Tail into tree. + if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { + newRoot = editableVNode(newRoot, owner); + var node = newRoot; + for (var level = newLevel; level > SHIFT; level -= SHIFT) { + var idx = (oldTailOffset >>> level) & MASK; + node = node.array[idx] = editableVNode(node.array[idx], owner); + } + node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; + } + + // If the size has been reduced, there's a chance the tail needs to be trimmed. + if (newCapacity < oldCapacity) { + newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); + } + + // If the new origin is within the tail, then we do not need a root. + if (newOrigin >= newTailOffset) { + newOrigin -= newTailOffset; + newCapacity -= newTailOffset; + newLevel = SHIFT; + newRoot = null; + newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); + + // Otherwise, if the root has been trimmed, garbage collect. + } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { + offsetShift = 0; + + // Identify the new top root node of the subtree of the old root. + while (newRoot) { + var beginIndex = (newOrigin >>> newLevel) & MASK; + if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { + break; + } + if (beginIndex) { + offsetShift += (1 << newLevel) * beginIndex; + } + newLevel -= SHIFT; + newRoot = newRoot.array[beginIndex]; + } + + // Trim the new sides of the new root. + if (newRoot && newOrigin > oldOrigin) { + newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); + } + if (newRoot && newTailOffset < oldTailOffset) { + newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); + } + if (offsetShift) { + newOrigin -= offsetShift; + newCapacity -= offsetShift; + } + } + + if (list.__ownerID) { + list.size = newCapacity - newOrigin; + list._origin = newOrigin; + list._capacity = newCapacity; + list._level = newLevel; + list._root = newRoot; + list._tail = newTail; + list.__hash = undefined; + list.__altered = true; + return list; + } + return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); + } + + function mergeIntoListWith(list, merger, iterables) { + var iters = []; + var maxSize = 0; + for (var ii = 0; ii < iterables.length; ii++) { + var value = iterables[ii]; + var iter = IndexedIterable(value); + if (iter.size > maxSize) { + maxSize = iter.size; + } + if (!isIterable(value)) { + iter = iter.map(function(v ) {return fromJS(v)}); + } + iters.push(iter); + } + if (maxSize > list.size) { + list = list.setSize(maxSize); + } + return mergeIntoCollectionWith(list, merger, iters); + } + + function getTailOffset(size) { + return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); + } + + createClass(OrderedMap, Map); + + // @pragma Construction + + function OrderedMap(value) { + return value === null || value === undefined ? emptyOrderedMap() : + isOrderedMap(value) ? value : + emptyOrderedMap().withMutations(function(map ) { + var iter = KeyedIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v, k) {return map.set(k, v)}); + }); + } + + OrderedMap.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedMap.prototype.toString = function() { + return this.__toString('OrderedMap {', '}'); + }; + + // @pragma Access + + OrderedMap.prototype.get = function(k, notSetValue) { + var index = this._map.get(k); + return index !== undefined ? this._list.get(index)[1] : notSetValue; + }; + + // @pragma Modification + + OrderedMap.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._map.clear(); + this._list.clear(); + return this; + } + return emptyOrderedMap(); + }; + + OrderedMap.prototype.set = function(k, v) { + return updateOrderedMap(this, k, v); + }; + + OrderedMap.prototype.remove = function(k) { + return updateOrderedMap(this, k, NOT_SET); + }; + + OrderedMap.prototype.wasAltered = function() { + return this._map.wasAltered() || this._list.wasAltered(); + }; + + OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._list.__iterate( + function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, + reverse + ); + }; + + OrderedMap.prototype.__iterator = function(type, reverse) { + return this._list.fromEntrySeq().__iterator(type, reverse); + }; + + OrderedMap.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + var newList = this._list.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + this._list = newList; + return this; + } + return makeOrderedMap(newMap, newList, ownerID, this.__hash); + }; + + + function isOrderedMap(maybeOrderedMap) { + return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); + } + + OrderedMap.isOrderedMap = isOrderedMap; + + OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; + OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; + + + + function makeOrderedMap(map, list, ownerID, hash) { + var omap = Object.create(OrderedMap.prototype); + omap.size = map ? map.size : 0; + omap._map = map; + omap._list = list; + omap.__ownerID = ownerID; + omap.__hash = hash; + return omap; + } + + var EMPTY_ORDERED_MAP; + function emptyOrderedMap() { + return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); + } + + function updateOrderedMap(omap, k, v) { + var map = omap._map; + var list = omap._list; + var i = map.get(k); + var has = i !== undefined; + var newMap; + var newList; + if (v === NOT_SET) { // removed + if (!has) { + return omap; + } + if (list.size >= SIZE && list.size >= map.size * 2) { + newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); + newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); + if (omap.__ownerID) { + newMap.__ownerID = newList.__ownerID = omap.__ownerID; + } + } else { + newMap = map.remove(k); + newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); + } + } else { + if (has) { + if (v === list.get(i)[1]) { + return omap; + } + newMap = map; + newList = list.set(i, [k, v]); + } else { + newMap = map.set(k, list.size); + newList = list.set(list.size, [k, v]); + } + } + if (omap.__ownerID) { + omap.size = newMap.size; + omap._map = newMap; + omap._list = newList; + omap.__hash = undefined; + return omap; + } + return makeOrderedMap(newMap, newList); + } + + createClass(ToKeyedSequence, KeyedSeq); + function ToKeyedSequence(indexed, useKeys) { + this._iter = indexed; + this._useKeys = useKeys; + this.size = indexed.size; + } + + ToKeyedSequence.prototype.get = function(key, notSetValue) { + return this._iter.get(key, notSetValue); + }; + + ToKeyedSequence.prototype.has = function(key) { + return this._iter.has(key); + }; + + ToKeyedSequence.prototype.valueSeq = function() { + return this._iter.valueSeq(); + }; + + ToKeyedSequence.prototype.reverse = function() {var this$0 = this; + var reversedSequence = reverseFactory(this, true); + if (!this._useKeys) { + reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; + } + return reversedSequence; + }; + + ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; + var mappedSequence = mapFactory(this, mapper, context); + if (!this._useKeys) { + mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; + } + return mappedSequence; + }; + + ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var ii; + return this._iter.__iterate( + this._useKeys ? + function(v, k) {return fn(v, k, this$0)} : + ((ii = reverse ? resolveSize(this) : 0), + function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), + reverse + ); + }; + + ToKeyedSequence.prototype.__iterator = function(type, reverse) { + if (this._useKeys) { + return this._iter.__iterator(type, reverse); + } + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var ii = reverse ? resolveSize(this) : 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, reverse ? --ii : ii++, step.value, step); + }); + }; + + ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; + + + createClass(ToIndexedSequence, IndexedSeq); + function ToIndexedSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToIndexedSequence.prototype.includes = function(value) { + return this._iter.includes(value); + }; + + ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + var iterations = 0; + return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); + }; + + ToIndexedSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, iterations++, step.value, step) + }); + }; + + + + createClass(ToSetSequence, SetSeq); + function ToSetSequence(iter) { + this._iter = iter; + this.size = iter.size; + } + + ToSetSequence.prototype.has = function(key) { + return this._iter.includes(key); + }; + + ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); + }; + + ToSetSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + var step = iterator.next(); + return step.done ? step : + iteratorValue(type, step.value, step.value, step); + }); + }; + + + + createClass(FromEntriesSequence, KeyedSeq); + function FromEntriesSequence(entries) { + this._iter = entries; + this.size = entries.size; + } + + FromEntriesSequence.prototype.entrySeq = function() { + return this._iter.toSeq(); + }; + + FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(entry ) { + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return fn( + indexedIterable ? entry.get(1) : entry[1], + indexedIterable ? entry.get(0) : entry[0], + this$0 + ); + } + }, reverse); + }; + + FromEntriesSequence.prototype.__iterator = function(type, reverse) { + var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + // Check if entry exists first so array access doesn't throw for holes + // in the parent iteration. + if (entry) { + validateEntry(entry); + var indexedIterable = isIterable(entry); + return iteratorValue( + type, + indexedIterable ? entry.get(0) : entry[0], + indexedIterable ? entry.get(1) : entry[1], + step + ); + } + } + }); + }; + + + ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough; + + + function flipFactory(iterable) { + var flipSequence = makeSequence(iterable); + flipSequence._iter = iterable; + flipSequence.size = iterable.size; + flipSequence.flip = function() {return iterable}; + flipSequence.reverse = function () { + var reversedSequence = iterable.reverse.apply(this); // super.reverse() + reversedSequence.flip = function() {return iterable.reverse()}; + return reversedSequence; + }; + flipSequence.has = function(key ) {return iterable.includes(key)}; + flipSequence.includes = function(key ) {return iterable.has(key)}; + flipSequence.cacheResult = cacheResultThrough; + flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); + } + flipSequence.__iteratorUncached = function(type, reverse) { + if (type === ITERATE_ENTRIES) { + var iterator = iterable.__iterator(type, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (!step.done) { + var k = step.value[0]; + step.value[0] = step.value[1]; + step.value[1] = k; + } + return step; + }); + } + return iterable.__iterator( + type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, + reverse + ); + } + return flipSequence; + } + + + function mapFactory(iterable, mapper, context) { + var mappedSequence = makeSequence(iterable); + mappedSequence.size = iterable.size; + mappedSequence.has = function(key ) {return iterable.has(key)}; + mappedSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v === NOT_SET ? + notSetValue : + mapper.call(context, v, key, iterable); + }; + mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + return iterable.__iterate( + function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, + reverse + ); + } + mappedSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + return new Iterator(function() { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + return iteratorValue( + type, + key, + mapper.call(context, entry[1], key, iterable), + step + ); + }); + } + return mappedSequence; + } + + + function reverseFactory(iterable, useKeys) { + var reversedSequence = makeSequence(iterable); + reversedSequence._iter = iterable; + reversedSequence.size = iterable.size; + reversedSequence.reverse = function() {return iterable}; + if (iterable.flip) { + reversedSequence.flip = function () { + var flipSequence = flipFactory(iterable); + flipSequence.reverse = function() {return iterable.flip()}; + return flipSequence; + }; + } + reversedSequence.get = function(key, notSetValue) + {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; + reversedSequence.has = function(key ) + {return iterable.has(useKeys ? key : -1 - key)}; + reversedSequence.includes = function(value ) {return iterable.includes(value)}; + reversedSequence.cacheResult = cacheResultThrough; + reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; + return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); + }; + reversedSequence.__iterator = + function(type, reverse) {return iterable.__iterator(type, !reverse)}; + return reversedSequence; + } + + + function filterFactory(iterable, predicate, context, useKeys) { + var filterSequence = makeSequence(iterable); + if (useKeys) { + filterSequence.has = function(key ) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && !!predicate.call(context, v, key, iterable); + }; + filterSequence.get = function(key, notSetValue) { + var v = iterable.get(key, NOT_SET); + return v !== NOT_SET && predicate.call(context, v, key, iterable) ? + v : notSetValue; + }; + } + filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }, reverse); + return iterations; + }; + filterSequence.__iteratorUncached = function (type, reverse) { + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterations = 0; + return new Iterator(function() { + while (true) { + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var key = entry[0]; + var value = entry[1]; + if (predicate.call(context, value, key, iterable)) { + return iteratorValue(type, useKeys ? key : iterations++, value, step); + } + } + }); + } + return filterSequence; + } + + + function countByFactory(iterable, grouper, context) { + var groups = Map().asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + 0, + function(a ) {return a + 1} + ); + }); + return groups.asImmutable(); + } + + + function groupByFactory(iterable, grouper, context) { + var isKeyedIter = isKeyed(iterable); + var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); + iterable.__iterate(function(v, k) { + groups.update( + grouper.call(context, v, k, iterable), + function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} + ); + }); + var coerce = iterableClass(iterable); + return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); + } + + + function sliceFactory(iterable, begin, end, useKeys) { + var originalSize = iterable.size; + + // Sanitize begin & end using this shorthand for ToInt32(argument) + // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 + if (begin !== undefined) { + begin = begin | 0; + } + if (end !== undefined) { + end = end | 0; + } + + if (wholeSlice(begin, end, originalSize)) { + return iterable; + } + + var resolvedBegin = resolveBegin(begin, originalSize); + var resolvedEnd = resolveEnd(end, originalSize); + + // begin or end will be NaN if they were provided as negative numbers and + // this iterable's size is unknown. In that case, cache first so there is + // a known size and these do not resolve to NaN. + if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { + return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); + } + + // Note: resolvedEnd is undefined when the original sequence's length is + // unknown and this slice did not supply an end and should contain all + // elements after resolvedBegin. + // In that case, resolvedSize will be NaN and sliceSize will remain undefined. + var resolvedSize = resolvedEnd - resolvedBegin; + var sliceSize; + if (resolvedSize === resolvedSize) { + sliceSize = resolvedSize < 0 ? 0 : resolvedSize; + } + + var sliceSeq = makeSequence(iterable); + + // If iterable.size is undefined, the size of the realized sliceSeq is + // unknown at this point unless the number of items to slice is 0 + sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; + + if (!useKeys && isSeq(iterable) && sliceSize >= 0) { + sliceSeq.get = function (index, notSetValue) { + index = wrapIndex(this, index); + return index >= 0 && index < sliceSize ? + iterable.get(index + resolvedBegin, notSetValue) : + notSetValue; + } + } + + sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (sliceSize === 0) { + return 0; + } + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var skipped = 0; + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k) { + if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0) !== false && + iterations !== sliceSize; + } + }); + return iterations; + }; + + sliceSeq.__iteratorUncached = function(type, reverse) { + if (sliceSize !== 0 && reverse) { + return this.cacheResult().__iterator(type, reverse); + } + // Don't bother instantiating parent iterator if taking 0. + var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); + var skipped = 0; + var iterations = 0; + return new Iterator(function() { + while (skipped++ < resolvedBegin) { + iterator.next(); + } + if (++iterations > sliceSize) { + return iteratorDone(); + } + var step = iterator.next(); + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations - 1, undefined, step); + } else { + return iteratorValue(type, iterations - 1, step.value[1], step); + } + }); + } + + return sliceSeq; + } + + + function takeWhileFactory(iterable, predicate, context) { + var takeSequence = makeSequence(iterable); + takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var iterations = 0; + iterable.__iterate(function(v, k, c) + {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} + ); + return iterations; + }; + takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var iterating = true; + return new Iterator(function() { + if (!iterating) { + return iteratorDone(); + } + var step = iterator.next(); + if (step.done) { + return step; + } + var entry = step.value; + var k = entry[0]; + var v = entry[1]; + if (!predicate.call(context, v, k, this$0)) { + iterating = false; + return iteratorDone(); + } + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return takeSequence; + } + + + function skipWhileFactory(iterable, predicate, context, useKeys) { + var skipSequence = makeSequence(iterable); + skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterate(fn, reverse); + } + var isSkipping = true; + var iterations = 0; + iterable.__iterate(function(v, k, c) { + if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { + iterations++; + return fn(v, useKeys ? k : iterations - 1, this$0); + } + }); + return iterations; + }; + skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; + if (reverse) { + return this.cacheResult().__iterator(type, reverse); + } + var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); + var skipping = true; + var iterations = 0; + return new Iterator(function() { + var step, k, v; + do { + step = iterator.next(); + if (step.done) { + if (useKeys || type === ITERATE_VALUES) { + return step; + } else if (type === ITERATE_KEYS) { + return iteratorValue(type, iterations++, undefined, step); + } else { + return iteratorValue(type, iterations++, step.value[1], step); + } + } + var entry = step.value; + k = entry[0]; + v = entry[1]; + skipping && (skipping = predicate.call(context, v, k, this$0)); + } while (skipping); + return type === ITERATE_ENTRIES ? step : + iteratorValue(type, k, v, step); + }); + }; + return skipSequence; + } + + + function concatFactory(iterable, values) { + var isKeyedIterable = isKeyed(iterable); + var iters = [iterable].concat(values).map(function(v ) { + if (!isIterable(v)) { + v = isKeyedIterable ? + keyedSeqFromValue(v) : + indexedSeqFromValue(Array.isArray(v) ? v : [v]); + } else if (isKeyedIterable) { + v = KeyedIterable(v); + } + return v; + }).filter(function(v ) {return v.size !== 0}); + + if (iters.length === 0) { + return iterable; + } + + if (iters.length === 1) { + var singleton = iters[0]; + if (singleton === iterable || + isKeyedIterable && isKeyed(singleton) || + isIndexed(iterable) && isIndexed(singleton)) { + return singleton; + } + } + + var concatSeq = new ArraySeq(iters); + if (isKeyedIterable) { + concatSeq = concatSeq.toKeyedSeq(); + } else if (!isIndexed(iterable)) { + concatSeq = concatSeq.toSetSeq(); + } + concatSeq = concatSeq.flatten(true); + concatSeq.size = iters.reduce( + function(sum, seq) { + if (sum !== undefined) { + var size = seq.size; + if (size !== undefined) { + return sum + size; + } + } + }, + 0 + ); + return concatSeq; + } + + + function flattenFactory(iterable, depth, useKeys) { + var flatSequence = makeSequence(iterable); + flatSequence.__iterateUncached = function(fn, reverse) { + var iterations = 0; + var stopped = false; + function flatDeep(iter, currentDepth) {var this$0 = this; + iter.__iterate(function(v, k) { + if ((!depth || currentDepth < depth) && isIterable(v)) { + flatDeep(v, currentDepth + 1); + } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { + stopped = true; + } + return !stopped; + }, reverse); + } + flatDeep(iterable, 0); + return iterations; + } + flatSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(type, reverse); + var stack = []; + var iterations = 0; + return new Iterator(function() { + while (iterator) { + var step = iterator.next(); + if (step.done !== false) { + iterator = stack.pop(); + continue; + } + var v = step.value; + if (type === ITERATE_ENTRIES) { + v = v[1]; + } + if ((!depth || stack.length < depth) && isIterable(v)) { + stack.push(iterator); + iterator = v.__iterator(type, reverse); + } else { + return useKeys ? step : iteratorValue(type, iterations++, v, step); + } + } + return iteratorDone(); + }); + } + return flatSequence; + } + + + function flatMapFactory(iterable, mapper, context) { + var coerce = iterableClass(iterable); + return iterable.toSeq().map( + function(v, k) {return coerce(mapper.call(context, v, k, iterable))} + ).flatten(true); + } + + + function interposeFactory(iterable, separator) { + var interposedSequence = makeSequence(iterable); + interposedSequence.size = iterable.size && iterable.size * 2 -1; + interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; + var iterations = 0; + iterable.__iterate(function(v, k) + {return (!iterations || fn(separator, iterations++, this$0) !== false) && + fn(v, iterations++, this$0) !== false}, + reverse + ); + return iterations; + }; + interposedSequence.__iteratorUncached = function(type, reverse) { + var iterator = iterable.__iterator(ITERATE_VALUES, reverse); + var iterations = 0; + var step; + return new Iterator(function() { + if (!step || iterations % 2) { + step = iterator.next(); + if (step.done) { + return step; + } + } + return iterations % 2 ? + iteratorValue(type, iterations++, separator) : + iteratorValue(type, iterations++, step.value, step); + }); + }; + return interposedSequence; + } + + + function sortFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + var isKeyedIterable = isKeyed(iterable); + var index = 0; + var entries = iterable.toSeq().map( + function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} + ).toArray(); + entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( + isKeyedIterable ? + function(v, i) { entries[i].length = 2; } : + function(v, i) { entries[i] = v[1]; } + ); + return isKeyedIterable ? KeyedSeq(entries) : + isIndexed(iterable) ? IndexedSeq(entries) : + SetSeq(entries); + } + + + function maxFactory(iterable, comparator, mapper) { + if (!comparator) { + comparator = defaultComparator; + } + if (mapper) { + var entry = iterable.toSeq() + .map(function(v, k) {return [v, mapper(v, k, iterable)]}) + .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); + return entry && entry[0]; + } else { + return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); + } + } + + function maxCompare(comparator, a, b) { + var comp = comparator(b, a); + // b is considered the new max if the comparator declares them equal, but + // they are not equal and b is in fact a nullish value. + return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; + } + + + function zipWithFactory(keyIter, zipper, iters) { + var zipSequence = makeSequence(keyIter); + zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); + // Note: this a generic base implementation of __iterate in terms of + // __iterator which may be more generically useful in the future. + zipSequence.__iterate = function(fn, reverse) { + /* generic: + var iterator = this.__iterator(ITERATE_ENTRIES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + iterations++; + if (fn(step.value[1], step.value[0], this) === false) { + break; + } + } + return iterations; + */ + // indexed: + var iterator = this.__iterator(ITERATE_VALUES, reverse); + var step; + var iterations = 0; + while (!(step = iterator.next()).done) { + if (fn(step.value, iterations++, this) === false) { + break; + } + } + return iterations; + }; + zipSequence.__iteratorUncached = function(type, reverse) { + var iterators = iters.map(function(i ) + {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} + ); + var iterations = 0; + var isDone = false; + return new Iterator(function() { + var steps; + if (!isDone) { + steps = iterators.map(function(i ) {return i.next()}); + isDone = steps.some(function(s ) {return s.done}); + } + if (isDone) { + return iteratorDone(); + } + return iteratorValue( + type, + iterations++, + zipper.apply(null, steps.map(function(s ) {return s.value})) + ); + }); + }; + return zipSequence + } + + + // #pragma Helper Functions + + function reify(iter, seq) { + return isSeq(iter) ? seq : iter.constructor(seq); + } + + function validateEntry(entry) { + if (entry !== Object(entry)) { + throw new TypeError('Expected [K, V] tuple: ' + entry); + } + } + + function resolveSize(iter) { + assertNotInfinite(iter.size); + return ensureSize(iter); + } + + function iterableClass(iterable) { + return isKeyed(iterable) ? KeyedIterable : + isIndexed(iterable) ? IndexedIterable : + SetIterable; + } + + function makeSequence(iterable) { + return Object.create( + ( + isKeyed(iterable) ? KeyedSeq : + isIndexed(iterable) ? IndexedSeq : + SetSeq + ).prototype + ); + } + + function cacheResultThrough() { + if (this._iter.cacheResult) { + this._iter.cacheResult(); + this.size = this._iter.size; + return this; + } else { + return Seq.prototype.cacheResult.call(this); + } + } + + function defaultComparator(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + } + + function forceIterator(keyPath) { + var iter = getIterator(keyPath); + if (!iter) { + // Array might not be iterable in this environment, so we need a fallback + // to our wrapped type. + if (!isArrayLike(keyPath)) { + throw new TypeError('Expected iterable or array-like: ' + keyPath); + } + iter = getIterator(Iterable(keyPath)); + } + return iter; + } + + createClass(Record, KeyedCollection); + + function Record(defaultValues, name) { + var hasInitialized; + + var RecordType = function Record(values) { + if (values instanceof RecordType) { + return values; + } + if (!(this instanceof RecordType)) { + return new RecordType(values); + } + if (!hasInitialized) { + hasInitialized = true; + var keys = Object.keys(defaultValues); + setProps(RecordTypePrototype, keys); + RecordTypePrototype.size = keys.length; + RecordTypePrototype._name = name; + RecordTypePrototype._keys = keys; + RecordTypePrototype._defaultValues = defaultValues; + } + this._map = Map(values); + }; + + var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); + RecordTypePrototype.constructor = RecordType; + + return RecordType; + } + + Record.prototype.toString = function() { + return this.__toString(recordName(this) + ' {', '}'); + }; + + // @pragma Access + + Record.prototype.has = function(k) { + return this._defaultValues.hasOwnProperty(k); + }; + + Record.prototype.get = function(k, notSetValue) { + if (!this.has(k)) { + return notSetValue; + } + var defaultVal = this._defaultValues[k]; + return this._map ? this._map.get(k, defaultVal) : defaultVal; + }; + + // @pragma Modification + + Record.prototype.clear = function() { + if (this.__ownerID) { + this._map && this._map.clear(); + return this; + } + var RecordType = this.constructor; + return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); + }; + + Record.prototype.set = function(k, v) { + if (!this.has(k)) { + throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); + } + var newMap = this._map && this._map.set(k, v); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.remove = function(k) { + if (!this.has(k)) { + return this; + } + var newMap = this._map && this._map.remove(k); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; + + Record.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Record.prototype.__iterator = function(type, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); + }; + + Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); + }; + + Record.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map && this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return makeRecord(this, newMap, ownerID); + }; + + + var RecordPrototype = Record.prototype; + RecordPrototype[DELETE] = RecordPrototype.remove; + RecordPrototype.deleteIn = + RecordPrototype.removeIn = MapPrototype.removeIn; + RecordPrototype.merge = MapPrototype.merge; + RecordPrototype.mergeWith = MapPrototype.mergeWith; + RecordPrototype.mergeIn = MapPrototype.mergeIn; + RecordPrototype.mergeDeep = MapPrototype.mergeDeep; + RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; + RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; + RecordPrototype.setIn = MapPrototype.setIn; + RecordPrototype.update = MapPrototype.update; + RecordPrototype.updateIn = MapPrototype.updateIn; + RecordPrototype.withMutations = MapPrototype.withMutations; + RecordPrototype.asMutable = MapPrototype.asMutable; + RecordPrototype.asImmutable = MapPrototype.asImmutable; + + + function makeRecord(likeRecord, map, ownerID) { + var record = Object.create(Object.getPrototypeOf(likeRecord)); + record._map = map; + record.__ownerID = ownerID; + return record; + } + + function recordName(record) { + return record._name || record.constructor.name || 'Record'; + } + + function setProps(prototype, names) { + try { + names.forEach(setProp.bind(undefined, prototype)); + } catch (error) { + // Object.defineProperty failed. Probably IE8. + } + } + + function setProp(prototype, name) { + Object.defineProperty(prototype, name, { + get: function() { + return this.get(name); + }, + set: function(value) { + invariant(this.__ownerID, 'Cannot set on an immutable record.'); + this.set(name, value); + } + }); + } + + createClass(Set, SetCollection); + + // @pragma Construction + + function Set(value) { + return value === null || value === undefined ? emptySet() : + isSet(value) && !isOrdered(value) ? value : + emptySet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + Set.of = function(/*...values*/) { + return this(arguments); + }; + + Set.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + Set.prototype.toString = function() { + return this.__toString('Set {', '}'); + }; + + // @pragma Access + + Set.prototype.has = function(value) { + return this._map.has(value); + }; + + // @pragma Modification + + Set.prototype.add = function(value) { + return updateSet(this, this._map.set(value, true)); + }; + + Set.prototype.remove = function(value) { + return updateSet(this, this._map.remove(value)); + }; + + Set.prototype.clear = function() { + return updateSet(this, this._map.clear()); + }; + + // @pragma Composition + + Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); + iters = iters.filter(function(x ) {return x.size !== 0}); + if (iters.length === 0) { + return this; + } + if (this.size === 0 && !this.__ownerID && iters.length === 1) { + return this.constructor(iters[0]); + } + return this.withMutations(function(set ) { + for (var ii = 0; ii < iters.length; ii++) { + SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); + } + }); + }; + + Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (!iters.every(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); + if (iters.length === 0) { + return this; + } + iters = iters.map(function(iter ) {return SetIterable(iter)}); + var originalSet = this; + return this.withMutations(function(set ) { + originalSet.forEach(function(value ) { + if (iters.some(function(iter ) {return iter.includes(value)})) { + set.remove(value); + } + }); + }); + }; + + Set.prototype.merge = function() { + return this.union.apply(this, arguments); + }; + + Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return this.union.apply(this, iters); + }; + + Set.prototype.sort = function(comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator)); + }; + + Set.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator, mapper)); + }; + + Set.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; + + Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); + }; + + Set.prototype.__iterator = function(type, reverse) { + return this._map.map(function(_, k) {return k}).__iterator(type, reverse); + }; + + Set.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + var newMap = this._map.__ensureOwner(ownerID); + if (!ownerID) { + this.__ownerID = ownerID; + this._map = newMap; + return this; + } + return this.__make(newMap, ownerID); + }; + + + function isSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); + } + + Set.isSet = isSet; + + var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; + + var SetPrototype = Set.prototype; + SetPrototype[IS_SET_SENTINEL] = true; + SetPrototype[DELETE] = SetPrototype.remove; + SetPrototype.mergeDeep = SetPrototype.merge; + SetPrototype.mergeDeepWith = SetPrototype.mergeWith; + SetPrototype.withMutations = MapPrototype.withMutations; + SetPrototype.asMutable = MapPrototype.asMutable; + SetPrototype.asImmutable = MapPrototype.asImmutable; + + SetPrototype.__empty = emptySet; + SetPrototype.__make = makeSet; + + function updateSet(set, newMap) { + if (set.__ownerID) { + set.size = newMap.size; + set._map = newMap; + return set; + } + return newMap === set._map ? set : + newMap.size === 0 ? set.__empty() : + set.__make(newMap); + } + + function makeSet(map, ownerID) { + var set = Object.create(SetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_SET; + function emptySet() { + return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); + } + + createClass(OrderedSet, Set); + + // @pragma Construction + + function OrderedSet(value) { + return value === null || value === undefined ? emptyOrderedSet() : + isOrderedSet(value) ? value : + emptyOrderedSet().withMutations(function(set ) { + var iter = SetIterable(value); + assertNotInfinite(iter.size); + iter.forEach(function(v ) {return set.add(v)}); + }); + } + + OrderedSet.of = function(/*...values*/) { + return this(arguments); + }; + + OrderedSet.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; + + OrderedSet.prototype.toString = function() { + return this.__toString('OrderedSet {', '}'); + }; + + + function isOrderedSet(maybeOrderedSet) { + return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); + } + + OrderedSet.isOrderedSet = isOrderedSet; + + var OrderedSetPrototype = OrderedSet.prototype; + OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; + + OrderedSetPrototype.__empty = emptyOrderedSet; + OrderedSetPrototype.__make = makeOrderedSet; + + function makeOrderedSet(map, ownerID) { + var set = Object.create(OrderedSetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } + + var EMPTY_ORDERED_SET; + function emptyOrderedSet() { + return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); + } + + createClass(Stack, IndexedCollection); + + // @pragma Construction + + function Stack(value) { + return value === null || value === undefined ? emptyStack() : + isStack(value) ? value : + emptyStack().unshiftAll(value); + } + + Stack.of = function(/*...values*/) { + return this(arguments); + }; + + Stack.prototype.toString = function() { + return this.__toString('Stack [', ']'); + }; + + // @pragma Access + + Stack.prototype.get = function(index, notSetValue) { + var head = this._head; + index = wrapIndex(this, index); + while (head && index--) { + head = head.next; + } + return head ? head.value : notSetValue; + }; + + Stack.prototype.peek = function() { + return this._head && this._head.value; + }; + + // @pragma Modification + + Stack.prototype.push = function(/*...values*/) { + if (arguments.length === 0) { + return this; + } + var newSize = this.size + arguments.length; + var head = this._head; + for (var ii = arguments.length - 1; ii >= 0; ii--) { + head = { + value: arguments[ii], + next: head + }; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pushAll = function(iter) { + iter = IndexedIterable(iter); + if (iter.size === 0) { + return this; + } + assertNotInfinite(iter.size); + var newSize = this.size; + var head = this._head; + iter.reverse().forEach(function(value ) { + newSize++; + head = { + value: value, + next: head + }; + }); + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + Stack.prototype.pop = function() { + return this.slice(1); + }; + + Stack.prototype.unshift = function(/*...values*/) { + return this.push.apply(this, arguments); + }; + + Stack.prototype.unshiftAll = function(iter) { + return this.pushAll(iter); + }; + + Stack.prototype.shift = function() { + return this.pop.apply(this, arguments); + }; + + Stack.prototype.clear = function() { + if (this.size === 0) { + return this; + } + if (this.__ownerID) { + this.size = 0; + this._head = undefined; + this.__hash = undefined; + this.__altered = true; + return this; + } + return emptyStack(); + }; + + Stack.prototype.slice = function(begin, end) { + if (wholeSlice(begin, end, this.size)) { + return this; + } + var resolvedBegin = resolveBegin(begin, this.size); + var resolvedEnd = resolveEnd(end, this.size); + if (resolvedEnd !== this.size) { + // super.slice(begin, end); + return IndexedCollection.prototype.slice.call(this, begin, end); + } + var newSize = this.size - resolvedBegin; + var head = this._head; + while (resolvedBegin--) { + head = head.next; + } + if (this.__ownerID) { + this.size = newSize; + this._head = head; + this.__hash = undefined; + this.__altered = true; + return this; + } + return makeStack(newSize, head); + }; + + // @pragma Mutability + + Stack.prototype.__ensureOwner = function(ownerID) { + if (ownerID === this.__ownerID) { + return this; + } + if (!ownerID) { + this.__ownerID = ownerID; + this.__altered = false; + return this; + } + return makeStack(this.size, this._head, ownerID, this.__hash); + }; + + // @pragma Iteration + + Stack.prototype.__iterate = function(fn, reverse) { + if (reverse) { + return this.reverse().__iterate(fn); + } + var iterations = 0; + var node = this._head; + while (node) { + if (fn(node.value, iterations++, this) === false) { + break; + } + node = node.next; + } + return iterations; + }; + + Stack.prototype.__iterator = function(type, reverse) { + if (reverse) { + return this.reverse().__iterator(type); + } + var iterations = 0; + var node = this._head; + return new Iterator(function() { + if (node) { + var value = node.value; + node = node.next; + return iteratorValue(type, iterations++, value); + } + return iteratorDone(); + }); + }; + + + function isStack(maybeStack) { + return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); + } + + Stack.isStack = isStack; + + var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + + var StackPrototype = Stack.prototype; + StackPrototype[IS_STACK_SENTINEL] = true; + StackPrototype.withMutations = MapPrototype.withMutations; + StackPrototype.asMutable = MapPrototype.asMutable; + StackPrototype.asImmutable = MapPrototype.asImmutable; + StackPrototype.wasAltered = MapPrototype.wasAltered; + + + function makeStack(size, head, ownerID, hash) { + var map = Object.create(StackPrototype); + map.size = size; + map._head = head; + map.__ownerID = ownerID; + map.__hash = hash; + map.__altered = false; + return map; + } + + var EMPTY_STACK; + function emptyStack() { + return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); + } + + /** + * Contributes additional methods to a constructor + */ + function mixin(ctor, methods) { + var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; + Object.keys(methods).forEach(keyCopier); + Object.getOwnPropertySymbols && + Object.getOwnPropertySymbols(methods).forEach(keyCopier); + return ctor; + } + + Iterable.Iterator = Iterator; + + mixin(Iterable, { + + // ### Conversion to other types + + toArray: function() { + assertNotInfinite(this.size); + var array = new Array(this.size || 0); + this.valueSeq().__iterate(function(v, i) { array[i] = v; }); + return array; + }, + + toIndexedSeq: function() { + return new ToIndexedSequence(this); + }, + + toJS: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} + ).__toJS(); + }, + + toJSON: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} + ).__toJS(); + }, + + toKeyedSeq: function() { + return new ToKeyedSequence(this, true); + }, + + toMap: function() { + // Use Late Binding here to solve the circular dependency. + return Map(this.toKeyedSeq()); + }, + + toObject: function() { + assertNotInfinite(this.size); + var object = {}; + this.__iterate(function(v, k) { object[k] = v; }); + return object; + }, + + toOrderedMap: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedMap(this.toKeyedSeq()); + }, + + toOrderedSet: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, + + toSet: function() { + // Use Late Binding here to solve the circular dependency. + return Set(isKeyed(this) ? this.valueSeq() : this); + }, + + toSetSeq: function() { + return new ToSetSequence(this); + }, + + toSeq: function() { + return isIndexed(this) ? this.toIndexedSeq() : + isKeyed(this) ? this.toKeyedSeq() : + this.toSetSeq(); + }, + + toStack: function() { + // Use Late Binding here to solve the circular dependency. + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, + + toList: function() { + // Use Late Binding here to solve the circular dependency. + return List(isKeyed(this) ? this.valueSeq() : this); + }, + + + // ### Common JavaScript methods and properties + + toString: function() { + return '[Iterable]'; + }, + + __toString: function(head, tail) { + if (this.size === 0) { + return head + tail; + } + return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + concat: function() {var values = SLICE$0.call(arguments, 0); + return reify(this, concatFactory(this, values)); + }, + + includes: function(searchValue) { + return this.some(function(value ) {return is(value, searchValue)}); + }, + + entries: function() { + return this.__iterator(ITERATE_ENTRIES); + }, + + every: function(predicate, context) { + assertNotInfinite(this.size); + var returnValue = true; + this.__iterate(function(v, k, c) { + if (!predicate.call(context, v, k, c)) { + returnValue = false; + return false; + } + }); + return returnValue; + }, + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, true)); + }, + + find: function(predicate, context, notSetValue) { + var entry = this.findEntry(predicate, context); + return entry ? entry[1] : notSetValue; + }, + + findEntry: function(predicate, context) { + var found; + this.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } + }); + return found; + }, + + findLastEntry: function(predicate, context) { + return this.toSeq().reverse().findEntry(predicate, context); + }, + + forEach: function(sideEffect, context) { + assertNotInfinite(this.size); + return this.__iterate(context ? sideEffect.bind(context) : sideEffect); + }, + + join: function(separator) { + assertNotInfinite(this.size); + separator = separator !== undefined ? '' + separator : ','; + var joined = ''; + var isFirst = true; + this.__iterate(function(v ) { + isFirst ? (isFirst = false) : (joined += separator); + joined += v !== null && v !== undefined ? v.toString() : ''; + }); + return joined; + }, + + keys: function() { + return this.__iterator(ITERATE_KEYS); + }, + + map: function(mapper, context) { + return reify(this, mapFactory(this, mapper, context)); + }, + + reduce: function(reducer, initialReduction, context) { + assertNotInfinite(this.size); + var reduction; + var useFirst; + if (arguments.length < 2) { + useFirst = true; + } else { + reduction = initialReduction; + } + this.__iterate(function(v, k, c) { + if (useFirst) { + useFirst = false; + reduction = v; + } else { + reduction = reducer.call(context, reduction, v, k, c); + } + }); + return reduction; + }, + + reduceRight: function(reducer, initialReduction, context) { + var reversed = this.toKeyedSeq().reverse(); + return reversed.reduce.apply(reversed, arguments); + }, + + reverse: function() { + return reify(this, reverseFactory(this, true)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, true)); + }, + + some: function(predicate, context) { + return !this.every(not(predicate), context); + }, + + sort: function(comparator) { + return reify(this, sortFactory(this, comparator)); + }, + + values: function() { + return this.__iterator(ITERATE_VALUES); + }, + + + // ### More sequential methods + + butLast: function() { + return this.slice(0, -1); + }, + + isEmpty: function() { + return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); + }, + + count: function(predicate, context) { + return ensureSize( + predicate ? this.toSeq().filter(predicate, context) : this + ); + }, + + countBy: function(grouper, context) { + return countByFactory(this, grouper, context); + }, + + equals: function(other) { + return deepEqual(this, other); + }, + + entrySeq: function() { + var iterable = this; + if (iterable._cache) { + // We cache as an entries array, so we can just return the cache! + return new ArraySeq(iterable._cache); + } + var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); + entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; + return entriesSequence; + }, + + filterNot: function(predicate, context) { + return this.filter(not(predicate), context); + }, + + findLast: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, + + first: function() { + return this.find(returnTrue); + }, + + flatMap: function(mapper, context) { + return reify(this, flatMapFactory(this, mapper, context)); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, true)); + }, + + fromEntrySeq: function() { + return new FromEntriesSequence(this); + }, + + get: function(searchKey, notSetValue) { + return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); + }, + + getIn: function(searchKeyPath, notSetValue) { + var nested = this; + // Note: in an ES6 environment, we would prefer: + // for (var key of searchKeyPath) { + var iter = forceIterator(searchKeyPath); + var step; + while (!(step = iter.next()).done) { + var key = step.value; + nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; + if (nested === NOT_SET) { + return notSetValue; + } + } + return nested; + }, + + groupBy: function(grouper, context) { + return groupByFactory(this, grouper, context); + }, + + has: function(searchKey) { + return this.get(searchKey, NOT_SET) !== NOT_SET; + }, + + hasIn: function(searchKeyPath) { + return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; + }, + + isSubset: function(iter) { + iter = typeof iter.includes === 'function' ? iter : Iterable(iter); + return this.every(function(value ) {return iter.includes(value)}); + }, + + isSuperset: function(iter) { + iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); + return iter.isSubset(this); + }, + + keySeq: function() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, + + last: function() { + return this.toSeq().reverse().first(); + }, + + max: function(comparator) { + return maxFactory(this, comparator); + }, + + maxBy: function(mapper, comparator) { + return maxFactory(this, comparator, mapper); + }, + + min: function(comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); + }, + + minBy: function(mapper, comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); + }, + + rest: function() { + return this.slice(1); + }, + + skip: function(amount) { + return this.slice(Math.max(0, amount)); + }, + + skipLast: function(amount) { + return reify(this, this.toSeq().reverse().skip(amount).reverse()); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, true)); + }, + + skipUntil: function(predicate, context) { + return this.skipWhile(not(predicate), context); + }, + + sortBy: function(mapper, comparator) { + return reify(this, sortFactory(this, comparator, mapper)); + }, + + take: function(amount) { + return this.slice(0, Math.max(0, amount)); + }, + + takeLast: function(amount) { + return reify(this, this.toSeq().reverse().take(amount).reverse()); + }, + + takeWhile: function(predicate, context) { + return reify(this, takeWhileFactory(this, predicate, context)); + }, + + takeUntil: function(predicate, context) { + return this.takeWhile(not(predicate), context); + }, + + valueSeq: function() { + return this.toIndexedSeq(); + }, + + + // ### Hashable Object + + hashCode: function() { + return this.__hash || (this.__hash = hashIterable(this)); + } + + + // ### Internal + + // abstract __iterate(fn, reverse) + + // abstract __iterator(type, reverse) + }); + + // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; + + var IterablePrototype = Iterable.prototype; + IterablePrototype[IS_ITERABLE_SENTINEL] = true; + IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; + IterablePrototype.__toJS = IterablePrototype.toArray; + IterablePrototype.__toStringMapper = quoteString; + IterablePrototype.inspect = + IterablePrototype.toSource = function() { return this.toString(); }; + IterablePrototype.chain = IterablePrototype.flatMap; + IterablePrototype.contains = IterablePrototype.includes; + + // Temporary warning about using length + (function () { + try { + Object.defineProperty(IterablePrototype, 'length', { + get: function () { + if (!Iterable.noLengthWarning) { + var stack; + try { + throw new Error(); + } catch (error) { + stack = error.stack; + } + if (stack.indexOf('_wrapObject') === -1) { + console && console.warn && console.warn( + 'iterable.length has been deprecated, '+ + 'use iterable.size or iterable.count(). '+ + 'This warning will become a silent error in a future version. ' + + stack + ); + return this.size; + } + } + } + }); + } catch (e) {} + })(); + + + + mixin(KeyedIterable, { + + // ### More sequential methods + + flip: function() { + return reify(this, flipFactory(this)); + }, + + findKey: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, + + findLastKey: function(predicate, context) { + return this.toSeq().reverse().findKey(predicate, context); + }, + + keyOf: function(searchValue) { + return this.findKey(function(value ) {return is(value, searchValue)}); + }, + + lastKeyOf: function(searchValue) { + return this.findLastKey(function(value ) {return is(value, searchValue)}); + }, + + mapEntries: function(mapper, context) {var this$0 = this; + var iterations = 0; + return reify(this, + this.toSeq().map( + function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} + ).fromEntrySeq() + ); + }, + + mapKeys: function(mapper, context) {var this$0 = this; + return reify(this, + this.toSeq().flip().map( + function(k, v) {return mapper.call(context, k, v, this$0)} + ).flip() + ); + } + + }); + + var KeyedIterablePrototype = KeyedIterable.prototype; + KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; + KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; + KeyedIterablePrototype.__toJS = IterablePrototype.toObject; + KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; + + + + mixin(IndexedIterable, { + + // ### Conversion to other types + + toKeyedSeq: function() { + return new ToKeyedSequence(this, false); + }, + + + // ### ES6 Collection methods (ES6 Array and Map) + + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, false)); + }, + + findIndex: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry ? entry[0] : -1; + }, + + indexOf: function(searchValue) { + var key = this.toKeyedSeq().keyOf(searchValue); + return key === undefined ? -1 : key; + }, + + lastIndexOf: function(searchValue) { + var key = this.toKeyedSeq().reverse().keyOf(searchValue); + return key === undefined ? -1 : key; + + // var index = + // return this.toSeq().reverse().indexOf(searchValue); + }, + + reverse: function() { + return reify(this, reverseFactory(this, false)); + }, + + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, false)); + }, + + splice: function(index, removeNum /*, ...values*/) { + var numArgs = arguments.length; + removeNum = Math.max(removeNum | 0, 0); + if (numArgs === 0 || (numArgs === 2 && !removeNum)) { + return this; + } + // If index is negative, it should resolve relative to the size of the + // collection. However size may be expensive to compute if not cached, so + // only call count() if the number is in fact negative. + index = resolveBegin(index, index < 0 ? this.count() : this.size); + var spliced = this.slice(0, index); + return reify( + this, + numArgs === 1 ? + spliced : + spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) + ); + }, + + + // ### More collection methods + + findLastIndex: function(predicate, context) { + var key = this.toKeyedSeq().findLastKey(predicate, context); + return key === undefined ? -1 : key; + }, + + first: function() { + return this.get(0); + }, + + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, false)); + }, + + get: function(index, notSetValue) { + index = wrapIndex(this, index); + return (index < 0 || (this.size === Infinity || + (this.size !== undefined && index > this.size))) ? + notSetValue : + this.find(function(_, key) {return key === index}, undefined, notSetValue); + }, + + has: function(index) { + index = wrapIndex(this, index); + return index >= 0 && (this.size !== undefined ? + this.size === Infinity || index < this.size : + this.indexOf(index) !== -1 + ); + }, + + interpose: function(separator) { + return reify(this, interposeFactory(this, separator)); + }, + + interleave: function(/*...iterables*/) { + var iterables = [this].concat(arrCopy(arguments)); + var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); + var interleaved = zipped.flatten(true); + if (zipped.size) { + interleaved.size = zipped.size * iterables.length; + } + return reify(this, interleaved); + }, + + last: function() { + return this.get(-1); + }, + + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, false)); + }, + + zip: function(/*, ...iterables */) { + var iterables = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, iterables)); + }, + + zipWith: function(zipper/*, ...iterables */) { + var iterables = arrCopy(arguments); + iterables[0] = this; + return reify(this, zipWithFactory(this, zipper, iterables)); + } + + }); + + IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; + IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; + + + + mixin(SetIterable, { + + // ### ES6 Collection methods (ES6 Array and Map) + + get: function(value, notSetValue) { + return this.has(value) ? value : notSetValue; + }, + + includes: function(value) { + return this.has(value); + }, + + + // ### More sequential methods + + keySeq: function() { + return this.valueSeq(); + } + + }); + + SetIterable.prototype.has = IterablePrototype.includes; + + + // Mixin subclasses + + mixin(KeyedSeq, KeyedIterable.prototype); + mixin(IndexedSeq, IndexedIterable.prototype); + mixin(SetSeq, SetIterable.prototype); + + mixin(KeyedCollection, KeyedIterable.prototype); + mixin(IndexedCollection, IndexedIterable.prototype); + mixin(SetCollection, SetIterable.prototype); + + + // #pragma Helper functions + + function keyMapper(v, k) { + return k; + } + + function entryMapper(v, k) { + return [k, v]; + } + + function not(predicate) { + return function() { + return !predicate.apply(this, arguments); + } + } + + function neg(predicate) { + return function() { + return -predicate.apply(this, arguments); + } + } + + function quoteString(value) { + return typeof value === 'string' ? JSON.stringify(value) : value; + } + + function defaultZipper() { + return arrCopy(arguments); + } + + function defaultNegComparator(a, b) { + return a < b ? 1 : a > b ? -1 : 0; + } + + function hashIterable(iterable) { + if (iterable.size === Infinity) { + return 0; + } + var ordered = isOrdered(iterable); + var keyed = isKeyed(iterable); + var h = ordered ? 1 : 0; + var size = iterable.__iterate( + keyed ? + ordered ? + function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : + function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : + ordered ? + function(v ) { h = 31 * h + hash(v) | 0; } : + function(v ) { h = h + hash(v) | 0; } + ); + return murmurHashOfSize(size, h); + } + + function murmurHashOfSize(size, h) { + h = imul(h, 0xCC9E2D51); + h = imul(h << 15 | h >>> -15, 0x1B873593); + h = imul(h << 13 | h >>> -13, 5); + h = (h + 0xE6546B64 | 0) ^ size; + h = imul(h ^ h >>> 16, 0x85EBCA6B); + h = imul(h ^ h >>> 13, 0xC2B2AE35); + h = smi(h ^ h >>> 16); + return h; + } + + function hashMerge(a, b) { + return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int + } + + var Immutable = { + + Iterable: Iterable, + + Seq: Seq, + Collection: Collection, + Map: Map, + OrderedMap: OrderedMap, + List: List, + Stack: Stack, + Set: Set, + OrderedSet: OrderedSet, + + Record: Record, + Range: Range, + Repeat: Repeat, + + is: is, + fromJS: fromJS + + }; + + return Immutable; + +})); +},{}],119:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Creates an hash object. + * + * @private + * @constructor + * @returns {Object} Returns the new hash object. + */ +function Hash() {} + +// Avoid inheriting from `Object.prototype` when possible. +Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto; + +module.exports = Hash; + +},{"./_nativeCreate":190}],120:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'); + +module.exports = Map; + +},{"./_getNative":169,"./_root":192}],121:[function(require,module,exports){ +var mapClear = require('./_mapClear'), + mapDelete = require('./_mapDelete'), + mapGet = require('./_mapGet'), + mapHas = require('./_mapHas'), + mapSet = require('./_mapSet'); + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function MapCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.clear(); + while (++index < length) { + var entry = values[index]; + this.set(entry[0], entry[1]); + } +} + +// Add functions to the `MapCache`. +MapCache.prototype.clear = mapClear; +MapCache.prototype['delete'] = mapDelete; +MapCache.prototype.get = mapGet; +MapCache.prototype.has = mapHas; +MapCache.prototype.set = mapSet; + +module.exports = MapCache; + +},{"./_mapClear":184,"./_mapDelete":185,"./_mapGet":186,"./_mapHas":187,"./_mapSet":188}],122:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Set = getNative(root, 'Set'); + +module.exports = Set; + +},{"./_getNative":169,"./_root":192}],123:[function(require,module,exports){ +var stackClear = require('./_stackClear'), + stackDelete = require('./_stackDelete'), + stackGet = require('./_stackGet'), + stackHas = require('./_stackHas'), + stackSet = require('./_stackSet'); + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function Stack(values) { + var index = -1, + length = values ? values.length : 0; + + this.clear(); + while (++index < length) { + var entry = values[index]; + this.set(entry[0], entry[1]); + } +} + +// Add functions to the `Stack` cache. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +module.exports = Stack; + +},{"./_stackClear":194,"./_stackDelete":195,"./_stackGet":196,"./_stackHas":197,"./_stackSet":198}],124:[function(require,module,exports){ +var root = require('./_root'); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +module.exports = Symbol; + +},{"./_root":192}],125:[function(require,module,exports){ +var root = require('./_root'); + +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; + +module.exports = Uint8Array; + +},{"./_root":192}],126:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var WeakMap = getNative(root, 'WeakMap'); + +module.exports = WeakMap; + +},{"./_getNative":169,"./_root":192}],127:[function(require,module,exports){ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + var length = args.length; + switch (length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; + +},{}],128:[function(require,module,exports){ +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +module.exports = arrayMap; + +},{}],129:[function(require,module,exports){ +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +module.exports = arrayPush; + +},{}],130:[function(require,module,exports){ +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +module.exports = arraySome; + +},{}],131:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the associative array. + * + * @private + * @param {Array} array The array to query. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function assocDelete(array, key) { + var index = assocIndexOf(array, key); + if (index < 0) { + return false; + } + var lastIndex = array.length - 1; + if (index == lastIndex) { + array.pop(); + } else { + splice.call(array, index, 1); + } + return true; +} + +module.exports = assocDelete; + +},{"./_assocIndexOf":134}],132:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Gets the associative array value for `key`. + * + * @private + * @param {Array} array The array to query. + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function assocGet(array, key) { + var index = assocIndexOf(array, key); + return index < 0 ? undefined : array[index][1]; +} + +module.exports = assocGet; + +},{"./_assocIndexOf":134}],133:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Checks if an associative array value for `key` exists. + * + * @private + * @param {Array} array The array to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function assocHas(array, key) { + return assocIndexOf(array, key) > -1; +} + +module.exports = assocHas; + +},{"./_assocIndexOf":134}],134:[function(require,module,exports){ +var eq = require('./eq'); + +/** + * Gets the index at which the first occurrence of `key` is found in `array` + * of key-value pairs. + * + * @private + * @param {Array} array The array to search. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +module.exports = assocIndexOf; + +},{"./eq":200}],135:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Sets the associative array `key` to `value`. + * + * @private + * @param {Array} array The array to modify. + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + */ +function assocSet(array, key, value) { + var index = assocIndexOf(array, key); + if (index < 0) { + array.push([key, value]); + } else { + array[index][1] = value; + } +} + +module.exports = assocSet; + +},{"./_assocIndexOf":134}],136:[function(require,module,exports){ +var isArray = require('./isArray'), + stringToPath = require('./_stringToPath'); + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ +function baseCastPath(value) { + return isArray(value) ? value : stringToPath(value); +} + +module.exports = baseCastPath; + +},{"./_stringToPath":199,"./isArray":205}],137:[function(require,module,exports){ +var baseForOwn = require('./_baseForOwn'), + createBaseEach = require('./_createBaseEach'); + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); + +module.exports = baseEach; + +},{"./_baseForOwn":140,"./_createBaseEach":162}],138:[function(require,module,exports){ +var arrayPush = require('./_arrayPush'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, isStrict, result) { + result || (result = []); + + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index]; + if (depth > 0 && isArrayLikeObject(value) && + (isStrict || isArray(value) || isArguments(value))) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +module.exports = baseFlatten; + +},{"./_arrayPush":129,"./isArguments":204,"./isArray":205,"./isArrayLikeObject":207}],139:[function(require,module,exports){ +var createBaseFor = require('./_createBaseFor'); + +/** + * The base implementation of `baseForIn` and `baseForOwn` which iterates + * over `object` properties returned by `keysFunc` invoking `iteratee` for + * each property. Iteratee functions may exit iteration early by explicitly + * returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +module.exports = baseFor; + +},{"./_createBaseFor":163}],140:[function(require,module,exports){ +var baseFor = require('./_baseFor'), + keys = require('./keys'); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +module.exports = baseForOwn; + +},{"./_baseFor":139,"./keys":216}],141:[function(require,module,exports){ +var baseCastPath = require('./_baseCastPath'), + isKey = require('./_isKey'); + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = isKey(path, object) ? [path + ''] : baseCastPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[path[index++]]; + } + return (index && index == length) ? object : undefined; +} + +module.exports = baseGet; + +},{"./_baseCastPath":136,"./_isKey":180}],142:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Built-in value references. */ +var getPrototypeOf = Object.getPrototypeOf; + +/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHas(object, key) { + // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, + // that are composed entirely of index properties, return `false` for + // `hasOwnProperty` checks of them. + return hasOwnProperty.call(object, key) || + (typeof object == 'object' && key in object && getPrototypeOf(object) === null); +} + +module.exports = baseHas; + +},{}],143:[function(require,module,exports){ +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return key in Object(object); +} + +module.exports = baseHasIn; + +},{}],144:[function(require,module,exports){ +var baseIsEqualDeep = require('./_baseIsEqualDeep'), + isObject = require('./isObject'), + isObjectLike = require('./isObjectLike'); + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); +} + +module.exports = baseIsEqual; + +},{"./_baseIsEqualDeep":145,"./isObject":211,"./isObjectLike":212}],145:[function(require,module,exports){ +var Stack = require('./_Stack'), + equalArrays = require('./_equalArrays'), + equalByTag = require('./_equalByTag'), + equalObjects = require('./_equalObjects'), + getTag = require('./_getTag'), + isArray = require('./isArray'), + isHostObject = require('./_isHostObject'), + isTypedArray = require('./isTypedArray'); + +/** Used to compose bitmasks for comparison styles. */ +var PARTIAL_COMPARE_FLAG = 2; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag && !isHostObject(object), + othIsObj = othTag == objectTag && !isHostObject(other), + isSameTag = objTag == othTag; + + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + stack || (stack = new Stack); + return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); +} + +module.exports = baseIsEqualDeep; + +},{"./_Stack":123,"./_equalArrays":164,"./_equalByTag":165,"./_equalObjects":166,"./_getTag":170,"./_isHostObject":177,"./isArray":205,"./isTypedArray":215}],146:[function(require,module,exports){ +var Stack = require('./_Stack'), + baseIsEqual = require('./_baseIsEqual'); + +/** Used to compose bitmasks for comparison styles. */ +var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack, + result = customizer ? customizer(objValue, srcValue, key, object, source, stack) : undefined; + + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) + : result + )) { + return false; + } + } + } + return true; +} + +module.exports = baseIsMatch; + +},{"./_Stack":123,"./_baseIsEqual":144}],147:[function(require,module,exports){ +var baseMatches = require('./_baseMatches'), + baseMatchesProperty = require('./_baseMatchesProperty'), + identity = require('./identity'), + isArray = require('./isArray'), + property = require('./property'); + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + var type = typeof value; + if (type == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (type == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +module.exports = baseIteratee; + +},{"./_baseMatches":150,"./_baseMatchesProperty":151,"./identity":203,"./isArray":205,"./property":218}],148:[function(require,module,exports){ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = Object.keys; + +/** + * The base implementation of `_.keys` which doesn't skip the constructor + * property of prototypes or treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + return nativeKeys(Object(object)); +} + +module.exports = baseKeys; + +},{}],149:[function(require,module,exports){ +var baseEach = require('./_baseEach'), + isArrayLike = require('./isArrayLike'); + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +module.exports = baseMap; + +},{"./_baseEach":137,"./isArrayLike":206}],150:[function(require,module,exports){ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + var key = matchData[0][0], + value = matchData[0][1]; + + return function(object) { + if (object == null) { + return false; + } + return object[key] === value && + (value !== undefined || (key in Object(object))); + }; + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +module.exports = baseMatches; + +},{"./_baseIsMatch":146,"./_getMatchData":168}],151:[function(require,module,exports){ +var baseIsEqual = require('./_baseIsEqual'), + get = require('./get'), + hasIn = require('./hasIn'); + +/** Used to compose bitmasks for comparison styles. */ +var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new function. + */ +function baseMatchesProperty(path, srcValue) { + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; +} + +module.exports = baseMatchesProperty; + +},{"./_baseIsEqual":144,"./get":201,"./hasIn":202}],152:[function(require,module,exports){ +var arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseMap = require('./_baseMap'), + baseSortBy = require('./_baseSortBy'), + compareMultiple = require('./_compareMultiple'); + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : Array(1), baseIteratee); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +module.exports = baseOrderBy; + +},{"./_arrayMap":128,"./_baseIteratee":147,"./_baseMap":149,"./_baseSortBy":156,"./_compareMultiple":161}],153:[function(require,module,exports){ +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = baseProperty; + +},{}],154:[function(require,module,exports){ +var baseGet = require('./_baseGet'); + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +module.exports = basePropertyDeep; + +},{"./_baseGet":141}],155:[function(require,module,exports){ +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +module.exports = baseSlice; + +},{}],156:[function(require,module,exports){ +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +module.exports = baseSortBy; + +},{}],157:[function(require,module,exports){ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; + +},{}],158:[function(require,module,exports){ +var arrayMap = require('./_arrayMap'); + +/** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the new array of key-value pairs. + */ +function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); +} + +module.exports = baseToPairs; + +},{"./_arrayMap":128}],159:[function(require,module,exports){ +/** + * Checks if `value` is a global object. + * + * @private + * @param {*} value The value to check. + * @returns {null|Object} Returns `value` if it's a global object, else `null`. + */ +function checkGlobal(value) { + return (value && value.Object === Object) ? value : null; +} + +module.exports = checkGlobal; + +},{}],160:[function(require,module,exports){ +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsNull = value === null, + valIsUndef = value === undefined, + valIsReflexive = value === value; + + var othIsNull = other === null, + othIsUndef = other === undefined, + othIsReflexive = other === other; + + if ((value > other && !othIsNull) || !valIsReflexive || + (valIsNull && !othIsUndef && othIsReflexive) || + (valIsUndef && othIsReflexive)) { + return 1; + } + if ((value < other && !valIsNull) || !othIsReflexive || + (othIsNull && !valIsUndef && valIsReflexive) || + (othIsUndef && valIsReflexive)) { + return -1; + } + } + return 0; +} + +module.exports = compareAscending; + +},{}],161:[function(require,module,exports){ +var compareAscending = require('./_compareAscending'); + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://code.google.com/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +module.exports = compareMultiple; + +},{"./_compareAscending":160}],162:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'); + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +module.exports = createBaseEach; + +},{"./isArrayLike":206}],163:[function(require,module,exports){ +/** + * Creates a base function for methods like `_.forIn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +module.exports = createBaseFor; + +},{}],164:[function(require,module,exports){ +var arraySome = require('./_arraySome'); + +/** Used to compose bitmasks for comparison styles. */ +var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var index = -1, + isPartial = bitmask & PARTIAL_COMPARE_FLAG, + isUnordered = bitmask & UNORDERED_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked) { + return stacked == other; + } + var result = true; + stack.set(array, other); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (isUnordered) { + if (!arraySome(other, function(othValue) { + return arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack); + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + result = false; + break; + } + } + stack['delete'](array); + return result; +} + +module.exports = equalArrays; + +},{"./_arraySome":130}],165:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + Uint8Array = require('./_Uint8Array'), + equalArrays = require('./_equalArrays'), + mapToArray = require('./_mapToArray'), + setToArray = require('./_setToArray'); + +/** Used to compose bitmasks for comparison styles. */ +var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + // Coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. + return +object == +other; + + case errorTag: + return object.name == other.name && object.message == other.message; + + case numberTag: + // Treat `NaN` vs. `NaN` as equal. + return (object != +object) ? other != +other : object == +other; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings primitives and string + // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + // Recursively compare objects (susceptible to call stack limits). + return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask | UNORDERED_COMPARE_FLAG, stack.set(object, other)); + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +module.exports = equalByTag; + +},{"./_Symbol":124,"./_Uint8Array":125,"./_equalArrays":164,"./_mapToArray":189,"./_setToArray":193}],166:[function(require,module,exports){ +var baseHas = require('./_baseHas'), + keys = require('./keys'); + +/** Used to compose bitmasks for comparison styles. */ +var PARTIAL_COMPARE_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : baseHas(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + var result = true; + stack.set(object, other); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + return result; +} + +module.exports = equalObjects; + +},{"./_baseHas":142,"./keys":216}],167:[function(require,module,exports){ +var baseProperty = require('./_baseProperty'); + +/** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * that affects Safari on at least iOS 8.1-8.3 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ +var getLength = baseProperty('length'); + +module.exports = getLength; + +},{"./_baseProperty":153}],168:[function(require,module,exports){ +var isStrictComparable = require('./_isStrictComparable'), + toPairs = require('./toPairs'); + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = toPairs(object), + length = result.length; + + while (length--) { + result[length][2] = isStrictComparable(result[length][1]); + } + return result; +} + +module.exports = getMatchData; + +},{"./_isStrictComparable":183,"./toPairs":223}],169:[function(require,module,exports){ +var isNative = require('./isNative'); + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = object[key]; + return isNative(value) ? value : undefined; +} + +module.exports = getNative; + +},{"./isNative":210}],170:[function(require,module,exports){ +var Map = require('./_Map'), + Set = require('./_Set'), + WeakMap = require('./_WeakMap'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + objectTag = '[object Object]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = Function.prototype.toString; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Used to detect maps, sets, and weakmaps. */ +var mapCtorString = Map ? funcToString.call(Map) : '', + setCtorString = Set ? funcToString.call(Set) : '', + weakMapCtorString = WeakMap ? funcToString.call(WeakMap) : ''; + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function getTag(value) { + return objectToString.call(value); +} + +// Fallback for IE 11 providing `toStringTag` values for maps, sets, and weakmaps. +if ((Map && getTag(new Map) != mapTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : null, + ctorString = typeof Ctor == 'function' ? funcToString.call(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case mapCtorString: return mapTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +module.exports = getTag; + +},{"./_Map":120,"./_Set":122,"./_WeakMap":126}],171:[function(require,module,exports){ +var baseCastPath = require('./_baseCastPath'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'), + isKey = require('./_isKey'), + isLength = require('./isLength'), + isString = require('./isString'), + last = require('./last'), + parent = require('./_parent'); + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + if (object == null) { + return false; + } + var result = hasFunc(object, path); + if (!result && !isKey(path)) { + path = baseCastPath(path); + object = parent(object, path); + if (object != null) { + path = last(path); + result = hasFunc(object, path); + } + } + var length = object ? object.length : undefined; + return result || ( + !!length && isLength(length) && isIndex(path, length) && + (isArray(object) || isString(object) || isArguments(object)) + ); +} + +module.exports = hasPath; + +},{"./_baseCastPath":136,"./_isIndex":178,"./_isKey":180,"./_parent":191,"./isArguments":204,"./isArray":205,"./isLength":209,"./isString":213,"./last":217}],172:[function(require,module,exports){ +var hashHas = require('./_hashHas'); + +/** + * Removes `key` and its value from the hash. + * + * @private + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(hash, key) { + return hashHas(hash, key) && delete hash[key]; +} + +module.exports = hashDelete; + +},{"./_hashHas":174}],173:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @param {Object} hash The hash to query. + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(hash, key) { + if (nativeCreate) { + var result = hash[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(hash, key) ? hash[key] : undefined; +} + +module.exports = hashGet; + +},{"./_nativeCreate":190}],174:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @param {Object} hash The hash to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(hash, key) { + return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key); +} + +module.exports = hashHas; + +},{"./_nativeCreate":190}],175:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + */ +function hashSet(hash, key, value) { + hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; +} + +module.exports = hashSet; + +},{"./_nativeCreate":190}],176:[function(require,module,exports){ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isLength = require('./isLength'), + isString = require('./isString'); + +/** + * Creates an array of index keys for `object` values of arrays, + * `arguments` objects, and strings, otherwise `null` is returned. + * + * @private + * @param {Object} object The object to query. + * @returns {Array|null} Returns index keys, else `null`. + */ +function indexKeys(object) { + var length = object ? object.length : undefined; + if (isLength(length) && + (isArray(object) || isString(object) || isArguments(object))) { + return baseTimes(length, String); + } + return null; +} + +module.exports = indexKeys; + +},{"./_baseTimes":157,"./isArguments":204,"./isArray":205,"./isLength":209,"./isString":213}],177:[function(require,module,exports){ +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +module.exports = isHostObject; + +},{}],178:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; + length = length == null ? MAX_SAFE_INTEGER : length; + return value > -1 && value % 1 == 0 && value < length; +} + +module.exports = isIndex; + +},{}],179:[function(require,module,exports){ +var eq = require('./eq'), + isArrayLike = require('./isArrayLike'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'); + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object)) { + return eq(object[index], value); + } + return false; +} + +module.exports = isIterateeCall; + +},{"./_isIndex":178,"./eq":200,"./isArrayLike":206,"./isObject":211}],180:[function(require,module,exports){ +var isArray = require('./isArray'); + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (typeof value == 'number') { + return true; + } + return !isArray(value) && + (reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object))); +} + +module.exports = isKey; + +},{"./isArray":205}],181:[function(require,module,exports){ +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return type == 'number' || type == 'boolean' || + (type == 'string' && value != '__proto__') || value == null; +} + +module.exports = isKeyable; + +},{}],182:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; + +},{}],183:[function(require,module,exports){ +var isObject = require('./isObject'); + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +module.exports = isStrictComparable; + +},{"./isObject":211}],184:[function(require,module,exports){ +var Hash = require('./_Hash'), + Map = require('./_Map'); + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapClear() { + this.__data__ = { + 'hash': new Hash, + 'map': Map ? new Map : [], + 'string': new Hash + }; +} + +module.exports = mapClear; + +},{"./_Hash":119,"./_Map":120}],185:[function(require,module,exports){ +var Map = require('./_Map'), + assocDelete = require('./_assocDelete'), + hashDelete = require('./_hashDelete'), + isKeyable = require('./_isKeyable'); + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapDelete(key) { + var data = this.__data__; + if (isKeyable(key)) { + return hashDelete(typeof key == 'string' ? data.string : data.hash, key); + } + return Map ? data.map['delete'](key) : assocDelete(data.map, key); +} + +module.exports = mapDelete; + +},{"./_Map":120,"./_assocDelete":131,"./_hashDelete":172,"./_isKeyable":181}],186:[function(require,module,exports){ +var Map = require('./_Map'), + assocGet = require('./_assocGet'), + hashGet = require('./_hashGet'), + isKeyable = require('./_isKeyable'); + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapGet(key) { + var data = this.__data__; + if (isKeyable(key)) { + return hashGet(typeof key == 'string' ? data.string : data.hash, key); + } + return Map ? data.map.get(key) : assocGet(data.map, key); +} + +module.exports = mapGet; + +},{"./_Map":120,"./_assocGet":132,"./_hashGet":173,"./_isKeyable":181}],187:[function(require,module,exports){ +var Map = require('./_Map'), + assocHas = require('./_assocHas'), + hashHas = require('./_hashHas'), + isKeyable = require('./_isKeyable'); + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapHas(key) { + var data = this.__data__; + if (isKeyable(key)) { + return hashHas(typeof key == 'string' ? data.string : data.hash, key); + } + return Map ? data.map.has(key) : assocHas(data.map, key); +} + +module.exports = mapHas; + +},{"./_Map":120,"./_assocHas":133,"./_hashHas":174,"./_isKeyable":181}],188:[function(require,module,exports){ +var Map = require('./_Map'), + assocSet = require('./_assocSet'), + hashSet = require('./_hashSet'), + isKeyable = require('./_isKeyable'); + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache object. + */ +function mapSet(key, value) { + var data = this.__data__; + if (isKeyable(key)) { + hashSet(typeof key == 'string' ? data.string : data.hash, key, value); + } else if (Map) { + data.map.set(key, value); + } else { + assocSet(data.map, key, value); + } + return this; +} + +module.exports = mapSet; + +},{"./_Map":120,"./_assocSet":135,"./_hashSet":175,"./_isKeyable":181}],189:[function(require,module,exports){ +/** + * Converts `map` to an array. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the converted array. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +module.exports = mapToArray; + +},{}],190:[function(require,module,exports){ +var getNative = require('./_getNative'); + +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); + +module.exports = nativeCreate; + +},{"./_getNative":169}],191:[function(require,module,exports){ +var baseSlice = require('./_baseSlice'), + get = require('./get'); + +/** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ +function parent(object, path) { + return path.length == 1 ? object : get(object, baseSlice(path, 0, -1)); +} + +module.exports = parent; + +},{"./_baseSlice":155,"./get":201}],192:[function(require,module,exports){ +(function (global){ +var checkGlobal = require('./_checkGlobal'); + +/** Used to determine if values are of the language type `Object`. */ +var objectTypes = { + 'function': true, + 'object': true +}; + +/** Detect free variable `exports`. */ +var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) + ? exports + : undefined; + +/** Detect free variable `module`. */ +var freeModule = (objectTypes[typeof module] && module && !module.nodeType) + ? module + : undefined; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global); + +/** Detect free variable `self`. */ +var freeSelf = checkGlobal(objectTypes[typeof self] && self); + +/** Detect free variable `window`. */ +var freeWindow = checkGlobal(objectTypes[typeof window] && window); + +/** Detect `this` as the global object. */ +var thisGlobal = checkGlobal(objectTypes[typeof this] && this); + +/** + * Used as a reference to the global object. + * + * The `this` value is used if it's the global object to avoid Greasemonkey's + * restricted `window` object, otherwise the `window` object is used. + */ +var root = freeGlobal || + ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || + freeSelf || thisGlobal || Function('return this')(); + +module.exports = root; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_checkGlobal":159}],193:[function(require,module,exports){ +/** + * Converts `set` to an array. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the converted array. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +module.exports = setToArray; + +},{}],194:[function(require,module,exports){ +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = { 'array': [], 'map': null }; +} + +module.exports = stackClear; + +},{}],195:[function(require,module,exports){ +var assocDelete = require('./_assocDelete'); + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + array = data.array; + + return array ? assocDelete(array, key) : data.map['delete'](key); +} + +module.exports = stackDelete; + +},{"./_assocDelete":131}],196:[function(require,module,exports){ +var assocGet = require('./_assocGet'); + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + var data = this.__data__, + array = data.array; + + return array ? assocGet(array, key) : data.map.get(key); +} + +module.exports = stackGet; + +},{"./_assocGet":132}],197:[function(require,module,exports){ +var assocHas = require('./_assocHas'); + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + var data = this.__data__, + array = data.array; + + return array ? assocHas(array, key) : data.map.has(key); +} + +module.exports = stackHas; + +},{"./_assocHas":133}],198:[function(require,module,exports){ +var MapCache = require('./_MapCache'), + assocSet = require('./_assocSet'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache object. + */ +function stackSet(key, value) { + var data = this.__data__, + array = data.array; + + if (array) { + if (array.length < (LARGE_ARRAY_SIZE - 1)) { + assocSet(array, key, value); + } else { + data.array = null; + data.map = new MapCache(array); + } + } + var map = data.map; + if (map) { + map.set(key, value); + } + return this; +} + +module.exports = stackSet; + +},{"./_MapCache":121,"./_assocSet":135}],199:[function(require,module,exports){ +var toString = require('./toString'); + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +function stringToPath(string) { + var result = []; + toString(string).replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +} + +module.exports = stringToPath; + +},{"./toString":224}],200:[function(require,module,exports){ +/** + * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +module.exports = eq; + +},{}],201:[function(require,module,exports){ +var baseGet = require('./_baseGet'); + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined` the `defaultValue` is used in its place. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +module.exports = get; + +},{"./_baseGet":141}],202:[function(require,module,exports){ +var baseHasIn = require('./_baseHasIn'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b.c'); + * // => true + * + * _.hasIn(object, ['a', 'b', 'c']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return hasPath(object, path, baseHasIn); +} + +module.exports = hasIn; + +},{"./_baseHasIn":143,"./_hasPath":171}],203:[function(require,module,exports){ +/** + * This method returns the first argument given to it. + * + * @static + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'user': 'fred' }; + * + * _.identity(object) === object; + * // => true + */ +function identity(value) { + return value; +} + +module.exports = identity; + +},{}],204:[function(require,module,exports){ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +module.exports = isArguments; + +},{"./isArrayLikeObject":207}],205:[function(require,module,exports){ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type {Function} + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; + +},{}],206:[function(require,module,exports){ +var getLength = require('./_getLength'), + isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(getLength(value)) && !isFunction(value); +} + +module.exports = isArrayLike; + +},{"./_getLength":167,"./isFunction":208,"./isLength":209}],207:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; + +},{"./isArrayLike":206,"./isObjectLike":212}],208:[function(require,module,exports){ +var isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8 which returns 'object' for typed array and weak map constructors, + // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +module.exports = isFunction; + +},{"./isObject":211}],209:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; + +},{}],210:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isHostObject = require('./_isHostObject'), + isObjectLike = require('./isObjectLike'); + +/** Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari > 5). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = Function.prototype.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * Checks if `value` is a native function. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ +function isNative(value) { + if (value == null) { + return false; + } + if (isFunction(value)) { + return reIsNative.test(funcToString.call(value)); + } + return isObjectLike(value) && + (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); +} + +module.exports = isNative; + +},{"./_isHostObject":177,"./isFunction":208,"./isObjectLike":212}],211:[function(require,module,exports){ +/** + * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +module.exports = isObject; + +},{}],212:[function(require,module,exports){ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isObjectLike; + +},{}],213:[function(require,module,exports){ +var isArray = require('./isArray'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} + +module.exports = isString; + +},{"./isArray":205,"./isObjectLike":212}],214:[function(require,module,exports){ +var isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +module.exports = isSymbol; + +},{"./isObjectLike":212}],215:[function(require,module,exports){ +var isLength = require('./isLength'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dateTag] = typedArrayTags[errorTag] = +typedArrayTags[funcTag] = typedArrayTags[mapTag] = +typedArrayTags[numberTag] = typedArrayTags[objectTag] = +typedArrayTags[regexpTag] = typedArrayTags[setTag] = +typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +function isTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; +} + +module.exports = isTypedArray; + +},{"./isLength":209,"./isObjectLike":212}],216:[function(require,module,exports){ +var baseHas = require('./_baseHas'), + baseKeys = require('./_baseKeys'), + indexKeys = require('./_indexKeys'), + isArrayLike = require('./isArrayLike'), + isIndex = require('./_isIndex'), + isPrototype = require('./_isPrototype'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) + * for more details. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + var isProto = isPrototype(object); + if (!(isProto || isArrayLike(object))) { + return baseKeys(object); + } + var indexes = indexKeys(object), + skipIndexes = !!indexes, + result = indexes || [], + length = result.length; + + for (var key in object) { + if (baseHas(object, key) && + !(skipIndexes && (key == 'length' || isIndex(key, length))) && + !(isProto && key == 'constructor')) { + result.push(key); + } + } + return result; +} + +module.exports = keys; + +},{"./_baseHas":142,"./_baseKeys":148,"./_indexKeys":176,"./_isIndex":178,"./_isPrototype":182,"./isArrayLike":206}],217:[function(require,module,exports){ +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; +} + +module.exports = last; + +},{}],218:[function(require,module,exports){ +var baseProperty = require('./_baseProperty'), + basePropertyDeep = require('./_basePropertyDeep'), + isKey = require('./_isKey'); + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + * @example + * + * var objects = [ + * { 'a': { 'b': { 'c': 2 } } }, + * { 'a': { 'b': { 'c': 1 } } } + * ]; + * + * _.map(objects, _.property('a.b.c')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); + * // => [1, 2] + */ +function property(path) { + return isKey(path) ? baseProperty(path) : basePropertyDeep(path); +} + +module.exports = property; + +},{"./_baseProperty":153,"./_basePropertyDeep":154,"./_isKey":180}],219:[function(require,module,exports){ +var apply = require('./_apply'), + toInteger = require('./toInteger'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, array); + case 1: return func.call(this, args[0], array); + case 2: return func.call(this, args[0], args[1], array); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +module.exports = rest; + +},{"./_apply":127,"./toInteger":221}],220:[function(require,module,exports){ +var baseFlatten = require('./_baseFlatten'), + baseOrderBy = require('./_baseOrderBy'), + isIterateeCall = require('./_isIterateeCall'), + rest = require('./rest'); + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} [iteratees=[_.identity]] + * The iteratees to sort by, specified individually or in arrays. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, function(o) { return o.user; }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.sortBy(users, 'user', function(o) { + * return Math.floor(o.age / 10); + * }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ +var sortBy = rest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees.length = 1; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); +}); + +module.exports = sortBy; + +},{"./_baseFlatten":138,"./_baseOrderBy":152,"./_isIterateeCall":179,"./rest":219}],221:[function(require,module,exports){ +var toNumber = require('./toNumber'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; + +/** + * Converts `value` to an integer. + * + * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3'); + * // => 3 + */ +function toInteger(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + var remainder = value % 1; + return value === value ? (remainder ? value - remainder : value) : 0; +} + +module.exports = toInteger; + +},{"./toNumber":222}],222:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isObject = require('./isObject'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3); + * // => 3 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3'); + * // => 3 + */ +function toNumber(value) { + if (isObject(value)) { + var other = isFunction(value.valueOf) ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = toNumber; + +},{"./isFunction":208,"./isObject":211}],223:[function(require,module,exports){ +var baseToPairs = require('./_baseToPairs'), + keys = require('./keys'); + +/** + * Creates an array of own enumerable key-value pairs for `object` which + * can be consumed by `_.fromPairs`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the new array of key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ +function toPairs(object) { + return baseToPairs(object, keys(object)); +} + +module.exports = toPairs; + +},{"./_baseToPairs":158,"./keys":216}],224:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * Converts `value` to a string if it's not one. An empty string is returned + * for `null` and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (value == null) { + return ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = toString; + +},{"./_Symbol":124,"./isSymbol":214}],225:[function(require,module,exports){ +module.exports={ + "name": "rxmarbles", + "version": "1.4.1", + "author": "Andre Staltz", + "repository": { + "type": "git", + "url": "git@github.com:staltz/rxmarbles.git" + }, + "license": "BSD 3-Clause", + "private": true, + "main": "js/app.js", + "dependencies": { + "@cycle/core": "1.0.x", + "@cycle/dom": "3.1.x", + "immutable": "^3.7.2", + "lodash": "4.6.1", + "rxtween": "0.3.3" + }, + "devDependencies": { + "browserify": "10.1.3", + "less": "^2.5.0", + "uglify-js": "~2.4.21", + "watchify": "~3.2.1", + "babel": "^5.2.7" + }, + "scripts": { + "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src", + "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json", + "less": "lessc styles/main.less dist/css/main.css", + "babel": "mkdir -p ignore/es5src && babel src --out-dir ignore/es5src", + "browserify": "browserify -e ignore/es5src/app.js --outfile dist/js/app.js", + "browserify-element": "browserify -e ignore/es5src/element.js --outfile dist/js/element.js", + "build": "npm run less && npm run babel && npm run browserify", + "build-production": "npm run less && npm run babel && npm run browserify && npm run uglify", + "build-element": "npm run less && npm run babel && npm run browserify-element", + "build-element-production": "npm run less && npm run babel && npm run browserify-element && npm run uglify-element", + "uglify": "uglifyjs dist/js/app.js -o dist/js/app.js", + "uglify-element": "uglifyjs dist/js/element.js -o dist/js/element.js", + "update-gh-pages": "git checkout gh-pages && git merge --no-ff -X theirs master && git push origin gh-pages && git checkout master", + "release": "npm run release-patch", + "release-patch": "git checkout master && npm version patch && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages", + "release-minor": "git checkout master && npm version minor && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages", + "release-major": "git checkout master && npm version major && npm run build-production && npm run build-element-production && git commit -a -m 'Build dist/' && git push origin master --tags && npm run update-gh-pages" + } +} + +},{}],226:[function(require,module,exports){ +arguments[4][2][0].apply(exports,arguments) +},{"_process":117,"dup":2}],227:[function(require,module,exports){ +'use strict'; + +var _cycleCore = require('@cycle/core'); + +var packageJson = require('package'); +var RxPackageJson = require('@cycle/core/node_modules/rx/package.json'); + +var DEFAULT_EXAMPLE = 'merge'; + +module.exports = function appModel() { + var route$ = _cycleCore.Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { + return hashEvent.target.location.hash.replace('#', ''); + }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE); + var appVersion$ = _cycleCore.Rx.Observable.just(packageJson.version); + var rxVersion$ = _cycleCore.Rx.Observable.just(RxPackageJson.version); + return _cycleCore.Rx.Observable.combineLatest(route$, appVersion$, rxVersion$, function (route, appVersion, rxVersion) { + return { route: route, appVersion: appVersion, rxVersion: rxVersion }; + }); +}; +},{"@cycle/core":1,"@cycle/core/node_modules/rx/package.json":3,"package":225}],228:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesStylesFonts = require('rxmarbles/styles/fonts'); + +var _rxmarblesStylesFonts2 = _interopRequireDefault(_rxmarblesStylesFonts); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +var rxmarblesGithubUrl = 'https://github.com/staltz/rxmarbles'; +var rxjsGithubUrl = 'https://github.com/Reactive-Extensions/RxJS'; + +var pageRowWidth = '1060px'; +var sandboxWidth = '820px'; + +var pageRowStyle = { + position: 'relative', + width: pageRowWidth, + margin: '0 auto' +}; + +var pageRowChildStyle = { + display: 'inline-block' +}; + +var pageRowFirstChildStyle = (0, _rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle, { + width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _rxmarblesStylesDimens2['default'].spaceMedium + ')' +}); + +var pageRowLastChildStyle = (0, _rxmarblesStylesUtils.mergeStyles)(pageRowChildStyle, { + width: sandboxWidth +}); + +function renderHeader() { + return (0, _cycleDom.h)('div', { style: pageRowStyle }, [(0, _cycleDom.h)('h1', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + fontFamily: _rxmarblesStylesFonts2['default'].fontSpecial, + color: _rxmarblesStylesColors2['default'].greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), (0, _cycleDom.h)('h3', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + color: _rxmarblesStylesColors2['default'].greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); +} + +function renderContent(route) { + var style = (0, _rxmarblesStylesUtils.mergeStyles)(pageRowStyle, { marginTop: _rxmarblesStylesDimens2['default'].spaceSmall }); + return (0, _cycleDom.h)('div', { style: style }, [(0, _cycleDom.h)('div', { style: pageRowFirstChildStyle }, (0, _cycleDom.h)('x-operators-menu', { key: 'operatorsMenu' })), (0, _cycleDom.h)('div', { style: (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'absolute', + top: '0' }, pageRowLastChildStyle) }, (0, _cycleDom.h)('x-sandbox', { key: 'sandbox', route: route, width: '820px' }))]); +} + +function renderFooter(appVersion, rxVersion) { + var style = { + position: 'fixed', + bottom: '2px', + right: _rxmarblesStylesDimens2['default'].spaceMedium, + color: _rxmarblesStylesColors2['default'].greyDark + }; + return (0, _cycleDom.h)('section', { style: style }, [(0, _cycleDom.h)('a', { href: rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', (0, _cycleDom.h)('a', { href: rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', (0, _cycleDom.h)('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); +} + +module.exports = function appView(state$) { + var wrapperStyle = { + paddingLeft: _rxmarblesStylesDimens2['default'].spaceSmall, + paddingRight: 'calc(' + _rxmarblesStylesDimens2['default'].spaceHuge + ' + ' + _rxmarblesStylesDimens2['default'].spaceSmall + ')' + }; + return state$.map(function (_ref) { + var route = _ref.route; + var appVersion = _ref.appVersion; + var rxVersion = _ref.rxVersion; + return (0, _cycleDom.h)('div', { style: wrapperStyle }, [(0, _rxmarblesStylesUtils.renderSvgDropshadow)(), renderHeader(), renderContent(route), renderFooter(appVersion, rxVersion)]); + }); +}; +},{"@cycle/dom":6,"rxmarbles/styles/colors":248,"rxmarbles/styles/dimens":249,"rxmarbles/styles/fonts":250,"rxmarbles/styles/utils":251}],229:[function(require,module,exports){ +'use strict'; + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +function createContainerStyle(inputStyle) { + return { + display: 'inline-block', + position: 'relative', + width: 'calc(8 * ' + inputStyle.thickness + ')', + height: inputStyle.height, + margin: '0 calc(-4 * ' + inputStyle.thickness + ')' + }; +} + +function createInnerStyle(inputStyle) { + return { + width: inputStyle.thickness, + height: '50%', + marginLeft: 'calc(3.5 * ' + inputStyle.thickness + ')', + marginTop: 'calc(' + inputStyle.height + ' / 4.0)', + backgroundColor: inputStyle.color + }; +} + +function render(time, isDraggable, isTall, inputStyle, isHighlighted) { + var draggableContainerStyle = { + cursor: 'ew-resize' + }; + var innerTallStyle = { + height: '100%', + marginTop: 0 + }; + var containerStyle = createContainerStyle(inputStyle); + var innerStyle = createInnerStyle(inputStyle); + return (0, _cycleDom.h)('div.completionRoot', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ + left: time + '%' }, containerStyle, isDraggable ? draggableContainerStyle : {}) + }, [(0, _cycleDom.h)('div.completionInner', { + style: (0, _rxmarblesStylesUtils.mergeStyles)(innerStyle, isDraggable && isHighlighted ? _rxmarblesStylesUtils.elevation1Style : null, isTall ? innerTallStyle : null) + })]); +} + +function diagramCompletionComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var startHighlight$ = DOM.get('.completionRoot', 'mouseenter'); + var stopHighlight$ = DOM.get('.completionRoot', 'mouseleave'); + var time$ = props.get('time').startWith(100); + var isDraggable$ = props.get('isDraggable').startWith(false); + var isTall$ = props.get('isTall').startWith(false); + var style$ = props.get('style').startWith({ + thickness: '2px', + height: '10px', + color: 'black' + }); + var isHighlighted$ = _cycleCore.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _cycleCore.Rx.Observable.combineLatest(time$, isDraggable$, isTall$, style$, isHighlighted$, render); + + return { + DOM: vtree$ + }; +} + +module.exports = diagramCompletionComponent; +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/utils":251}],230:[function(require,module,exports){ +'use strict'; + +var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var mouseMove$ = _cycleCore.Rx.Observable.fromEvent(document, 'mousemove'); +var mouseUp$ = _cycleCore.Rx.Observable.fromEvent(document, 'mouseup'); + +function getPxToPercentageRatio(element) { + var pxToPercentage = undefined; + try { + if (element && element.parentElement && element.parentElement.clientWidth) { + pxToPercentage = 100.0 / element.parentElement.clientWidth; + } else { + throw new Error('Invalid marble parent or parent width.'); + } + } catch (err) { + console.warn(err); + pxToPercentage = 0.15; // a 'safe enough' magic number + } + return pxToPercentage; +} + +function makeDeltaTime$(mouseDown$, resultFn) { + return mouseDown$.map(function (downevent) { + var target = downevent.currentTarget; + var pxToPercentage = getPxToPercentageRatio(target); + return mouseMove$.takeUntil(mouseUp$).pairwise().map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2); + + var ev1 = _ref2[0]; + var ev2 = _ref2[1]; + + var dx = ev2.pageX - ev1.pageX; // the drag dx in pixels + var deltaTime = dx * pxToPercentage; + if (!!resultFn) { + return resultFn(deltaTime, target); + } else { + return deltaTime; + } + }).filter(function (x) { + return x !== 0; + }); + }).concatAll(); +} + +function diagramIntent(DOM) { + var marbleMouseDown$ = DOM.get('.diagramMarble', 'mousedown'); + var completionMouseDown$ = DOM.get('.diagramCompletion', 'mousedown'); + + return { + changeMarbleTime$: makeDeltaTime$(marbleMouseDown$, function (deltaTime, target) { + return _immutable2['default'].Map({ + deltaTime: deltaTime, + id: target.attributes['data-marble-id'].value + }); + }), + changeEndTime$: makeDeltaTime$(completionMouseDown$) + }; +} + +module.exports = diagramIntent; +},{"@cycle/core":1,"immutable":118}],231:[function(require,module,exports){ +'use strict'; + +var _cycleCore = require('@cycle/core'); + +function findLargestMarbleTime(diagramData) { + return diagramData.get('notifications').max(function (notifA, notifB) { + if (notifA.get('time') < notifB.get('time')) { + return -1; + } + if (notifA.get('time') > notifB.get('time')) { + return 1; + } + return 0; + }).get('time'); +} + +function applyChangeMarbleTime(diagramData, marbleDelta) { + return diagramData.set('notifications', diagramData.get('notifications').map(function (notif) { + if (String(notif.get('id')) === String(marbleDelta.get('id'))) { + var newTime = notif.get('time') + marbleDelta.get('deltaTime'); + return notif.set('time', newTime); + } else { + return notif; + } + })); +} + +function applyChangeEndTime(diagramData, endDelta) { + return diagramData.set('end', diagramData.get('end') + endDelta); +} + +function applyMarbleDataConstraints(marbleData) { + var newTime = marbleData.get('time'); + newTime = Math.round(newTime); + newTime = Math.min(newTime, 100); + newTime = Math.max(0, newTime); + return marbleData.set('time', newTime); +} + +function applyEndTimeConstraint(diagramData) { + var largestMarbleTime = findLargestMarbleTime(diagramData); + var newEndTime = diagramData.get('end'); + newEndTime = Math.max(newEndTime, largestMarbleTime); + newEndTime = Math.round(newEndTime); + newEndTime = Math.min(newEndTime, 100); + newEndTime = Math.max(0, newEndTime); + return diagramData.set('end', newEndTime); +} + +function applyDiagramDataConstraints(diagramData) { + var newDiagramData = diagramData.set('notifications', diagramData.get('notifications').map(applyMarbleDataConstraints)); + newDiagramData = applyEndTimeConstraint(newDiagramData); + return newDiagramData; +} + +function makeNewDiagramData$(data$, changeMarbleTime$, changeEndTime$, interactive$) { + var mod$ = _cycleCore.Rx.Observable.merge(changeMarbleTime$.map(function (x) { + return function (data) { + return applyChangeMarbleTime(data, x); + }; + }), changeEndTime$.map(function (x) { + return function (data) { + return applyChangeEndTime(data, x); + }; + })).pausable(interactive$); + return data$.flatMapLatest(function (data) { + return mod$.scan(data, function (acc, mod) { + return mod(acc); + }); + }).map(applyDiagramDataConstraints); +} + +function diagramModel(props, intent) { + var data$ = props.get('data').distinctUntilChanged().shareReplay(1); + return { + data$: data$, + newData$: makeNewDiagramData$(data$, intent.changeMarbleTime$, intent.changeEndTime$, props.get('interactive')), + isInteractive$: props.get('interactive').startWith(false) + }; +} + +module.exports = diagramModel; +},{"@cycle/core":1}],232:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesStylesFonts = require('rxmarbles/styles/fonts'); + +var _rxmarblesStylesFonts2 = _interopRequireDefault(_rxmarblesStylesFonts); + +var _rxtween = require('rxtween'); + +var _rxtween2 = _interopRequireDefault(_rxtween); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +var MARBLE_WIDTH = 5; // estimate of a marble width, in percentages +var diagramSidePadding = _rxmarblesStylesDimens2['default'].spaceMedium; +var diagramVerticalMargin = _rxmarblesStylesDimens2['default'].spaceLarge; +var diagramArrowThickness = '2px'; +var diagramArrowSidePadding = _rxmarblesStylesDimens2['default'].spaceLarge; +var diagramArrowHeadSize = '8px'; +var diagramArrowColor = _rxmarblesStylesColors2['default'].black; +var diagramMarbleSize = _rxmarblesStylesDimens2['default'].spaceLarge; +var diagramCompletionHeight = '44px'; + +var diagramStyle = (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'relative', + display: 'block', + width: '100%', + height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin + ')', + overflow: 'visible', + cursor: 'default' }, _rxmarblesStylesUtils.textUnselectable); + +var diagramBodyStyle = { + position: 'absolute', + left: 'calc(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + '\n + (' + diagramMarbleSize + ' / 2))', + right: 'calc(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + '\n + (' + diagramMarbleSize + ' / 2))', + top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', + height: diagramCompletionHeight, + marginTop: 'calc(0px - (' + diagramCompletionHeight + ' / 2))' +}; + +function renderMarble(marbleData) { + var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + return (0, _cycleDom.h)('x-marble.diagramMarble', { + key: 'marble' + marbleData.get('id'), + data: marbleData, + isDraggable: isDraggable, + style: { size: diagramMarbleSize } + }); +} + +function renderCompletion(diagramData) { + var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var endTime = diagramData.get('end'); + var isTall = diagramData.get('notifications').some(function (marbleData) { + return Math.abs(marbleData.get('time') - diagramData.get('end')) <= MARBLE_WIDTH * 0.5; + }); + return (0, _cycleDom.h)('x-diagram-completion.diagramCompletion', { + key: 'completion', + time: endTime, + isDraggable: isDraggable, + isTall: isTall, + style: { + thickness: diagramArrowThickness, + color: diagramArrowColor, + height: diagramCompletionHeight + } + }); +} + +function renderDiagramArrow() { + return (0, _cycleDom.h)('div.diagramArrow', { style: { + backgroundColor: diagramArrowColor, + height: diagramArrowThickness, + position: 'absolute', + top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', + left: diagramSidePadding, + right: diagramSidePadding + } }); +} + +function renderDiagramArrowHead() { + return (0, _cycleDom.h)('div.diagramArrowHead', { style: { + width: 0, + height: 0, + borderTop: diagramArrowHeadSize + ' solid transparent', + borderBottom: diagramArrowHeadSize + ' solid transparent', + borderLeft: 'calc(2 * ' + diagramArrowHeadSize + ') solid ' + diagramArrowColor, + display: 'inline-block', + right: 'calc(' + diagramSidePadding + ' - 1px)', + position: 'absolute', + top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2)\n - ' + diagramArrowHeadSize + ' + (' + diagramArrowThickness + ' / 2))' + } }); +} + +function renderDiagram(data, isInteractive) { + var marblesVTree = data.get('notifications').map(function (notification) { + return renderMarble(notification, isInteractive); + }).toArray(); // from Immutable.List + var completionVTree = renderCompletion(data, isInteractive); + return (0, _cycleDom.h)('div', { style: diagramStyle }, [renderDiagramArrow(), renderDiagramArrowHead(), (0, _cycleDom.h)('div', { style: diagramBodyStyle }, [completionVTree].concat(marblesVTree))]); +} + +function sanitizeDiagramItem(x) { + return Math.max(0, Math.min(100, x)); +} + +function interpolate(from, to, x) { + return from * (1 - x) + to * x; +} + +function animateData$(data$) { + var animConf = { + from: 0, + to: 1, + ease: _rxtween2['default'].Power3.easeOut, + duration: 600 + }; + return data$.flatMapLatest(function (data) { + if (!data.get('isFirst')) { + return _cycleCore.Rx.Observable.just(data); + } else { + var _ret = (function () { + var randomizedNotifs = data.get('notifications').map(function (notif) { + return notif.update('time', function (time) { + return time - 10 + 20 * Math.random(); + }); + }); + + return { + v: (0, _rxtween2['default'])(animConf).map(function (x) { + return data.update('notifications', function (notifications) { + return notifications.zipWith(function (n1, n2) { + return n1.update('time', function (t1) { + var t2 = n2.get('time'); + return interpolate(t2, t1, x); + }); + }, randomizedNotifs); + }); + }) + }; + })(); + + if (typeof _ret === 'object') return _ret.v; + } + }); +} + +function diagramView(model) { + return { + vtree$: _cycleCore.Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, renderDiagram) + }; +} + +module.exports = diagramView; +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":248,"rxmarbles/styles/dimens":249,"rxmarbles/styles/fonts":250,"rxmarbles/styles/utils":251,"rxtween":260}],233:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _rxmarblesComponentsDiagramDiagramModel = require('rxmarbles/components/diagram/diagram-model'); + +var _rxmarblesComponentsDiagramDiagramModel2 = _interopRequireDefault(_rxmarblesComponentsDiagramDiagramModel); + +var _rxmarblesComponentsDiagramDiagramView = require('rxmarbles/components/diagram/diagram-view'); + +var _rxmarblesComponentsDiagramDiagramView2 = _interopRequireDefault(_rxmarblesComponentsDiagramDiagramView); + +var _rxmarblesComponentsDiagramDiagramIntent = require('rxmarbles/components/diagram/diagram-intent'); + +var _rxmarblesComponentsDiagramDiagramIntent2 = _interopRequireDefault(_rxmarblesComponentsDiagramDiagramIntent); + +function DiagramComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var intent = (0, _rxmarblesComponentsDiagramDiagramIntent2['default'])(DOM); + var model = (0, _rxmarblesComponentsDiagramDiagramModel2['default'])(props, intent); + var view = (0, _rxmarblesComponentsDiagramDiagramView2['default'])(model); + + return { + DOM: view.vtree$, + events: { + newdata: model.newData$ + } + }; +} + +module.exports = DiagramComponent; +},{"rxmarbles/components/diagram/diagram-intent":230,"rxmarbles/components/diagram/diagram-model":231,"rxmarbles/components/diagram/diagram-view":232}],234:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +function createContainerStyle(inputStyle) { + return { + width: inputStyle.size, + height: inputStyle.size, + position: 'relative', + display: 'inline-block', + margin: 'calc(0px - (' + inputStyle.size + ' / 2))', + bottom: 'calc((100% - ' + inputStyle.size + ') / 2)', + cursor: 'default' + }; +} + +function renderSvg(data, isDraggable, inputStyle, isHighlighted) { + var POSSIBLE_COLORS = [_rxmarblesStylesColors2['default'].blue, _rxmarblesStylesColors2['default'].green, _rxmarblesStylesColors2['default'].yellow, _rxmarblesStylesColors2['default'].red]; + var color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + return (0, _cycleDom.svg)('svg.marbleShape', { + style: { + overflow: 'visible', + width: inputStyle.size, + height: inputStyle.size + }, + attributes: { viewBox: '0 0 1 1' } }, [(0, _cycleDom.svg)('circle', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ + stroke: _rxmarblesStylesColors2['default'].black, + fill: color + }, isDraggable && isHighlighted ? _rxmarblesStylesUtils.marbleElevation1Style : {}), + attributes: { + cx: 0.5, cy: 0.5, r: 0.47, + 'stroke-width': '0.06px' + } + })]); +} + +function renderInnerContent(data, inputStyle) { + return (0, _cycleDom.h)('p.marbleContent', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size }, _rxmarblesStylesUtils.textUnselectable) + }, '' + data.get('content')); +} + +function render(data, isDraggable, inputStyle, isHighlighted) { + var draggableContainerStyle = { + cursor: 'ew-resize' + }; + return (0, _cycleDom.h)('div.marbleRoot', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ + left: data.get('time') + '%', + zIndex: data.get('time') }, createContainerStyle(inputStyle), isDraggable ? draggableContainerStyle : null), + attributes: { 'data-marble-id': data.get('id') } + }, [renderSvg(data, isDraggable, inputStyle, isHighlighted), renderInnerContent(data, inputStyle)]); +} + +function marbleComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var startHighlight$ = DOM.get('.marbleRoot', 'mouseenter'); + var stopHighlight$ = DOM.get('.marbleRoot', 'mouseleave'); + var data$ = props.get('data'); + var isDraggable$ = props.get('isDraggable').startWith(false); + var style$ = props.get('style').startWith({}); + var isHighlighted$ = _cycleCore.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _cycleCore.Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, render); + + return { + DOM: vtree$ + }; +} + +module.exports = marbleComponent; +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":248,"rxmarbles/styles/utils":251}],235:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +function operatorsMenuLink(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var href$ = props.get('href'); + var content$ = props.get('content').startWith(''); + var isHighlighted$ = (0, _rxmarblesStylesUtils.makeIsHighlighted$)(DOM, '.link'); + var highlightingArrow = (0, _cycleDom.h)('span', { + style: { + display: 'inline-block', + position: 'absolute', + right: _rxmarblesStylesDimens2['default'].spaceTiny } + }, '❯'); + var vtree$ = _cycleCore.Rx.Observable.combineLatest(href$, content$, isHighlighted$, function (href, content, isHighlighted) { + return (0, _cycleDom.h)('a.link', { + style: (0, _rxmarblesStylesUtils.mergeStyles)({ + position: 'relative', + display: 'block', + color: _rxmarblesStylesColors2['default'].greyDark }, isHighlighted ? { color: _rxmarblesStylesColors2['default'].black } : null), + href: href }, [content, isHighlighted ? highlightingArrow : null]); + }); + + return { DOM: vtree$ }; +} + +module.exports = operatorsMenuLink; +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/styles/colors":248,"rxmarbles/styles/dimens":249,"rxmarbles/styles/utils":251}],236:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesDataExamples = require('rxmarbles/data/examples'); + +var _rxmarblesDataExamples2 = _interopRequireDefault(_rxmarblesDataExamples); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +var operatorsMenuCategoryStyle = { + textTransform: 'uppercase', + fontSize: '0.7em', + color: _rxmarblesStylesColors2['default'].grey, + marginTop: _rxmarblesStylesDimens2['default'].spaceMedium +}; + +var operatorsMenuItemStyle = { + color: _rxmarblesStylesColors2['default'].greyDark, + fontSize: '1rem', + lineHeight: '1.6rem' +}; + +function renderExampleItem(example) { + return (0, _cycleDom.h)('li', { style: operatorsMenuItemStyle }, (0, _cycleDom.h)('x-operators-menu-link', { + key: 'operatorsMenuLink' + example.key, + href: '#' + example.key, + content: example.key + })); +} + +function renderExampleItems(examples) { + var items = []; + for (var i = 0; i < examples.length; i++) { + var example = examples[i]; + items.push(renderExampleItem(example)); + } + return items; +} + +function renderExampleCategory(categoryName, isFirstCategory) { + return (0, _cycleDom.h)('li', { + style: (0, _rxmarblesStylesUtils.mergeStyles)(operatorsMenuCategoryStyle, isFirstCategory ? { marginTop: '0' } : {}) }, '' + categoryName); +} + +function renderMenuByCategory(categoryMap) { + var listItems = []; + var isFirstCategory = true; + for (var categoryName in categoryMap) { + if (!categoryMap.hasOwnProperty(categoryName)) continue; + listItems.push(renderExampleCategory(categoryName, isFirstCategory)); + listItems = listItems.concat(renderExampleItems(categoryMap[categoryName])); + isFirstCategory = false; + } + listItems.push((0, _cycleDom.h)('li', { style: operatorsMenuCategoryStyle }, 'More')); + listItems.push((0, _cycleDom.h)('li', { style: operatorsMenuItemStyle }, 'Coming soon...')); + return listItems; +} + +function renderSwitchItem(key, label, isActive, isHighlighted) { + return (0, _cycleDom.h)('div.switch.' + key, { + style: { + cursor: 'pointer', + float: 'left', + 'padding-right': '10px', + 'box-sizing': 'border-box', + 'text-align': 'left', + color: isHighlighted ? _rxmarblesStylesColors2['default'].greyDark : _rxmarblesStylesColors2['default'].grey, + 'text-decoration': 'underline' + } }, label); +} + +function renderMenu(byCategory, byCategoryIsHighlighted, byAlphabetIsHighlighted) { + var menuItemsByCategory = renderMenuByCategory(_rxmarblesDataExamples2['default'].byCategory); + var menuItemsByAlphabet = renderExampleItems(_rxmarblesDataExamples2['default'].byAlphabet); + return (0, _cycleDom.h)('div', {}, [(0, _cycleDom.h)('div', { style: { + paddingRight: '36px', + boxSizing: 'border-box', + // 100px is the estimated header page row height + height: 'calc(100vh - 100px)' } }, [(0, _cycleDom.h)('div', {}, [renderSwitchItem('byAlphabet', 'by Name', !byCategory, byAlphabetIsHighlighted), renderSwitchItem('byCategory', 'by Category', byCategory, byCategoryIsHighlighted)]), (0, _cycleDom.h)('div', { style: { clear: 'both' } }), (0, _cycleDom.h)('ul', { style: { + margin: '0', + 'margin-top': _rxmarblesStylesDimens2['default'].spaceSmall, + padding: '0', + listStyleType: 'none', + overflowY: 'scroll', + height: '100%' } }, byCategory ? menuItemsByCategory : menuItemsByAlphabet)])]); +} + +function operatorsMenuComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var switchMouseDown$ = DOM.get('.switch', 'mousedown'); + var showItemsByCategory$ = switchMouseDown$.map(function (ev) { + return ev.currentTarget.className.indexOf('byCategory') >= 0; + }).startWith(true); + var byCategoryIsHighlighted$ = (0, _rxmarblesStylesUtils.makeIsHighlighted$)(DOM, '.byCategory'); + var byAlphabetIsHighlighted$ = (0, _rxmarblesStylesUtils.makeIsHighlighted$)(DOM, '.byAlphabet'); + + return { + DOM: _cycleCore.Rx.Observable.combineLatest(showItemsByCategory$, byCategoryIsHighlighted$, byAlphabetIsHighlighted$, renderMenu) + }; +} + +module.exports = operatorsMenuComponent; +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/data/examples":244,"rxmarbles/styles/colors":248,"rxmarbles/styles/dimens":249,"rxmarbles/styles/utils":251}],237:[function(require,module,exports){ +/* + * Functions to handle data of input diagrams in the example shown in the + * sandbox. + */ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _rxmarblesComponentsSandboxUtils = require('rxmarbles/components/sandbox/utils'); + +var _rxmarblesComponentsSandboxUtils2 = _interopRequireDefault(_rxmarblesComponentsSandboxUtils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function getNotifications(diagram) { + var last = diagram[diagram.length - 1]; + if (typeof last === 'number') { + return _immutable2['default'].List(diagram.slice(0, -1)); + } else { + return _immutable2['default'].List(diagram); + } +} + +function prepareNotification(input, diagramId) { + if (input && input.get && typeof input.get('time') !== 'undefined') { + return input; // is already a prepared notification + } + return _immutable2['default'].Map({}).set('time', input.t).set('content', input.d).set('diagramId', diagramId).set('id', _rxmarblesComponentsSandboxUtils2['default'].calculateNotificationHash({ time: input.t, content: input.d })); +} + +function prepareInputDiagram(diagram) { + var indexInDiagramArray = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + var last = diagram[diagram.length - 1]; + return _immutable2['default'].Map({}).set('notifications', getNotifications(diagram).map(function (notification) { + return prepareNotification(notification, indexInDiagramArray); + })).set('end', typeof last === 'number' ? last : 100).set('id', indexInDiagramArray); +} + +function augmentWithExampleKey(diagramData, exampleKey) { + return diagramData.set('example', exampleKey).set('notifications', diagramData.get('notifications').map(function (notif) { + return notif.set('example', exampleKey); + })); +} + +function replaceDiagramDataIn(diagrams, newDiagramData) { + return diagrams.map(function (diagramData) { + if (diagramData.get('id') === newDiagramData.get('id')) { + return newDiagramData; + } else { + return diagramData; + } + }); +} + +function makeNewInputDiagramsData$(changeInputDiagram$, inputs$) { + return inputs$.flatMapLatest(function (inputs) { + return changeInputDiagram$.scan(inputs, function (acc, newDiagramData) { + return acc.set('diagrams', replaceDiagramDataIn(acc.get('diagrams'), newDiagramData)); + }); + }); +} + +module.exports = { + prepareInputDiagram: prepareInputDiagram, + augmentWithExampleKey: augmentWithExampleKey, + makeNewInputDiagramsData$: makeNewInputDiagramsData$ +}; +},{"@cycle/core":1,"immutable":118,"rxmarbles/components/sandbox/utils":240}],238:[function(require,module,exports){ +/* + * Functions to handle data of the output diagram in the example shown in the + * sandbox. + */ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _rxmarblesComponentsSandboxUtils = require('rxmarbles/components/sandbox/utils'); + +var _rxmarblesComponentsSandboxUtils2 = _interopRequireDefault(_rxmarblesComponentsSandboxUtils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var MAX_VT_TIME = 100; // Time of completion + +function makeScheduler() { + var scheduler = new _cycleCore.Rx.VirtualTimeScheduler(0, function (x, y) { + if (x > y) { + return 1; + } + if (x < y) { + return -1; + } + return 0; + }); + scheduler.add = function (absolute, relative) { + return absolute + relative; + }; + scheduler.toDateTimeOffset = function (absolute) { + return Math.floor(absolute); + }; + scheduler.toRelative = function (timeSpan) { + return timeSpan; + }; + return scheduler; +} + +function justIncomplete(item, scheduler) { + return new _cycleCore.Rx.AnonymousObservable(function (observer) { + return scheduler.schedule(function () { + observer.onNext(item); + }); + }); +} + +/** + * Creates an (virtual time) Rx.Observable from diagram + * data (array of data items). + */ +function toVTStream(diagramData, scheduler) { + var singleMarbleStreams = diagramData.get('notifications').map(function (item) { + return justIncomplete(item, scheduler).delay(item.get('time'), scheduler); + }).toArray(); + // Necessary correction to include marbles at time exactly diagramData.end: + var correctedEndTime = diagramData.get('end') + 0.01; + return _cycleCore.Rx.Observable.merge(singleMarbleStreams).takeUntilWithTime(correctedEndTime, scheduler).publish().refCount(); +} + +function getDiagramPromise(stream, scheduler) { + var diagram = {}; + var subject = new _cycleCore.Rx.BehaviorSubject([]); + stream.observeOn(scheduler).timestamp(scheduler).map(function (x) { + if (typeof x.value !== 'object') { + x.value = _immutable2['default'].Map({ + content: x.value, + id: _rxmarblesComponentsSandboxUtils2['default'].calculateNotificationContentHash(x.value) + }); + } + // converts timestamp to % of MAX_VT_TIME + return x.value.set('time', x.timestamp / MAX_VT_TIME * 100); + }).reduce(function (acc, x) { + acc.push(x); + return acc; + }, []).subscribe(function onNext(x) { + diagram.notifications = x; + subject.onNext(diagram); + }, function onError(e) { + console.warn('Error in the diagram promise stream: ' + e); + }, function onComplete() { + diagram.end = scheduler.now(); + }); + return subject.asObservable(); +} + +function toImmutableDiagramData(diagramData) { + return _immutable2['default'].Map({}).set('notifications', _immutable2['default'].List(diagramData.notifications).map(_immutable2['default'].Map)).set('end', diagramData.end); +} + +function getOutputDiagram$(example$, inputDiagrams$) { + return inputDiagrams$.withLatestFrom(example$, function (diagrams, example) { + var vtscheduler = makeScheduler(); + var inputVTStreams = diagrams.get('diagrams').map(function (diagram) { + return toVTStream(diagram, vtscheduler); + }); + var outputVTStream = example.get('apply')(inputVTStreams, vtscheduler); + // Necessary hack to include marbles at exactly 100.01 + var correctedMaxTime = MAX_VT_TIME + 0.02; + outputVTStream = outputVTStream.takeUntilWithTime(correctedMaxTime, vtscheduler); + var outputDiagram = getDiagramPromise(outputVTStream, vtscheduler, MAX_VT_TIME); + vtscheduler.start(); + return outputDiagram.map(toImmutableDiagramData); + }).mergeAll(); +} + +module.exports = { + getOutputDiagram$: getOutputDiagram$ +}; +},{"@cycle/core":1,"immutable":118,"rxmarbles/components/sandbox/utils":240}],239:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleDom = require('@cycle/dom'); + +var _rxtween = require('rxtween'); + +var _rxtween2 = _interopRequireDefault(_rxtween); + +var _rxmarblesDataExamples = require('rxmarbles/data/examples'); + +var _rxmarblesDataExamples2 = _interopRequireDefault(_rxmarblesDataExamples); + +var _rxmarblesComponentsSandboxSandboxInput = require('rxmarbles/components/sandbox/sandbox-input'); + +var _rxmarblesComponentsSandboxSandboxOutput = require('rxmarbles/components/sandbox/sandbox-output'); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var _rxmarblesStylesColors = require('rxmarbles/styles/colors'); + +var _rxmarblesStylesColors2 = _interopRequireDefault(_rxmarblesStylesColors); + +var _rxmarblesStylesDimens = require('rxmarbles/styles/dimens'); + +var _rxmarblesStylesDimens2 = _interopRequireDefault(_rxmarblesStylesDimens); + +var _rxmarblesStylesFonts = require('rxmarbles/styles/fonts'); + +var _rxmarblesStylesFonts2 = _interopRequireDefault(_rxmarblesStylesFonts); + +var _rxmarblesStylesUtils = require('rxmarbles/styles/utils'); + +function renderOperatorLabel(label) { + var fontSize = label.length >= 45 ? 1.3 : label.length >= 30 ? 1.5 : 2; + var style = { + fontFamily: _rxmarblesStylesFonts2['default'].fontCode, + fontWeight: '400', + fontSize: fontSize + 'rem' + }; + return (0, _cycleDom.h)('span.operatorLabel', { style: style }, label); +} + +function renderOperator(label) { + var style = (0, _rxmarblesStylesUtils.mergeStyles)({ + border: '1px solid rgba(0,0,0,0.06)', + padding: _rxmarblesStylesDimens2['default'].spaceMedium, + textAlign: 'center' }, _rxmarblesStylesUtils.elevation2Style); + return (0, _cycleDom.h)('div.operatorBox', { style: style }, [_rxmarblesStylesUtils.elevation2Before, renderOperatorLabel(label), _rxmarblesStylesUtils.elevation2After]); +} + +function getSandboxStyle(width) { + return (0, _rxmarblesStylesUtils.mergeStyles)({ + background: _rxmarblesStylesColors2['default'].white, + width: width, + borderRadius: '2px' }, _rxmarblesStylesUtils.elevation1Style); +} + +function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { + return (0, _cycleDom.h)('div.sandboxRoot', { style: getSandboxStyle(width) }, [inputDiagrams.get('diagrams').map(function (diagram, index) { + return (0, _cycleDom.h)('x-diagram.sandboxInputDiagram', { + key: 'inputDiagram' + index, + data: diagram, + interactive: true + }); + }), renderOperator(operatorLabel), (0, _cycleDom.h)('x-diagram.sandboxOutputDiagram', { + key: 'outputDiagram', + data: outputDiagram, + interactive: false + })]); +} + +function makeInputDiagrams(example) { + return _immutable2['default'].Map({ + 'diagrams': example.get('inputs').map(_rxmarblesComponentsSandboxSandboxInput.prepareInputDiagram).map(function (diag) { + return (0, _rxmarblesComponentsSandboxSandboxInput.augmentWithExampleKey)(diag, example.get('key')); + }) + }); +} + +function markAsFirstDiagram(diagram) { + return diagram.set('isFirst', true); +} + +function markAllDiagramsAsFirst(diagramsData) { + return diagramsData.update('diagrams', function (diagrams) { + return diagrams.map(markAsFirstDiagram); + }); +} + +var isTruthy = function isTruthy(x) { + return !!x; +}; + +function sandboxComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var changeInputDiagram$ = DOM.get('.sandboxInputDiagram', 'newdata').map(function (ev) { + return ev.detail; + }); + var width$ = props.get('width').startWith('100%'); + var example$ = props.get('route').filter(isTruthy).map(function (key) { + return _immutable2['default'].Map(_rxmarblesDataExamples2['default'][key]).set('key', key); + }).shareReplay(1); + var inputDiagrams$ = example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1); + var newInputDiagrams$ = (0, _rxmarblesComponentsSandboxSandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$, inputDiagrams$); + var operatorLabel$ = example$.map(function (example) { + return example.get('label'); + }); + var firstOutputDiagram$ = (0, _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$, inputDiagrams$).map(markAsFirstDiagram); + var newOutputDiagram$ = (0, _rxmarblesComponentsSandboxSandboxOutput.getOutputDiagram$)(example$, newInputDiagrams$); + var outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); + var vtree$ = _cycleCore.Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, renderSandbox); + + return { + DOM: vtree$ + }; +} + +module.exports = sandboxComponent; +},{"@cycle/core":1,"@cycle/dom":6,"immutable":118,"rxmarbles/components/sandbox/sandbox-input":237,"rxmarbles/components/sandbox/sandbox-output":238,"rxmarbles/data/examples":244,"rxmarbles/styles/colors":248,"rxmarbles/styles/dimens":249,"rxmarbles/styles/fonts":250,"rxmarbles/styles/utils":251,"rxtween":260}],240:[function(require,module,exports){ +/* + * Conversion from virtual time streams out to diagram data, and + * vice-versa, and related functions. + */ + +"use strict"; + +function calculateNotificationContentHash(content) { + var SMALL_PRIME_1 = 59; + var SMALL_PRIME_2 = 97; + var SOME_PRIME_NUMBER = 877; + if (typeof content === "string") { + return content.split("").map(function (x) { + return x.charCodeAt(0); + }).reduce(function (x, y) { + return x * SMALL_PRIME_1 + y * SMALL_PRIME_2; + }); + } else if (typeof content === "number") { + return parseInt(content) * SOME_PRIME_NUMBER; + } else if (typeof content === 'boolean') { + return content ? SOME_PRIME_NUMBER : SOME_PRIME_NUMBER * 3; + } +} + +function calculateNotificationHash(marbleData) { + var SMALL_PRIME = 7; + var LARGE_PRIME = 1046527; + var MAX = 100000; + var contentHash = calculateNotificationContentHash(marbleData.content); + return (marbleData.time + contentHash + SMALL_PRIME) * LARGE_PRIME % MAX; +} + +module.exports = { + calculateNotificationHash: calculateNotificationHash, + calculateNotificationContentHash: calculateNotificationContentHash +}; +},{}],241:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + "every": { + "label": "every(x => x < 10)", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }, { t: 35, d: 4 }, { t: 65, d: 5 }, 80]], + "apply": function apply(inputs) { + return inputs[0].every(function (x) { + return x.get('content') < 10; + }); + } + }, + + "some": { + "label": "some(x => x > 10)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }]], + "apply": function apply(inputs) { + return inputs[0].some(function (x) { + return x.get('content') > 10; + }); + } + }, + + "includes": { + "label": "includes(22)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }]], + "apply": function apply(inputs) { + return inputs[0].map(function (x) { + return x.get('content'); + }).includes(22); + } + }, + + "sequenceEqual": { + "label": "sequenceEqual", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }, { t: 35, d: 4 }, { t: 65, d: 5 }, 85], [{ t: 2, d: 1 }, { t: 20, d: 2 }, { t: 40, d: 3 }, { t: 70, d: 4 }, { t: 77, d: 5 }, 85]], + "apply": function apply(inputs) { + return inputs[0].sequenceEqual(inputs[1], function (x, y) { + return x.get('content') === y.get('content'); + }); + } + } +}; +},{"@cycle/core":1}],242:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + "combineLatest": { + "label": "combineLatest((x, y) => \"\" + x + y)", + "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }]], + "apply": function apply(inputs) { + return _cycleCore.Rx.Observable.combineLatest(inputs[0], inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + }, + + "concat": { + "label": "concat", + "inputs": [[{ t: 0, d: 1 }, { t: 15, d: 1 }, { t: 50, d: 1 }, 57], [{ t: 0, d: 2 }, { t: 8, d: 2 }, 12]], + "apply": function apply(inputs) { + return _cycleCore.Rx.Observable.concat(inputs); + } + }, + + "merge": { + "label": "merge", + "inputs": [[{ t: 0, d: 20 }, { t: 15, d: 40 }, { t: 30, d: 60 }, { t: 45, d: 80 }, { t: 60, d: 100 }], [{ t: 37, d: 1 }, { t: 68, d: 1 }]], + "apply": function apply(inputs) { + return _cycleCore.Rx.Observable.merge(inputs); + } + }, + + "sample": { + "label": "sample", + "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 40, d: 3 }, { t: 60, d: 4 }, { t: 80, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 33, d: "C" }, { t: 70, d: "D" }, 90]], + "apply": function apply(inputs) { + return inputs[0].sample(inputs[1]); + } + }, + + "startWith": { + "label": "startWith(1)", + "inputs": [[{ t: 30, d: 2 }, { t: 40, d: 3 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].startWith(scheduler, 1); + } + }, + + "withLatestFrom": { + "label": "withLatestFrom((x, y) => \"\" + x + y)", + "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }]], + "apply": function apply(inputs) { + return inputs[0].withLatestFrom(inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + }, + + "zip": { + "label": "zip", + "inputs": [[{ t: 0, d: 1 }, { t: 20, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, { t: 92, d: 5 }], [{ t: 10, d: "A" }, { t: 25, d: "B" }, { t: 50, d: "C" }, { t: 57, d: "D" }]], + "apply": function apply(inputs) { + return _cycleCore.Rx.Observable.zip(inputs[0], inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + } +}; +},{"@cycle/core":1}],243:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + "amb": { + "label": "amb", + "inputs": [[{ t: 10, d: 20 }, { t: 20, d: 40 }, { t: 30, d: 60 }], [{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }], [{ t: 20, d: 0 }, { t: 32, d: 0 }, { t: 44, d: 0 }]], + "apply": function apply(inputs) { + return _cycleCore.Rx.Observable.amb(inputs); + } + } +}; +},{"@cycle/core":1}],244:[function(require,module,exports){ +/* + * The database of all predefined examples in the app. + */ +'use strict'; + +var transformExamples = require('rxmarbles/data/transform-examples'); +var combineExamples = require('rxmarbles/data/combine-examples'); +var filterExamples = require('rxmarbles/data/filter-examples'); +var mathExamples = require('rxmarbles/data/math-examples'); +var booleanExamples = require('rxmarbles/data/boolean-examples'); +var conditionalExamples = require('rxmarbles/data/conditional-examples'); +var sortBy = require('lodash/sortBy'); + +function merge() { + var args = 1 <= arguments.length ? Array.prototype.slice.call(arguments) : []; + var result = {}; + for (var i = 0; i < args.length; i++) { + var object = args[i]; + for (var name in object) { + if (!object.hasOwnProperty(name)) continue; + result[name] = object[name]; + } + } + return result; +}; + +function applyCategory(examples, categoryName) { + for (var key in examples) { + if (!examples.hasOwnProperty(key)) continue; + examples[key]["category"] = categoryName; + } + return examples; +}; + +/** + * Returns a hashmap of category headers to lists of examples in that category. + */ +function organizeExamplesByCategory(examples) { + var categoryMap = {}; + for (var key in examples) { + if (!examples.hasOwnProperty(key)) continue; + var value = examples[key]; + value.key = key; + if (categoryMap.hasOwnProperty(value.category)) { + categoryMap[value.category].push(value); + } else { + categoryMap[value.category] = [value]; + } + } + return categoryMap; +} + +function organizeExamplesByAlphabet(examples) { + var array = []; + for (var key in examples) { + if (!examples.hasOwnProperty(key)) continue; + var value = examples[key]; + array.push(value); + } + return sortBy(array, 'key'); +} + +var examples = merge(applyCategory(transformExamples, "Transforming Operators"), applyCategory(combineExamples, "Combining Operators"), applyCategory(filterExamples, "Filtering Operators"), applyCategory(mathExamples, "Mathematical Operators"), applyCategory(booleanExamples, "Boolean Operators"), applyCategory(conditionalExamples, "Conditional Operators")); + +examples.byCategory = organizeExamplesByCategory(examples); +examples.byAlphabet = organizeExamplesByAlphabet(examples); + +module.exports = examples; +},{"lodash/sortBy":220,"rxmarbles/data/boolean-examples":241,"rxmarbles/data/combine-examples":242,"rxmarbles/data/conditional-examples":243,"rxmarbles/data/filter-examples":245,"rxmarbles/data/math-examples":246,"rxmarbles/data/transform-examples":247}],245:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + "distinct": { + "label": "distinct", + "inputs": [[{ t: 5, d: 1 }, { t: 20, d: 2 }, { t: 35, d: 2 }, { t: 60, d: 1 }, { t: 70, d: 3 }]], + "apply": function apply(inputs) { + return inputs[0].distinct(function (x) { + return x.get('content'); + }); + } + }, + + "distinctUntilChanged": { + "label": "distinctUntilChanged", + "inputs": [[{ t: 5, d: 1 }, { t: 20, d: 2 }, { t: 35, d: 2 }, { t: 60, d: 1 }, { t: 70, d: 3 }]], + "apply": function apply(inputs) { + return inputs[0].distinctUntilChanged(function (x) { + return x.get('content'); + }); + } + }, + + "elementAt": { + "label": "elementAt(2)", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].elementAt(2); + } + }, + + "filter": { + "label": "filter(x => x > 10)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }]], + "apply": function apply(inputs) { + return inputs[0].filter(function (x) { + return x.get('content') > 10; + }); + } + }, + + "find": { + "label": "find(x => x > 10)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].find(function (x) { + return x.get('content') > 10; + }); + } + }, + + "first": { + "label": "first", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, 85]], + "apply": function apply(inputs) { + return inputs[0].first(); + } + }, + + "last": { + "label": "last", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, 85]], + "apply": function apply(inputs) { + return inputs[0].last(); + } + }, + + "pausable": { + "label": "pausable", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }]], + "apply": function apply(inputs) { + inputs[0].subscribe(function () { + return 0; + }); + var subject = new _cycleCore.Rx.Subject(); + inputs[1].subscribe(function (x) { + return subject.onNext(x.get('content')); + }); + return inputs[0].pausable(subject); + } + }, + + "pausableBuffered": { + "label": "pausableBuffered", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }]], + "apply": function apply(inputs) { + inputs[0].subscribe(function () { + return 0; + }); + var subject = new _cycleCore.Rx.Subject(); + inputs[1].subscribe(function (x) { + return subject.onNext(x.get('content')); + }); + return inputs[0].pausableBuffered(subject); + } + }, + + "skip": { + "label": "skip(2)", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }]], + "apply": function apply(inputs) { + return inputs[0].skip(2); + } + }, + + "skipLast": { + "label": "skipLast(2)", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }]], + "apply": function apply(inputs) { + return inputs[0].skipLast(2); + } + }, + + "skipUntil": { + "label": "skipUntil", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 45, d: 0 }, { t: 73, d: 0 }]], + "apply": function apply(inputs) { + return inputs[0].skipUntil(inputs[1]); + } + }, + + "take": { + "label": "take(2)", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, 85]], + "apply": function apply(inputs, scheduler) { + return inputs[0].take(2, scheduler); + } + }, + + "takeLast": { + "label": "takeLast(1)", + "inputs": [[{ t: 30, d: 1 }, { t: 40, d: 2 }, { t: 65, d: 3 }, { t: 75, d: 4 }, 85]], + "apply": function apply(inputs) { + return inputs[0].takeLast(1); + } + }, + + "takeUntil": { + "label": "takeUntil", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, { t: 30, d: 4 }, { t: 40, d: 5 }, { t: 50, d: 6 }, { t: 60, d: 7 }, { t: 70, d: 8 }, { t: 80, d: 9 }], [{ t: 45, d: 0 }, { t: 73, d: 0 }]], + "apply": function apply(inputs) { + return inputs[0].takeUntil(inputs[1]); + } + } +}; +},{"@cycle/core":1}],246:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + // A clone of scan? + // "aggregate": { + // "label": "aggregate((x, y) => x + y)" + // "inputs": [ + // [{t:5, d:1}, {t:15, d:2}, {t:25, d:3}, {t:35, d:4}, {t:65, d:5}] + // ] + // "apply": (inputs) -> inputs[0].aggregate((x, y) -> + // return {content: x.content + y.content, time: x.time, id: x.id+y.id} + // ) + // } + + "average": { + "label": "average", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 30, d: 2 }, { t: 50, d: 2 }, { t: 65, d: 5 }, 80]], + "apply": function apply(inputs) { + return inputs[0].average(function (x) { + return x.get('content'); + }); + } + }, + + "count": { + "label": "count(x => x > 10)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }, 80]], + "apply": function apply(inputs) { + return inputs[0].count(function (x) { + return x.get('content') > 10; + }); + } + }, + + "max": { + "label": "max", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }, 80]], + "apply": function apply(inputs) { + return inputs[0].max(function (x, y) { + if (x.get('content') > y.get('content')) { + return 1; + } + if (x.get('content') < y.get('content')) { + return -1; + } + return 0; + }); + } + }, + + "min": { + "label": "min", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }, 80]], + "apply": function apply(inputs) { + return inputs[0].min(function (x, y) { + if (x.get('content') > y.get('content')) { + return 1; + } + if (x.get('content') < y.get('content')) { + return -1; + } + return 0; + }); + } + }, + + "reduce": { + "label": "reduce((x, y) => x + y)", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }, { t: 35, d: 4 }, { t: 65, d: 5 }, 80]], + "apply": function apply(inputs) { + return inputs[0].reduce(function (x, y) { + return y.set('content', x.get('content') + y.get('content')).set('id', x.get('id') + y.get('id')); + }); + } + }, + + "sum": { + "label": "sum", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }, { t: 35, d: 4 }, { t: 65, d: 5 }, 80]], + "apply": function apply(inputs) { + return inputs[0].sum(function (x) { + return x.get('content'); + }); + } + } +}; +},{"@cycle/core":1}],247:[function(require,module,exports){ +"use strict"; + +var _cycleCore = require('@cycle/core'); + +module.exports = { + "delay": { + "label": "delay", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 1 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].delay(20, scheduler); + } + }, + + "delayWithSelector": { + "label": "delayWithSelector(x => Rx.Observable.timer(20 * x))", + "inputs": [[{ t: 0, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 1 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].delayWithSelector(function (x) { + return _cycleCore.Rx.Observable.timer(Number(x.get('content')) * 20, 1000, scheduler); + }); + } + }, + + "findIndex": { + "label": "findIndex(x => x > 10)", + "inputs": [[{ t: 5, d: 2 }, { t: 15, d: 30 }, { t: 25, d: 22 }, { t: 35, d: 5 }, { t: 45, d: 60 }, { t: 55, d: 1 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].findIndex(function (x) { + return x.get('content') > 10; + }); + } + }, + + "map": { + "label": "map(x => 10 * x)", + "inputs": [[{ t: 10, d: 1 }, { t: 20, d: 2 }, { t: 50, d: 3 }]], + "apply": function apply(inputs) { + return inputs[0].map(function (x) { + return x.set('content', x.get('content') * 10); + }); + } + }, + + "scan": { + "label": "scan((x, y) => x + y)", + "inputs": [[{ t: 5, d: 1 }, { t: 15, d: 2 }, { t: 25, d: 3 }, { t: 35, d: 4 }, { t: 65, d: 5 }]], + "apply": function apply(inputs) { + return inputs[0].scan(function (x, y) { + return y.set('content', x.get('content') + y.get('content')).set('id', x.get('id') + y.get('id')); + }); + } + }, + + "debounce": { + "label": "debounce", + "inputs": [[{ t: 0, d: 1 }, { t: 26, d: 2 }, { t: 34, d: 3 }, { t: 40, d: 4 }, { t: 45, d: 5 }, { t: 79, d: 6 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].debounce(10, scheduler); + } + }, + + "debounceWithSelector": { + "label": "debounceWithSelector(x => Rx.Observable.timer(10 * x))", + "inputs": [[{ t: 0, d: 1 }, { t: 26, d: 2 }, { t: 34, d: 1 }, { t: 40, d: 1 }, { t: 45, d: 2 }, { t: 79, d: 1 }]], + "apply": function apply(inputs, scheduler) { + return inputs[0].debounceWithSelector(function (x) { + return _cycleCore.Rx.Observable.timer(Number(x.get('content')) * 10, 1000, scheduler); + }); + } + } +}; +},{"@cycle/core":1}],248:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports['default'] = { + white: '#FFFFFF', + almostWhite: '#ECECEC', + greyLight: '#D4D4D4', + grey: '#A7A7A7', + greyDark: '#7C7C7C', + black: '#323232', + blue: '#3EA1CB', + yellow: '#FFCB46', + red: '#FF6946', + green: '#82D736' +}; +module.exports = exports['default']; +},{}],249:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports['default'] = { + spaceTiny: '5px', + spaceSmall: '10px', + spaceMedium: '22px', + spaceLarge: '32px', + spaceHuge: '42px', + + animationDurationQuick: '100ms', + animationDurationNormal: '200ms', + animationDurationSlow: '400ms' +}; +module.exports = exports['default']; +},{}],250:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = { + fontBase: "'Source Sans Pro', sans-serif", + fontSpecial: "'Signika', Helvetica, serif", + fontCode: "'Source Code Pro', monospace" +}; +module.exports = exports["default"]; +},{}],251:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var _cycleDom = require('@cycle/dom'); + +var _cycleCore = require('@cycle/core'); + +var isTruthy = function isTruthy(x) { + return !!x; +}; + +function mergeStyles() { + for (var _len = arguments.length, styleObjects = Array(_len), _key = 0; _key < _len; _key++) { + styleObjects[_key] = arguments[_key]; + } + + return styleObjects.filter(isTruthy).reduce(function (styleA, styleB) { + var mapA = _immutable2['default'].Map(styleA); + var mapB = _immutable2['default'].Map(styleB); + return mapA.merge(mapB).toObject(); // notice B first + }, {}); +} + +var DROPSHADOW_FILTER_ID = 'dropshadow'; + +// Cross-browser SVG filter for drop shadows +function renderSvgDropshadow() { + return (0, _cycleDom.svg)('svg', { attributes: { height: '0' } }, [(0, _cycleDom.svg)('filter#' + DROPSHADOW_FILTER_ID, { attributes: { height: '130%' } }, [ + // stdDeviation is blur: + (0, _cycleDom.svg)('feGaussianBlur', { attributes: { 'in': 'SourceAlpha', stdDeviation: '0.05' } }), + // position relative to marble viewBox: + (0, _cycleDom.svg)('feOffset', { attributes: { dx: '0', dy: '0.05', result: 'offsetblur' } }), (0, _cycleDom.svg)('feFlood', { attributes: { 'flood-color': 'rgba(0,0,0,0.4)' } }), (0, _cycleDom.svg)('feComposite', { attributes: { in2: 'offsetblur', operator: 'in' } }), (0, _cycleDom.svg)('feMerge', [(0, _cycleDom.svg)('feMergeNode'), (0, _cycleDom.svg)('feMergeNode', { attributes: { 'in': 'SourceGraphic' } })])])]); +} + +function makeIsHighlighted$(DOM, cssSelector) { + var startHighlight$ = DOM.get(cssSelector, 'mouseenter').map(function () { + return 1; + }); + var stopHighlight$ = DOM.get(cssSelector, 'mouseleave').map(function () { + return 1; + }); + + return _cycleCore.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); +} + +var marbleElevation1Style = { + filter: 'url(#' + DROPSHADOW_FILTER_ID + ')' +}; + +var elevation1Style = { + '-webkit-box-shadow': '0px 1px 2px 1px rgba(0,0,0,0.17)', + '-moz-box-shadow': '0px 1px 2px 1px rgba(0,0,0,0.17)', + 'box-shadow': '0px 1px 2px 1px rgba(0,0,0,0.17)' +}; + +var elevation2Style = { + position: 'relative' +}; + +function getElevationPseudoElementStyle(dy, blur, opacity) { + return { + display: 'block', + position: 'absolute', + left: '0', top: '0', right: '0', bottom: '0', + '-webkit-box-shadow': '0 ' + dy + ' ' + blur + ' 0 rgba(0,0,0,' + opacity + ')', + '-moz-box-shadow': '0 ' + dy + ' ' + blur + ' 0 rgba(0,0,0,' + opacity + ')', + 'box-shadow': '0 ' + dy + ' ' + blur + ' 0 rgba(0,0,0,' + opacity + ')' + }; +} + +var elevation2Before = (0, _cycleDom.h)('div', { style: getElevationPseudoElementStyle('2px', '10px', '0.17') +}, ''); +var elevation2After = (0, _cycleDom.h)('div', { style: getElevationPseudoElementStyle('2px', '5px', '0.26') +}, ''); + +var elevation3Before = (0, _cycleDom.h)('div', { style: getElevationPseudoElementStyle('6px', '20px', '0.19') +}, ''); +var elevation3After = (0, _cycleDom.h)('div', { style: getElevationPseudoElementStyle('6px', '17px', '0.2') +}, ''); + +var textUnselectable = { + '-webkit-user-select': 'none', + '-khtml-user-select': 'none', + '-moz-user-select': 'none', + '-o-user-select': 'none', + 'user-select': 'none' +}; + +exports['default'] = { + mergeStyles: mergeStyles, + makeIsHighlighted$: makeIsHighlighted$, + elevation1Style: elevation1Style, + elevation2Style: elevation2Style, + elevation2Before: elevation2Before, + elevation2After: elevation2After, + elevation3Before: elevation3Before, + elevation3After: elevation3After, + marbleElevation1Style: marbleElevation1Style, + renderSvgDropshadow: renderSvgDropshadow, + textUnselectable: textUnselectable +}; +module.exports = exports['default']; +},{"@cycle/core":1,"@cycle/dom":6,"immutable":118}],252:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var OVERSHOOT = 1.70158; + +exports['default'] = { + EasingBack: createEasing(function (x) { + return x * x * ((OVERSHOOT + 1) * x - OVERSHOOT); + }) +}; +module.exports = exports['default']; +},{"./ease-common":255}],253:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var PARAM1 = 7.5625; +var PARAM2 = 2.75; +function easeOutFn(x) { + var z = x; + if (z < 1 / PARAM2) { + return PARAM1 * z * z; + } else if (z < 2 / PARAM2) { + return PARAM1 * (z -= 1.5 / PARAM2) * z + 0.75; + } else if (z < 2.5 / PARAM2) { + return PARAM1 * (z -= 2.25 / PARAM2) * z + 0.9375; + } else { + return PARAM1 * (z -= 2.625 / PARAM2) * z + 0.984375; + } +} + +exports['default'] = { + EasingBounce: createEasing(function (x) { + return 1 - easeOutFn(1 - x); + }) +}; +module.exports = exports['default']; +},{"./ease-common":255}],254:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; +exports['default'] = { + EasingCirc: createEasing(function (x) { + return -(Math.sqrt(1 - x * x) - 1); + }) +}; +module.exports = exports['default']; +},{"./ease-common":255}],255:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +function interpolate(y, from, to) { + return from * (1 - y) + to * y; +} + +function flip(fn) { + return function (x) { + return 1 - fn(1 - x); + }; +} + +exports['default'] = { + interpolate: interpolate, + + flip: flip, + + createEasing: function createEasing(fn) { + var fnFlipped = flip(fn); + return { + easeIn: function easeIn(x, from, to) { + return interpolate(fn(x), from, to); + }, + easeOut: function easeOut(x, from, to) { + return interpolate(fnFlipped(x), from, to); + }, + easeInOut: function easeInOut(x, from, to) { + var y = x < 0.5 ? fn(2 * x) * 0.5 : 0.5 + fnFlipped(2 * (x - 0.5)) * 0.5; + return interpolate(y, from, to); + } + }; + } +}; +module.exports = exports['default']; +},{}],256:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var PERIOD = 0.3; +var OVERSHOOT = PERIOD / 4; +var AMPLITUDE = 1; +function elasticIn(x) { + var z = x; + if (z <= 0) { + return 0; + } else if (z >= 1) { + return 1; + } else { + z -= 1; + return -(AMPLITUDE * Math.pow(2, 10 * z)) * Math.sin((z - OVERSHOOT) * (2 * Math.PI) / PERIOD); + } +} + +exports['default'] = { + EasingElastic: createEasing(elasticIn) +}; +module.exports = exports['default']; +},{"./ease-common":255}],257:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var EXP_WEIGHT = 6; +var EXP_MAX = Math.exp(EXP_WEIGHT) - 1; +function expFn(x) { + return (Math.exp(x * EXP_WEIGHT) - 1) / EXP_MAX; +} + +var EasingExponential = createEasing(expFn); + +exports['default'] = { + EasingExponential: EasingExponential +}; +module.exports = exports['default']; +},{"./ease-common":255}],258:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var EasingPower2 = createEasing(function (x) { + return x * x; +}); +var EasingPower3 = createEasing(function (x) { + return x * x * x; +}); +var EasingPower4 = createEasing(function (x) { + var xx = x * x; + return xx * xx; +}); + +exports['default'] = { + EasingPower2: EasingPower2, + EasingPower3: EasingPower3, + EasingPower4: EasingPower4 +}; +module.exports = exports['default']; +},{"./ease-common":255}],259:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +var _require = require('./ease-common'); + +var createEasing = _require.createEasing; + +var HALF_PI = Math.PI * 0.5; + +exports['default'] = { + EasingSine: createEasing(function (x) { + return 1 - Math.cos(x * HALF_PI); + }) +}; +module.exports = exports['default']; +},{"./ease-common":255}],260:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; +var Rx = require('rx'); + +var _require = require('./ease-common'); + +var interpolate = _require.interpolate; + +var _require2 = require('./ease-powers'); + +var EasingPower2 = _require2.EasingPower2; +var EasingPower3 = _require2.EasingPower3; +var EasingPower4 = _require2.EasingPower4; + +var _require3 = require('./ease-exponential'); + +var EasingExponential = _require3.EasingExponential; + +var _require4 = require('./ease-back'); + +var EasingBack = _require4.EasingBack; + +var _require5 = require('./ease-bounce'); + +var EasingBounce = _require5.EasingBounce; + +var _require6 = require('./ease-circ'); + +var EasingCirc = _require6.EasingCirc; + +var _require7 = require('./ease-elastic'); + +var EasingElastic = _require7.EasingElastic; + +var _require8 = require('./ease-sine'); + +var EasingSine = _require8.EasingSine; + +var DEFAULT_INTERVAL = 15; +function sanitizeInterval(interval) { + if (interval === 'auto') { + return DEFAULT_INTERVAL; + } else if (typeof interval !== 'number' || interval <= 0) { + console.warn('RxTween cannot use invalid given interval: ' + interval); + return DEFAULT_INTERVAL; + } + return interval; +} + +function RxTween(_ref) { + var from = _ref.from; + var to = _ref.to; + var duration = _ref.duration; + var _ref$ease = _ref.ease; + var ease = _ref$ease === undefined ? RxTween.Linear.ease : _ref$ease; + var _ref$interval = _ref.interval; + var interval = _ref$interval === undefined ? 'auto' : _ref$interval; + + var sanitizedInterval = sanitizeInterval(interval); + var totalTicks = Math.round(duration / sanitizedInterval); + return Rx.Observable.interval(sanitizedInterval).take(totalTicks).map(function (tick) { + return ease(tick / totalTicks, from, to); + }).concat(Rx.Observable.just(to)); +} + +RxTween.Linear = { ease: interpolate }; +RxTween.Power2 = EasingPower2; +RxTween.Power3 = EasingPower3; +RxTween.Power4 = EasingPower4; +RxTween.Exp = EasingExponential; +RxTween.Back = EasingBack; +RxTween.Bounce = EasingBounce; +RxTween.Circ = EasingCirc; +RxTween.Elastic = EasingElastic; +RxTween.Sine = EasingSine; + +exports['default'] = RxTween; +module.exports = exports['default']; +},{"./ease-back":252,"./ease-bounce":253,"./ease-circ":254,"./ease-common":255,"./ease-elastic":256,"./ease-exponential":257,"./ease-powers":258,"./ease-sine":259,"rx":226}],261:[function(require,module,exports){ +'use strict'; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +var _cycleCore = require('@cycle/core'); + +var _cycleCore2 = _interopRequireDefault(_cycleCore); + +var _cycleDom = require('@cycle/dom'); + +var _rxmarblesAppModel = require('rxmarbles/app-model'); + +var _rxmarblesAppModel2 = _interopRequireDefault(_rxmarblesAppModel); + +var _rxmarblesAppView = require('rxmarbles/app-view'); + +var _rxmarblesAppView2 = _interopRequireDefault(_rxmarblesAppView); + +var _rxmarblesComponentsOperatorsMenuLink = require('rxmarbles/components/operators-menu-link'); + +var _rxmarblesComponentsOperatorsMenuLink2 = _interopRequireDefault(_rxmarblesComponentsOperatorsMenuLink); + +var _rxmarblesComponentsOperatorsMenu = require('rxmarbles/components/operators-menu'); + +var _rxmarblesComponentsOperatorsMenu2 = _interopRequireDefault(_rxmarblesComponentsOperatorsMenu); + +var _rxmarblesComponentsSandboxSandbox = require('rxmarbles/components/sandbox/sandbox'); + +var _rxmarblesComponentsSandboxSandbox2 = _interopRequireDefault(_rxmarblesComponentsSandboxSandbox); + +var _rxmarblesComponentsDiagramDiagram = require('rxmarbles/components/diagram/diagram'); + +var _rxmarblesComponentsDiagramDiagram2 = _interopRequireDefault(_rxmarblesComponentsDiagramDiagram); + +var _rxmarblesComponentsMarble = require('rxmarbles/components/marble'); + +var _rxmarblesComponentsMarble2 = _interopRequireDefault(_rxmarblesComponentsMarble); + +var _rxmarblesComponentsDiagramCompletion = require('rxmarbles/components/diagram-completion'); + +var _rxmarblesComponentsDiagramCompletion2 = _interopRequireDefault(_rxmarblesComponentsDiagramCompletion); + +function main() { + return { + DOM: (0, _rxmarblesAppView2['default'])((0, _rxmarblesAppModel2['default'])()) + }; +} + +_cycleCore2['default'].run(main, { + DOM: (0, _cycleDom.makeDOMDriver)('.js-appContainer', { + 'x-operators-menu-link': _rxmarblesComponentsOperatorsMenuLink2['default'], + 'x-operators-menu': _rxmarblesComponentsOperatorsMenu2['default'], + 'x-sandbox': _rxmarblesComponentsSandboxSandbox2['default'], + 'x-marble': _rxmarblesComponentsMarble2['default'], + 'x-diagram-completion': _rxmarblesComponentsDiagramCompletion2['default'], + 'x-diagram': _rxmarblesComponentsDiagramDiagram2['default'] + }) +}); +},{"@cycle/core":1,"@cycle/dom":6,"rxmarbles/app-model":227,"rxmarbles/app-view":228,"rxmarbles/components/diagram-completion":229,"rxmarbles/components/diagram/diagram":233,"rxmarbles/components/marble":234,"rxmarbles/components/operators-menu":236,"rxmarbles/components/operators-menu-link":235,"rxmarbles/components/sandbox/sandbox":239}]},{},[261]); diff --git a/package.json b/package.json index d36ea63..dd8ad09 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "@cycle/core": "1.0.x", "@cycle/dom": "3.1.x", "immutable": "^3.7.2", + "lodash": "4.6.1", "rxtween": "0.3.3" }, "devDependencies": { diff --git a/src/components/operators-menu-link.js b/src/components/operators-menu-link.js index d347b7e..8736ec0 100644 --- a/src/components/operators-menu-link.js +++ b/src/components/operators-menu-link.js @@ -2,17 +2,12 @@ import {Rx} from '@cycle/core'; import {h} from '@cycle/dom'; import Colors from 'rxmarbles/styles/colors'; import Dimens from 'rxmarbles/styles/dimens'; -import {mergeStyles} from 'rxmarbles/styles/utils'; +import {mergeStyles, makeIsHighlighted$} from 'rxmarbles/styles/utils'; function operatorsMenuLink({DOM, props}) { - let startHighlight$ = DOM.get('.link', 'mouseenter').map(() => 1); - let stopHighlight$ = DOM.get('.link', 'mouseleave').map(() => 1); let href$ = props.get('href'); let content$ = props.get('content').startWith(''); - let isHighlighted$ = Rx.Observable.merge( - startHighlight$.map(() => true), - stopHighlight$.map(() => false) - ).startWith(false); + let isHighlighted$ = makeIsHighlighted$(DOM, '.link'); let highlightingArrow = h('span', { style: { display: 'inline-block', diff --git a/src/components/operators-menu.js b/src/components/operators-menu.js index dbb9c77..901a383 100644 --- a/src/components/operators-menu.js +++ b/src/components/operators-menu.js @@ -3,25 +3,7 @@ import {h} from '@cycle/dom'; import Colors from 'rxmarbles/styles/colors'; import Dimens from 'rxmarbles/styles/dimens'; import Examples from 'rxmarbles/data/examples'; -import {mergeStyles} from 'rxmarbles/styles/utils'; - -/** - * Returns a hashmap of category headers to lists of examples in that category. - */ -function organizeExamplesByCategory(examples) { - let categoryMap = {}; - for (let key in examples) { - if (!examples.hasOwnProperty(key)) continue; - let value = examples[key]; - value.key = key; - if (categoryMap.hasOwnProperty(value.category)) { - categoryMap[value.category].push(value); - } else { - categoryMap[value.category] = [value]; - } - } - return categoryMap; -} +import {mergeStyles, makeIsHighlighted$} from 'rxmarbles/styles/utils'; const operatorsMenuCategoryStyle = { textTransform: 'uppercase', @@ -64,7 +46,7 @@ function renderExampleCategory(categoryName, isFirstCategory) { ); } -function renderMenuContent(categoryMap) { +function renderMenuByCategory(categoryMap) { let listItems = []; let isFirstCategory = true; for (let categoryName in categoryMap) { @@ -78,26 +60,53 @@ function renderMenuContent(categoryMap) { return listItems; } -function operatorsMenuComponent() { - let categoryMap$ = Rx.Observable.just(organizeExamplesByCategory(Examples)); +function renderSwitchItem(key, label, isActive, isHighlighted) { + return h('div.switch.' + key, { + style: { + cursor: 'pointer', + float: 'left', + 'padding-right': '10px', + 'box-sizing': 'border-box', + 'text-align': 'left', + color: isHighlighted ? Colors.greyDark : Colors.grey, + 'text-decoration': 'underline' + }}, label); +} - return { - DOM: categoryMap$.map(categoryMap => - h('div', +function renderMenu(byCategory, byCategoryIsHighlighted, byAlphabetIsHighlighted) { + let menuItemsByCategory = renderMenuByCategory(Examples.byCategory); + let menuItemsByAlphabet = renderExampleItems(Examples.byAlphabet); + return h('div', {}, [ + h('div', + {style: { + paddingRight: '36px', + boxSizing: 'border-box', + // 100px is the estimated header page row height + height: 'calc(100vh - 100px)'}}, + [h('div', {}, + [ renderSwitchItem('byAlphabet', 'by Name', !byCategory, byAlphabetIsHighlighted), + renderSwitchItem('byCategory', 'by Category', byCategory, byCategoryIsHighlighted)]), + h('div', {style: {clear: 'both'}}), + h('ul', {style: { - paddingRight: '36px', - boxSizing: 'border-box', - // 100px is the estimated header page row height - height: 'calc(100vh - 100px)'}}, - [h('ul', - {style: { - margin: '0', - padding: '0', - listStyleType: 'none', - overflowY: 'scroll', - height: '100%'}}, - renderMenuContent(categoryMap))]) - ) + margin: '0', + 'margin-top': Dimens.spaceSmall, + padding: '0', + listStyleType: 'none', + overflowY: 'scroll', + height: '100%'}}, byCategory ? menuItemsByCategory : menuItemsByAlphabet)]) + ]); +} + +function operatorsMenuComponent({DOM, props}) { + + let switchMouseDown$ = DOM.get('.switch', 'mousedown'); + let showItemsByCategory$ = switchMouseDown$.map((ev) => ev.currentTarget.className.indexOf('byCategory') >= 0).startWith(true); + let byCategoryIsHighlighted$ = makeIsHighlighted$(DOM, '.byCategory'); + let byAlphabetIsHighlighted$ = makeIsHighlighted$(DOM, '.byAlphabet'); + + return { + DOM: Rx.Observable.combineLatest(showItemsByCategory$, byCategoryIsHighlighted$, byAlphabetIsHighlighted$, renderMenu) }; } diff --git a/src/data/examples.js b/src/data/examples.js index de1f49a..e226ad4 100644 --- a/src/data/examples.js +++ b/src/data/examples.js @@ -7,6 +7,7 @@ var filterExamples = require('rxmarbles/data/filter-examples'); var mathExamples = require('rxmarbles/data/math-examples'); var booleanExamples = require('rxmarbles/data/boolean-examples'); var conditionalExamples = require('rxmarbles/data/conditional-examples'); +var sortBy = require('lodash/sortBy'); function merge() { var args = (1 <= arguments.length) ? Array.prototype.slice.call(arguments) : []; @@ -29,7 +30,35 @@ function applyCategory(examples, categoryName) { return examples; }; -module.exports = merge( +/** + * Returns a hashmap of category headers to lists of examples in that category. + */ +function organizeExamplesByCategory(examples) { + let categoryMap = {}; + for (let key in examples) { + if (!examples.hasOwnProperty(key)) continue; + let value = examples[key]; + value.key = key; + if (categoryMap.hasOwnProperty(value.category)) { + categoryMap[value.category].push(value); + } else { + categoryMap[value.category] = [value]; + } + } + return categoryMap; +} + +function organizeExamplesByAlphabet(examples) { + let array = []; + for (let key in examples) { + if (!examples.hasOwnProperty(key)) continue; + let value = examples[key]; + array.push(value); + } + return sortBy(array, 'key'); +} + +let examples = merge( applyCategory(transformExamples, "Transforming Operators"), applyCategory(combineExamples, "Combining Operators"), applyCategory(filterExamples, "Filtering Operators"), @@ -37,3 +66,8 @@ module.exports = merge( applyCategory(booleanExamples, "Boolean Operators"), applyCategory(conditionalExamples, "Conditional Operators") ); + +examples.byCategory = organizeExamplesByCategory(examples); +examples.byAlphabet = organizeExamplesByAlphabet(examples); + +module.exports = examples; diff --git a/src/styles/utils.js b/src/styles/utils.js index 414e2c7..cb190b5 100644 --- a/src/styles/utils.js +++ b/src/styles/utils.js @@ -1,5 +1,6 @@ import Immutable from 'immutable'; import {h, svg} from '@cycle/dom'; +import {Rx} from '@cycle/core'; let isTruthy = x => !!x; @@ -31,6 +32,16 @@ function renderSvgDropshadow() { ]); } +function makeIsHighlighted$(DOM, cssSelector) { + let startHighlight$ = DOM.get(cssSelector, 'mouseenter').map(() => 1); + let stopHighlight$ = DOM.get(cssSelector, 'mouseleave').map(() => 1); + + return Rx.Observable.merge( + startHighlight$.map(() => true), + stopHighlight$.map(() => false) + ).startWith(false); +} + const marbleElevation1Style = { filter: 'url(#' + DROPSHADOW_FILTER_ID + ')' }; @@ -80,6 +91,7 @@ const textUnselectable = { export default { mergeStyles, + makeIsHighlighted$, elevation1Style, elevation2Style, elevation2Before,