From ac84681ce4fc467f690162085162111aae319094 Mon Sep 17 00:00:00 2001 From: Herman Banken Date: Mon, 19 Sep 2016 18:27:08 +0200 Subject: [PATCH 1/7] Update depencies / make compile on Node 6.6.0 & NPM 3.10.7 --- .babelrc | 3 +++ package.json | 13 ++++++++----- src/styles/utils.js | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) create mode 100644 .babelrc diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..c13c5f6 --- /dev/null +++ b/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015"] +} diff --git a/package.json b/package.json index d36ea63..bb1097c 100644 --- a/package.json +++ b/package.json @@ -13,18 +13,21 @@ "@cycle/core": "1.0.x", "@cycle/dom": "3.1.x", "immutable": "^3.7.2", - "rxtween": "0.3.3" + "rx": "^2.5.3", + "rxtween": "^0.3.3" }, "devDependencies": { + "babel": "^5.2.7", + "babel-cli": "^6.14.0", + "babel-preset-es2015": "^6.14.0", "browserify": "10.1.3", "less": "^2.5.0", "uglify-js": "~2.4.21", - "watchify": "~3.2.1", - "babel": "^5.2.7" + "watchify": "~3.2.1" }, "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", + "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src && rm -f node_modules/rxmarbles node_modules/package.json ignore/es5src/node_modules", + "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json && ln -s ../../node_modules ignore/es5src/node_modules", "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", diff --git a/src/styles/utils.js b/src/styles/utils.js index 414e2c7..ef74b4c 100644 --- a/src/styles/utils.js +++ b/src/styles/utils.js @@ -78,7 +78,7 @@ const textUnselectable = { 'user-select': 'none' }; -export default { +export { mergeStyles, elevation1Style, elevation2Style, From 0291403a10eba3157adb6aff7a620425a405dfe8 Mon Sep 17 00:00:00 2001 From: Herman Banken Date: Mon, 19 Sep 2016 19:17:06 +0200 Subject: [PATCH 2/7] Build --- dist/css/main.css | 4 +- dist/js/app.js | 23777 +++++++++++++++++++++++++++++++++++++++++++- src/app-model.js | 2 +- 3 files changed, 23764 insertions(+), 19 deletions(-) diff --git a/dist/css/main.css b/dist/css/main.css index ccade1e..49a8eb6 100644 --- a/dist/css/main.css +++ b/dist/css/main.css @@ -101,12 +101,12 @@ } body { position: relative; - background: #ececec; + background: #ECECEC; font-family: 'Source Sans Pro', sans-serif; color: #323232; } a { - color: #3ea1cb; + color: #3EA1CB; } p.marbleContent { -webkit-user-select: none; diff --git a/dist/js/app.js b/dist/js/app.js index 45c6efd..8a99ba3 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -1,16 +1,23761 @@ -(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 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) { + runTimeout(drainQueue); + } +}; + +// 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; }; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var packageJson = require('package'); +var RxPackageJson = require('rx/package.json'); + +var DEFAULT_EXAMPLE = 'merge'; + +module.exports = function appModel() { + var route$ = _core.Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { + return hashEvent.target.location.hash.replace('#', ''); + }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE); + var appVersion$ = _core.Rx.Observable.just(packageJson.version); + var rxVersion$ = _core.Rx.Observable.just(RxPackageJson.version); + return _core.Rx.Observable.combineLatest(route$, appVersion$, rxVersion$, function (route, appVersion, rxVersion) { + return { route: route, appVersion: appVersion, rxVersion: rxVersion }; + }); +}; +},{"@cycle/core":29,"package":154,"rx/package.json":101}],4:[function(require,module,exports){ +'use strict'; + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _fonts = require('rxmarbles/styles/fonts'); + +var _fonts2 = _interopRequireDefault(_fonts); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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, _utils.mergeStyles)(pageRowChildStyle, { + width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _dimens2.default.spaceMedium + ')' +}); + +var pageRowLastChildStyle = (0, _utils.mergeStyles)(pageRowChildStyle, { + width: sandboxWidth +}); + +function renderHeader() { + return (0, _dom.h)('div', { style: pageRowStyle }, [(0, _dom.h)('h1', { style: (0, _utils.mergeStyles)({ + fontFamily: _fonts2.default.fontSpecial, + color: _colors2.default.greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), (0, _dom.h)('h3', { style: (0, _utils.mergeStyles)({ + color: _colors2.default.greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); +} + +function renderContent(route) { + var style = (0, _utils.mergeStyles)(pageRowStyle, { marginTop: _dimens2.default.spaceSmall }); + return (0, _dom.h)('div', { style: style }, [(0, _dom.h)('div', { style: pageRowFirstChildStyle }, (0, _dom.h)('x-operators-menu', { key: 'operatorsMenu' })), (0, _dom.h)('div', { style: (0, _utils.mergeStyles)({ + position: 'absolute', + top: '0' }, pageRowLastChildStyle) }, (0, _dom.h)('x-sandbox', { key: 'sandbox', route: route, width: '820px' }))]); +} + +function renderFooter(appVersion, rxVersion) { + var style = { + position: 'fixed', + bottom: '2px', + right: _dimens2.default.spaceMedium, + color: _colors2.default.greyDark + }; + return (0, _dom.h)('section', { style: style }, [(0, _dom.h)('a', { href: rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', (0, _dom.h)('a', { href: rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', (0, _dom.h)('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); +} + +module.exports = function appView(state$) { + var wrapperStyle = { + paddingLeft: _dimens2.default.spaceSmall, + paddingRight: 'calc(' + _dimens2.default.spaceHuge + ' + ' + _dimens2.default.spaceSmall + ')' + }; + return state$.map(function (_ref) { + var route = _ref.route; + var appVersion = _ref.appVersion; + var rxVersion = _ref.rxVersion; + return (0, _dom.h)('div', { style: wrapperStyle }, [(0, _utils.renderSvgDropshadow)(), renderHeader(), renderContent(route), renderFooter(appVersion, rxVersion)]); + }); +}; +},{"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28}],5:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _core2 = _interopRequireDefault(_core); + +var _dom = require('@cycle/dom'); + +var _appModel = require('rxmarbles/app-model'); + +var _appModel2 = _interopRequireDefault(_appModel); + +var _appView = require('rxmarbles/app-view'); + +var _appView2 = _interopRequireDefault(_appView); + +var _operatorsMenuLink = require('rxmarbles/components/operators-menu-link'); + +var _operatorsMenuLink2 = _interopRequireDefault(_operatorsMenuLink); + +var _operatorsMenu = require('rxmarbles/components/operators-menu'); + +var _operatorsMenu2 = _interopRequireDefault(_operatorsMenu); + +var _sandbox = require('rxmarbles/components/sandbox/sandbox'); + +var _sandbox2 = _interopRequireDefault(_sandbox); + +var _diagram = require('rxmarbles/components/diagram/diagram'); + +var _diagram2 = _interopRequireDefault(_diagram); + +var _marble = require('rxmarbles/components/marble'); + +var _marble2 = _interopRequireDefault(_marble); + +var _diagramCompletion = require('rxmarbles/components/diagram-completion'); + +var _diagramCompletion2 = _interopRequireDefault(_diagramCompletion); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function main() { + return { + DOM: (0, _appView2.default)((0, _appModel2.default)()) + }; +} + +_core2.default.run(main, { + DOM: (0, _dom.makeDOMDriver)('.js-appContainer', { + 'x-operators-menu-link': _operatorsMenuLink2.default, + 'x-operators-menu': _operatorsMenu2.default, + 'x-sandbox': _sandbox2.default, + 'x-marble': _marble2.default, + 'x-diagram-completion': _diagramCompletion2.default, + 'x-diagram': _diagram2.default + }) +}); +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/app-model":3,"rxmarbles/app-view":4,"rxmarbles/components/diagram-completion":6,"rxmarbles/components/diagram/diagram":10,"rxmarbles/components/marble":11,"rxmarbles/components/operators-menu":13,"rxmarbles/components/operators-menu-link":12,"rxmarbles/components/sandbox/sandbox":16}],6:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _utils = 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, _dom.h)('div.completionRoot', { + style: (0, _utils.mergeStyles)({ + left: time + '%' }, containerStyle, isDraggable ? draggableContainerStyle : {}) + }, [(0, _dom.h)('div.completionInner', { + style: (0, _utils.mergeStyles)(innerStyle, isDraggable && isHighlighted ? _utils.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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _core.Rx.Observable.combineLatest(time$, isDraggable$, isTall$, style$, isHighlighted$, render); + + return { + DOM: vtree$ + }; +} + +module.exports = diagramCompletionComponent; +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/utils":28}],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 _core = require('@cycle/core'); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var mouseMove$ = _core.Rx.Observable.fromEvent(document, 'mousemove'); +var mouseUp$ = _core.Rx.Observable.fromEvent(document, 'mouseup'); + +function getPxToPercentageRatio(element) { + var pxToPercentage = void 0; + 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":29,"immutable":94}],8:[function(require,module,exports){ +'use strict'; + +var _core = 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$ = _core.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":29}],9:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _fonts = require('rxmarbles/styles/fonts'); + +var _fonts2 = _interopRequireDefault(_fonts); + +var _rxtween = require('rxtween'); + +var _rxtween2 = _interopRequireDefault(_rxtween); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MARBLE_WIDTH = 5; // estimate of a marble width, in percentages +var diagramSidePadding = _dimens2.default.spaceMedium; +var diagramVerticalMargin = _dimens2.default.spaceLarge; +var diagramArrowThickness = '2px'; +var diagramArrowSidePadding = _dimens2.default.spaceLarge; +var diagramArrowHeadSize = '8px'; +var diagramArrowColor = _colors2.default.black; +var diagramMarbleSize = _dimens2.default.spaceLarge; +var diagramCompletionHeight = '44px'; + +var diagramStyle = (0, _utils.mergeStyles)({ + position: 'relative', + display: 'block', + width: '100%', + height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin + ')', + overflow: 'visible', + cursor: 'default' }, _utils.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, _dom.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, _dom.h)('x-diagram-completion.diagramCompletion', { + key: 'completion', + time: endTime, + isDraggable: isDraggable, + isTall: isTall, + style: { + thickness: diagramArrowThickness, + color: diagramArrowColor, + height: diagramCompletionHeight + } + }); +} + +function renderDiagramArrow() { + return (0, _dom.h)('div.diagramArrow', { style: { + backgroundColor: diagramArrowColor, + height: diagramArrowThickness, + position: 'absolute', + top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', + left: diagramSidePadding, + right: diagramSidePadding + } }); +} + +function renderDiagramArrowHead() { + return (0, _dom.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, _dom.h)('div', { style: diagramStyle }, [renderDiagramArrow(), renderDiagramArrowHead(), (0, _dom.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 _core.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 === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }); +} + +function diagramView(model) { + return { + vtree$: _core.Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, renderDiagram) + }; +} + +module.exports = diagramView; +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28,"rxtween":110}],10:[function(require,module,exports){ +'use strict'; + +var _diagramModel = require('rxmarbles/components/diagram/diagram-model'); + +var _diagramModel2 = _interopRequireDefault(_diagramModel); + +var _diagramView = require('rxmarbles/components/diagram/diagram-view'); + +var _diagramView2 = _interopRequireDefault(_diagramView); + +var _diagramIntent = require('rxmarbles/components/diagram/diagram-intent'); + +var _diagramIntent2 = _interopRequireDefault(_diagramIntent); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function DiagramComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; + + var intent = (0, _diagramIntent2.default)(DOM); + var model = (0, _diagramModel2.default)(props, intent); + var view = (0, _diagramView2.default)(model); + + return { + DOM: view.vtree$, + events: { + newdata: model.newData$ + } + }; +} + +module.exports = DiagramComponent; +},{"rxmarbles/components/diagram/diagram-intent":7,"rxmarbles/components/diagram/diagram-model":8,"rxmarbles/components/diagram/diagram-view":9}],11:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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 = [_colors2.default.blue, _colors2.default.green, _colors2.default.yellow, _colors2.default.red]; + var color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + return (0, _dom.svg)('svg.marbleShape', { + style: { + overflow: 'visible', + width: inputStyle.size, + height: inputStyle.size + }, + attributes: { viewBox: '0 0 1 1' } }, [(0, _dom.svg)('circle', { + style: (0, _utils.mergeStyles)({ + stroke: _colors2.default.black, + fill: color + }, isDraggable && isHighlighted ? _utils.marbleElevation1Style : {}), + attributes: { + cx: 0.5, cy: 0.5, r: 0.47, + 'stroke-width': '0.06px' + } + })]); +} + +function renderInnerContent(data, inputStyle) { + return (0, _dom.h)('p.marbleContent', { + style: (0, _utils.mergeStyles)({ + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size }, _utils.textUnselectable) + }, '' + data.get('content')); +} + +function render(data, isDraggable, inputStyle, isHighlighted) { + var draggableContainerStyle = { + cursor: 'ew-resize' + }; + return (0, _dom.h)('div.marbleRoot', { + style: (0, _utils.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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _core.Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, render); + + return { + DOM: vtree$ + }; +} + +module.exports = marbleComponent; +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/utils":28}],12:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var highlightingArrow = (0, _dom.h)('span', { + style: { + display: 'inline-block', + position: 'absolute', + right: _dimens2.default.spaceTiny } + }, '❯'); + var vtree$ = _core.Rx.Observable.combineLatest(href$, content$, isHighlighted$, function (href, content, isHighlighted) { + return (0, _dom.h)('a.link', { + style: (0, _utils.mergeStyles)({ + position: 'relative', + display: 'block', + color: _colors2.default.greyDark }, isHighlighted ? { color: _colors2.default.black } : null), + href: href }, [content, isHighlighted ? highlightingArrow : null]); + }); + + return { DOM: vtree$ }; +} + +module.exports = operatorsMenuLink; +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/utils":28}],13:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _examples = require('rxmarbles/data/examples'); + +var _examples2 = _interopRequireDefault(_examples); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * 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; +} + +var operatorsMenuCategoryStyle = { + textTransform: 'uppercase', + fontSize: '0.7em', + color: _colors2.default.grey, + marginTop: _dimens2.default.spaceMedium +}; + +var operatorsMenuItemStyle = { + color: _colors2.default.greyDark, + fontSize: '1rem', + lineHeight: '1.6rem' +}; + +function renderExampleItem(example) { + return (0, _dom.h)('li', { style: operatorsMenuItemStyle }, (0, _dom.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, _dom.h)('li', { + style: (0, _utils.mergeStyles)(operatorsMenuCategoryStyle, isFirstCategory ? { marginTop: '0' } : {}) }, '' + categoryName); +} + +function renderMenuContent(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, _dom.h)('li', { style: operatorsMenuCategoryStyle }, 'More')); + listItems.push((0, _dom.h)('li', { style: operatorsMenuItemStyle }, 'Coming soon...')); + return listItems; +} + +function operatorsMenuComponent() { + var categoryMap$ = _core.Rx.Observable.just(organizeExamplesByCategory(_examples2.default)); + + return { + DOM: categoryMap$.map(function (categoryMap) { + return (0, _dom.h)('div', { style: { + paddingRight: '36px', + boxSizing: 'border-box', + // 100px is the estimated header page row height + height: 'calc(100vh - 100px)' } }, [(0, _dom.h)('ul', { style: { + margin: '0', + padding: '0', + listStyleType: 'none', + overflowY: 'scroll', + height: '100%' } }, renderMenuContent(categoryMap))]); + }) + }; +} + +module.exports = operatorsMenuComponent; +},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/data/examples":21,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/utils":28}],14:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _utils = require('rxmarbles/components/sandbox/utils'); + +var _utils2 = _interopRequireDefault(_utils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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); + } +} /* + * Functions to handle data of input diagrams in the example shown in the + * sandbox. + */ + + +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', _utils2.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":29,"immutable":94,"rxmarbles/components/sandbox/utils":17}],15:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* + * Functions to handle data of the output diagram in the example shown in the + * sandbox. + */ + + +var _core = require('@cycle/core'); + +var _utils = require('rxmarbles/components/sandbox/utils'); + +var _utils2 = _interopRequireDefault(_utils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MAX_VT_TIME = 100; // Time of completion + +function makeScheduler() { + var scheduler = new _core.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 _core.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 _core.Rx.Observable.merge(singleMarbleStreams).takeUntilWithTime(correctedEndTime, scheduler).publish().refCount(); +} + +function getDiagramPromise(stream, scheduler) { + var diagram = {}; + var subject = new _core.Rx.BehaviorSubject([]); + stream.observeOn(scheduler).timestamp(scheduler).map(function (x) { + if (_typeof(x.value) !== 'object') { + x.value = _immutable2.default.Map({ + content: x.value, + id: _utils2.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":29,"immutable":94,"rxmarbles/components/sandbox/utils":17}],16:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _rxtween = require('rxtween'); + +var _rxtween2 = _interopRequireDefault(_rxtween); + +var _examples = require('rxmarbles/data/examples'); + +var _examples2 = _interopRequireDefault(_examples); + +var _sandboxInput = require('rxmarbles/components/sandbox/sandbox-input'); + +var _sandboxOutput = require('rxmarbles/components/sandbox/sandbox-output'); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _fonts = require('rxmarbles/styles/fonts'); + +var _fonts2 = _interopRequireDefault(_fonts); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function renderOperatorLabel(label) { + var fontSize = label.length >= 45 ? 1.3 : label.length >= 30 ? 1.5 : 2; + var style = { + fontFamily: _fonts2.default.fontCode, + fontWeight: '400', + fontSize: fontSize + 'rem' + }; + return (0, _dom.h)('span.operatorLabel', { style: style }, label); +} + +function renderOperator(label) { + var style = (0, _utils.mergeStyles)({ + border: '1px solid rgba(0,0,0,0.06)', + padding: _dimens2.default.spaceMedium, + textAlign: 'center' }, _utils.elevation2Style); + return (0, _dom.h)('div.operatorBox', { style: style }, [_utils.elevation2Before, renderOperatorLabel(label), _utils.elevation2After]); +} + +function getSandboxStyle(width) { + return (0, _utils.mergeStyles)({ + background: _colors2.default.white, + width: width, + borderRadius: '2px' }, _utils.elevation1Style); +} + +function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { + return (0, _dom.h)('div.sandboxRoot', { style: getSandboxStyle(width) }, [inputDiagrams.get('diagrams').map(function (diagram, index) { + return (0, _dom.h)('x-diagram.sandboxInputDiagram', { + key: 'inputDiagram' + index, + data: diagram, + interactive: true + }); + }), renderOperator(operatorLabel), (0, _dom.h)('x-diagram.sandboxOutputDiagram', { + key: 'outputDiagram', + data: outputDiagram, + interactive: false + })]); +} + +function makeInputDiagrams(example) { + return _immutable2.default.Map({ + 'diagrams': example.get('inputs').map(_sandboxInput.prepareInputDiagram).map(function (diag) { + return (0, _sandboxInput.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(_examples2.default[key]).set('key', key); + }).shareReplay(1); + var inputDiagrams$ = example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1); + var newInputDiagrams$ = (0, _sandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$, inputDiagrams$); + var operatorLabel$ = example$.map(function (example) { + return example.get('label'); + }); + var firstOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, inputDiagrams$).map(markAsFirstDiagram); + var newOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, newInputDiagrams$); + var outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); + var vtree$ = _core.Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, renderSandbox); + + return { + DOM: vtree$ + }; +} + +module.exports = sandboxComponent; +},{"@cycle/core":29,"@cycle/dom":32,"immutable":94,"rxmarbles/components/sandbox/sandbox-input":14,"rxmarbles/components/sandbox/sandbox-output":15,"rxmarbles/data/examples":21,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28,"rxtween":110}],17:[function(require,module,exports){ +"use strict"; + +/* + * Conversion from virtual time streams out to diagram data, and + * vice-versa, and related functions. + */ + +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 +}; +},{}],18:[function(require,module,exports){ +"use strict"; + +var _core = 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":29}],19:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.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 _core.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 _core.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 _core.Rx.Observable.zip(inputs[0], inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + } +}; +},{"@cycle/core":29}],20:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.Rx.Observable.amb(inputs); + } + } +}; +},{"@cycle/core":29}],21:[function(require,module,exports){ +'use strict'; + +/* + * The database of all predefined examples in the app. + */ +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 < 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; +}; + +module.exports = 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")); +},{"rxmarbles/data/boolean-examples":18,"rxmarbles/data/combine-examples":19,"rxmarbles/data/conditional-examples":20,"rxmarbles/data/filter-examples":22,"rxmarbles/data/math-examples":23,"rxmarbles/data/transform-examples":24}],22:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.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 _core.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":29}],23:[function(require,module,exports){ +"use strict"; + +var _core = 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":29}],24:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.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 _core.Rx.Observable.timer(Number(x.get('content')) * 10, 1000, scheduler); + }); + } + } +}; +},{"@cycle/core":29}],25:[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' +}; +},{}],26:[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' +}; +},{}],27:[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" +}; +},{}],28:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.textUnselectable = exports.renderSvgDropshadow = exports.marbleElevation1Style = exports.elevation3After = exports.elevation3Before = exports.elevation2After = exports.elevation2Before = exports.elevation2Style = exports.elevation1Style = exports.mergeStyles = undefined; + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +var _dom = require('@cycle/dom'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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, _dom.svg)('svg', { attributes: { height: '0' } }, [(0, _dom.svg)('filter#' + DROPSHADOW_FILTER_ID, { attributes: { height: '130%' } }, [ + // stdDeviation is blur: + (0, _dom.svg)('feGaussianBlur', { attributes: { in: 'SourceAlpha', stdDeviation: '0.05' } }), + // position relative to marble viewBox: + (0, _dom.svg)('feOffset', { attributes: { dx: '0', dy: '0.05', result: 'offsetblur' } }), (0, _dom.svg)('feFlood', { attributes: { 'flood-color': 'rgba(0,0,0,0.4)' } }), (0, _dom.svg)('feComposite', { attributes: { in2: 'offsetblur', operator: 'in' } }), (0, _dom.svg)('feMerge', [(0, _dom.svg)('feMergeNode'), (0, _dom.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, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '10px', '0.17') +}, ''); +var elevation2After = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '5px', '0.26') +}, ''); + +var elevation3Before = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('6px', '20px', '0.19') +}, ''); +var elevation3After = (0, _dom.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.mergeStyles = mergeStyles; +exports.elevation1Style = elevation1Style; +exports.elevation2Style = elevation2Style; +exports.elevation2Before = elevation2Before; +exports.elevation2After = elevation2After; +exports.elevation3Before = elevation3Before; +exports.elevation3After = elevation3After; +exports.marbleElevation1Style = marbleElevation1Style; +exports.renderSvgDropshadow = renderSvgDropshadow; +exports.textUnselectable = textUnselectable; +},{"@cycle/dom":32,"immutable":94}],29:[function(require,module,exports){ +"use strict"; + +var Rx = require("rx"); + +function makeRequestProxies(drivers) { + var requestProxies = {}; + for (var _name in drivers) { + if (drivers.hasOwnProperty(_name)) { + requestProxies[_name] = new Rx.ReplaySubject(1); + } + } + return requestProxies; +} + +function callDrivers(drivers, requestProxies) { + var responses = {}; + for (var _name2 in drivers) { + if (drivers.hasOwnProperty(_name2)) { + responses[_name2] = drivers[_name2](requestProxies[_name2], _name2); + } + } + return responses; +} + +function makeDispose(requestProxies, rawResponses) { + return function dispose() { + for (var x in requestProxies) { + if (requestProxies.hasOwnProperty(x)) { + requestProxies[x].dispose(); + } + } + for (var _name3 in rawResponses) { + if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === "function") { + rawResponses[_name3].dispose(); + } + } + }; +} + +function makeAppInput(requestProxies, rawResponses) { + Object.defineProperty(rawResponses, "dispose", { + enumerable: false, + value: makeDispose(requestProxies, rawResponses) + }); + return rawResponses; +} + +function logToConsoleError(err) { + var target = err.stack || err; + if (console && console.error) { + console.error(target); + } +} + +function replicateMany(original, imitators) { + for (var _name4 in original) { + if (original.hasOwnProperty(_name4)) { + if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) { + original[_name4].doOnError(logToConsoleError).subscribe(imitators[_name4].asObserver()); + } + } + } +} + +function isObjectEmpty(obj) { + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + return false; + } + } + return true; +} + +function run(main, drivers) { + if (typeof main !== "function") { + throw new Error("First argument given to Cycle.run() must be the 'main' " + "function."); + } + if (typeof drivers !== "object" || drivers === null) { + throw new Error("Second argument given to Cycle.run() must be an object " + "with driver functions as properties."); + } + if (isObjectEmpty(drivers)) { + throw new Error("Second argument given to Cycle.run() must be an object " + "with at least one driver function declared as a property."); + } + + var requestProxies = makeRequestProxies(drivers); + var rawResponses = callDrivers(drivers, requestProxies); + var responses = makeAppInput(requestProxies, rawResponses); + var requests = main(responses); + setTimeout(function () { + return replicateMany(requests, requestProxies); + }, 1); + return [requests, responses]; +} + +var Cycle = { + /** + * Takes an `main` function and circularly connects it to the given collection + * of driver functions. + * + * The `main` function expects a collection of "driver response" Observables + * as input, and should return a collection of "driver request" Observables. + * A "collection of Observables" is a JavaScript object where + * keys match the driver names registered by the `drivers` object, and values + * are Observables or a collection of Observables. + * + * @param {Function} main a function that takes `responses` as input + * and outputs a collection of `requests` Observables. + * @param {Object} drivers an object where keys are driver names and values + * are driver functions. + * @return {Array} an array where the first object is the collection of driver + * requests, and the second object is the collection of driver responses, that + * can be used for debugging or testing. + * @function run + */ + run: run, + + /** + * A shortcut to the root object of + * [RxJS](https://github.com/Reactive-Extensions/RxJS). + * @name Rx + */ + Rx: Rx +}; + +module.exports = Cycle; +},{"rx":100}],30:[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":33,"@cycle/core":29}],31:[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":30,"es6-map":81}],32:[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":33,"./render-html":34,"virtual-dom":125,"virtual-dom/virtual-hyperscript/svg":139}],33:[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":31,"@cycle/core":29,"vdom-parser":115,"virtual-dom":125,"virtual-dom/diff":123,"virtual-dom/patch":126}],34:[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":30,"./custom-elements":31,"@cycle/core":29,"vdom-to-html":119}],35:[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; +})(); + +},{}],36:[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":49,"es5-ext/object/map":57,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64}],37:[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":46,"es5-ext/object/is-callable":52,"es5-ext/object/normalize-options":58,"es5-ext/string/#/contains":65}],38:[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":64}],39:[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":44,"../../object/valid-value":64}],40:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sign + : require('./shim'); + +},{"./is-implemented":41,"./shim":42}],41:[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)); +}; + +},{}],42:[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; +}; + +},{}],43:[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":40}],44:[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":43}],45:[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":63,"./valid-value":64}],46:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.assign + : require('./shim'); + +},{"./is-implemented":47,"./shim":48}],47:[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'; +}; + +},{}],48:[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":54,"../valid-value":64}],49:[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":46,"./valid-value":64}],50:[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":61,"./set-prototype-of/shim":62}],51:[function(require,module,exports){ +'use strict'; + +module.exports = require('./_iterate')('forEach'); + +},{"./_iterate":45}],52:[function(require,module,exports){ +// Deprecated + +'use strict'; + +module.exports = function (obj) { return typeof obj === 'function'; }; + +},{}],53:[function(require,module,exports){ +'use strict'; + +var map = { function: true, object: true }; + +module.exports = function (x) { + return ((x != null) && map[typeof x]) || false; +}; + +},{}],54:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.keys + : require('./shim'); + +},{"./is-implemented":55,"./shim":56}],55:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + try { + Object.keys('primitive'); + return true; + } catch (e) { return false; } +}; + +},{}],56:[function(require,module,exports){ +'use strict'; + +var keys = Object.keys; + +module.exports = function (object) { + return keys(object == null ? object : Object(object)); +}; + +},{}],57:[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":51,"./valid-callable":63}],58:[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; +}; + +},{}],59:[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; +}; + +},{}],60:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.setPrototypeOf + : require('./shim'); + +},{"./is-implemented":61,"./shim":62}],61:[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; +}; + +},{}],62:[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":50,"../is-object":53,"../valid-value":64}],63:[function(require,module,exports){ +'use strict'; + +module.exports = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; +}; + +},{}],64:[function(require,module,exports){ +'use strict'; + +module.exports = function (value) { + if (value == null) throw new TypeError("Cannot use null or undefined"); + return value; +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.contains + : require('./shim'); + +},{"./is-implemented":66,"./shim":67}],66:[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)); +}; + +},{}],67:[function(require,module,exports){ +'use strict'; + +var indexOf = String.prototype.indexOf; + +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + +},{}],68:[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; +}; + +},{}],69:[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]'; }) +}); + +},{"./":72,"d":37,"es5-ext/object/set-prototype-of":60,"es5-ext/string/#/contains":65}],70:[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":71,"es5-ext/object/valid-callable":63,"es5-ext/string/is-string":68}],71:[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":69,"./string":79,"./valid-iterable":80,"es5-ext/string/is-string":68,"es6-symbol":74}],72:[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":37,"d/auto-bind":36,"es5-ext/array/#/clear":38,"es5-ext/object/assign":46,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64,"es6-symbol":74}],73:[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":68,"es6-symbol":74}],74:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); + +},{"./is-implemented":75,"./polyfill":77}],75:[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; +}; + +},{}],76:[function(require,module,exports){ +'use strict'; + +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; + +},{}],77:[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":78,"d":37}],78:[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":76}],79:[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]'; }) +}); + +},{"./":72,"d":37,"es5-ext/object/set-prototype-of":60}],80:[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":73}],81:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() ? Map : require('./polyfill'); + +},{"./is-implemented":82,"./polyfill":86}],82:[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; +}; + +},{}],83:[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]'); +}()); + +},{}],84:[function(require,module,exports){ +'use strict'; + +module.exports = require('es5-ext/object/primitive-set')('key', + 'value', 'key+value'); + +},{"es5-ext/object/primitive-set":59}],85:[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":84,"d":37,"es5-ext/object/set-prototype-of":60,"es6-iterator":72,"es6-symbol":87}],86:[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":83,"./lib/iterator":85,"d":37,"es5-ext/array/#/clear":38,"es5-ext/array/#/e-index-of":39,"es5-ext/object/set-prototype-of":60,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64,"es6-iterator/for-of":70,"es6-iterator/valid-iterable":80,"es6-symbol":87,"event-emitter":92}],87:[function(require,module,exports){ +arguments[4][74][0].apply(exports,arguments) +},{"./is-implemented":88,"./polyfill":89,"dup":74}],88:[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; +}; + +},{}],89:[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":37}],90:[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; +} + +},{}],91:[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":96}],92:[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":37,"es5-ext/object/valid-callable":63}],93:[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":1}],94:[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') { + if (o !== o || o === Infinity) { + return 0; + } + 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.of = function() {var keyValues = SLICE$0.call(arguments, 0); + return emptyMap().withMutations(function(map ) { + for (var i = 0; i < keyValues.length; i += 2) { + if (i + 1 >= keyValues.length) { + throw new Error('Missing value for key: ' + keyValues[i]); + } + map.set(keyValues[i], keyValues[i + 1]); + } + }); + }; + + 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) { + if (end === Infinity) { + end = originalSize; + } else { + 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)); + } + if (this._map && !this._map.has(k)) { + var defaultVal = this._defaultValues[k]; + if (v === defaultVal) { + return 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; + }, + + 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); + }, + + findEntry: function(predicate, context, notSetValue) { + var found = notSetValue; + this.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } + }); + return found; + }, + + findKey: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, + + findLast: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, + + findLastEntry: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); + }, + + findLastKey: function(predicate, context) { + return this.toKeyedSeq().reverse().findKey(predicate, context); + }, + + 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); + }, + + keyOf: function(searchValue) { + return this.findKey(function(value ) {return is(value, searchValue)}); + }, + + keySeq: function() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, + + last: function() { + return this.toSeq().reverse().first(); + }, + + lastKeyOf: function(searchValue) { + return this.toKeyedSeq().reverse().keyOf(searchValue); + }, + + 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; + + mixin(KeyedIterable, { + + // ### More sequential methods + + flip: function() { + return reify(this, flipFactory(this)); + }, + + 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.keyOf(searchValue); + return key === undefined ? -1 : key; + }, + + lastIndexOf: function(searchValue) { + var key = this.lastKeyOf(searchValue); + return key === undefined ? -1 : key; + }, + + 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 entry = this.findLastEntry(predicate, context); + return entry ? entry[0] : -1; + }, + + 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); + }, + + keySeq: function() { + return Range(0, this.size); + }, + + 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; + SetIterable.prototype.contains = SetIterable.prototype.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) : String(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; + +})); +},{}],95:[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 : {}) +},{}],96:[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":95}],97:[function(require,module,exports){ +"use strict"; + +module.exports = function isObject(x) { + return typeof x === "object" && x !== null; +}; + +},{}],98:[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() +} + +},{}],99:[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":111}],100:[function(require,module,exports){ +(function (process,global){ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { + + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + var Rx = { + internals: {}, + config: { + Promise: root.Promise + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > 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":2}],101:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "rx@^2.5.3", + "scope": null, + "escapedName": "rx", + "name": "rx", + "rawSpec": "^2.5.3", + "spec": ">=2.5.3 <3.0.0", + "type": "range" + }, + "/Users/hba21580/Dropbox/Afstuderen/rxmarbles" + ] + ], + "_from": "rx@>=2.5.3 <3.0.0", + "_id": "rx@2.5.3", + "_inCache": true, + "_installable": true, + "_location": "/rx", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + }, + "_npmVersion": "2.7.4", + "_phantomChildren": {}, + "_requested": { + "raw": "rx@^2.5.3", + "scope": null, + "escapedName": "rx", + "name": "rx", + "rawSpec": "^2.5.3", + "spec": ">=2.5.3 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/", + "/@cycle/core" + ], + "_resolved": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz", + "_shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", + "_shrinkwrap": null, + "_spec": "rx@^2.5.3", + "_where": "/Users/hba21580/Dropbox/Afstuderen/rxmarbles", + "author": { + "name": "Cloud Programmability Team", + "url": "https://github.com/Reactive-Extensions/RxJS/blob/master/authors.txt" + }, + "browser": { + "index.js": "dist/rx.all.js" + }, + "bugs": { + "url": "https://github.com/Reactive-Extensions/RxJS/issues" + }, + "dependencies": {}, + "description": "Library for composing asynchronous and event-based operations in JavaScript", + "devDependencies": { + "benchmark": "*", + "grunt": "*", + "grunt-cli": "*", + "grunt-contrib-concat": "*", + "grunt-contrib-connect": "*", + "grunt-contrib-copy": "*", + "grunt-contrib-jshint": "*", + "grunt-contrib-qunit": "*", + "grunt-contrib-uglify": "*", + "grunt-contrib-watch": "*", + "grunt-jscs": "*", + "grunt-saucelabs": "*", + "load-grunt-tasks": "*" + }, + "directories": {}, + "dist": { + "shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", + "tarball": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz" + }, + "gitHead": "6507118725e93498f7a52a603acf679e472f47b7", + "homepage": "https://github.com/Reactive-Extensions/RxJS", + "jam": { + "main": "dist/rx.all.js" + }, + "keywords": [ + "LINQ", + "FRP", + "Reactive", + "Events", + "Rx", + "RxJS" + ], + "license": "Apache-2.0", + "main": "index.js", + "maintainers": [ + { + "name": "vvilhonen", + "email": "vesa@vilhonen.com" + }, + { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + } + ], + "name": "rx", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/Reactive-Extensions/RxJS.git" + }, + "scripts": { + "test": "grunt" + }, + "title": "Reactive Extensions for JavaScript (RxJS)", + "version": "2.5.3" +} + +},{}],102:[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":105}],103:[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":105}],104:[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":105}],105:[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']; +},{}],106:[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":105}],107:[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":105}],108:[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":105}],109:[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":105}],110:[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":102,"./ease-bounce":103,"./ease-circ":104,"./ease-common":105,"./ease-elastic":106,"./ease-exponential":107,"./ease-powers":108,"./ease-sine":109,"rx":100}],111:[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":112,"./vendor/non-word-regexp":113,"./vendor/trailing-digit-regexp":114,"lower-case":98}],112:[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 + +},{}],113:[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 + +},{}],114:[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 + +},{}],115:[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'){ + attr = createStyleProperty(el); + } + 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 || name.indexOf('aria-') === 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] || '' + }; +} + +/** + * Create style property from dom node + * + * @param Object el DOM node + * @return Object Normalized attribute + */ +function createStyleProperty(el) { + 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, '') + } + } + return { name: 'style', value: output }; +} + +},{"./namespace-map":116,"./property-map":117,"virtual-dom/vnode/vnode":147,"virtual-dom/vnode/vtext":149}],116:[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; + +},{}],117:[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; + +},{}],118:[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":120,"escape-html":90}],119:[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 == 'dataset') { + value = extend({}, value); + for (var dataProp in value) { + ret += ' ' + createAttribute('data-' + paramCase(dataProp), value[dataProp], 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":118,"./void-elements":121,"escape-html":90,"param-case":99,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":133,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":135,"virtual-dom/vnode/is-thunk":141,"virtual-dom/vnode/is-vnode":143,"virtual-dom/vnode/is-vtext":144,"virtual-dom/vnode/is-widget":145,"xtend":153}],120:[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 +}; +},{}],121:[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 +}; +},{}],122:[function(require,module,exports){ +var createElement = require("./vdom/create-element.js") + +module.exports = createElement + +},{"./vdom/create-element.js":128}],123:[function(require,module,exports){ +var diff = require("./vtree/diff.js") + +module.exports = diff + +},{"./vtree/diff.js":151}],124:[function(require,module,exports){ +var h = require("./virtual-hyperscript/index.js") + +module.exports = h + +},{"./virtual-hyperscript/index.js":136}],125:[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":122,"./diff.js":123,"./h.js":124,"./patch.js":126,"./vnode/vnode.js":147,"./vnode/vtext.js":149}],126:[function(require,module,exports){ +var patch = require("./vdom/patch.js") + +module.exports = patch + +},{"./vdom/patch.js":131}],127:[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":142,"is-object":97}],128:[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":140,"../vnode/is-vnode.js":143,"../vnode/is-vtext.js":144,"../vnode/is-widget.js":145,"./apply-properties":127,"global/document":93}],129:[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 +} + +},{}],130:[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":145,"../vnode/vpatch.js":148,"./apply-properties":127,"./update-widget":132}],131:[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":128,"./dom-index":129,"./patch-op":130,"global/document":93,"x-is-array":152}],132:[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":145}],133:[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'; + +},{}],134:[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":91}],135:[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; + } +}; + +},{}],136:[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":141,"../vnode/is-vhook":142,"../vnode/is-vnode":143,"../vnode/is-vtext":144,"../vnode/is-widget":145,"../vnode/vnode.js":147,"../vnode/vtext.js":149,"./hooks/ev-hook.js":134,"./hooks/soft-set-hook.js":135,"./parse-tag.js":137,"x-is-array":152}],137:[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":35}],138:[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]; + } +} + +},{}],139:[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":133,"./index.js":136,"./svg-attribute-namespace":138,"x-is-array":152}],140:[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":141,"./is-vnode":143,"./is-vtext":144,"./is-widget":145}],141:[function(require,module,exports){ +module.exports = isThunk + +function isThunk(t) { + return t && t.type === "Thunk" +} + +},{}],142:[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")) +} + +},{}],143:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualNode + +function isVirtualNode(x) { + return x && x.type === "VirtualNode" && x.version === version +} + +},{"./version":146}],144:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualText + +function isVirtualText(x) { + return x && x.type === "VirtualText" && x.version === version +} + +},{"./version":146}],145:[function(require,module,exports){ +module.exports = isWidget + +function isWidget(w) { + return w && w.type === "Widget" +} + +},{}],146:[function(require,module,exports){ +module.exports = "2" + +},{}],147:[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":141,"./is-vhook":142,"./is-vnode":143,"./is-widget":145,"./version":146}],148:[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":146}],149:[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":146}],150:[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":142,"is-object":97}],151:[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":140,"../vnode/is-thunk":141,"../vnode/is-vnode":143,"../vnode/is-vtext":144,"../vnode/is-widget":145,"../vnode/vpatch":148,"./diff-props":150,"x-is-array":152}],152:[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]" +} + +},{}],153:[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 +} + +},{}],154:[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", + "rx": "^2.5.3", + "rxtween": "^0.3.3" + }, + "devDependencies": { + "babel": "^5.2.7", + "babel-cli": "^6.14.0", + "babel-preset-es2015": "^6.14.0", + "browserify": "10.1.3", + "less": "^2.5.0", + "uglify-js": "~2.4.21", + "watchify": "~3.2.1" + }, + "scripts": { + "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src && rm -f node_modules/rxmarbles node_modules/package.json ignore/es5src/node_modules", + "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json && ln -s ../../node_modules ignore/es5src/node_modules", + "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" + } +} + +},{}]},{},[5]); diff --git a/src/app-model.js b/src/app-model.js index fd7a0bf..c9f4394 100644 --- a/src/app-model.js +++ b/src/app-model.js @@ -1,6 +1,6 @@ import {Rx} from '@cycle/core'; let packageJson = require('package'); -let RxPackageJson = require('@cycle/core/node_modules/rx/package.json'); +let RxPackageJson = require('rx/package.json'); const DEFAULT_EXAMPLE = 'merge'; From 6eac8d5a7c988f6afec3f20b45fc787669bcd8ba Mon Sep 17 00:00:00 2001 From: Brandon Wallace Date: Wed, 3 Jun 2015 06:08:18 -0500 Subject: [PATCH 3/7] Simplify input observable construction --- src/components/sandbox/sandbox-output.js | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/components/sandbox/sandbox-output.js b/src/components/sandbox/sandbox-output.js index be5289b..92bf1b8 100644 --- a/src/components/sandbox/sandbox-output.js +++ b/src/components/sandbox/sandbox-output.js @@ -20,25 +20,20 @@ function makeScheduler() { return scheduler; } -function justIncomplete(item, scheduler) { - return new Rx.AnonymousObservable(observer => - scheduler.schedule(() => { observer.onNext(item); }) - ); -} - /** * Creates an (virtual time) Rx.Observable from diagram * data (array of data items). */ function toVTStream(diagramData, scheduler) { - let singleMarbleStreams = diagramData.get('notifications').map(item => - justIncomplete(item, scheduler).delay(item.get('time'), scheduler) - ).toArray(); - // Necessary correction to include marbles at time exactly diagramData.end: - let correctedEndTime = diagramData.get('end') + 0.01; - return Rx.Observable.merge(singleMarbleStreams) - .takeUntilWithTime(correctedEndTime, scheduler) - .publish().refCount(); + return Rx.Observable.create(observer => { + let notifications = diagramData.get('notifications') + .map(item => scheduler.scheduleWithRelative(item.get('time'), () => observer.onNext(item))) + .toArray(); + let completion = scheduler.scheduleWithRelative(diagramData.get('end') + 0.01, () => observer.onCompleted()); + let s = new Rx.CompositeDisposable(notifications); + s.add(completion); + return s; + }).publish().refCount(); } function getDiagramPromise(stream, scheduler) { From 578e53893cf2df173a57f6607600196d09339c44 Mon Sep 17 00:00:00 2001 From: Brandon Wallace Date: Wed, 3 Jun 2015 06:09:56 -0500 Subject: [PATCH 4/7] Do not publish.refCount input observables Let examples do this if they need to. Otherwise it can break some example usage scenarios --- src/components/sandbox/sandbox-output.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/sandbox/sandbox-output.js b/src/components/sandbox/sandbox-output.js index 92bf1b8..7a402d8 100644 --- a/src/components/sandbox/sandbox-output.js +++ b/src/components/sandbox/sandbox-output.js @@ -33,7 +33,7 @@ function toVTStream(diagramData, scheduler) { let s = new Rx.CompositeDisposable(notifications); s.add(completion); return s; - }).publish().refCount(); + }); } function getDiagramPromise(stream, scheduler) { From bb6b9407f4773d1b9404cde74105b50f8be871f2 Mon Sep 17 00:00:00 2001 From: Brandon Wallace Date: Wed, 3 Jun 2015 09:37:08 -0500 Subject: [PATCH 5/7] Track and show individual subscriptions to input streams --- TODO | 1 + src/app-view.js | 2 +- src/components/diagram/diagram-model.js | 9 +- src/components/diagram/diagram-view.js | 174 +++++++++++++++++------ src/components/marble.js | 41 +++--- src/components/sandbox/sandbox-input.js | 6 +- src/components/sandbox/sandbox-output.js | 151 +++++++++++++++----- src/components/sandbox/sandbox.js | 46 ++++-- 8 files changed, 316 insertions(+), 114 deletions(-) diff --git a/TODO b/TODO index 0245474..6cfe499 100644 --- a/TODO +++ b/TODO @@ -76,6 +76,7 @@ DONE Fix marble hover and dragging styles for Firefox DONE Fix affordance animation stuck for combineLatest >>> v1.4.0 +DONE Track and show individual subscriptions to input streams TODO Fix visual semantics of concat diagram >>> diff --git a/src/app-view.js b/src/app-view.js index 68bb897..b5d2df3 100644 --- a/src/app-view.js +++ b/src/app-view.js @@ -57,7 +57,7 @@ function renderContent(route) { position: 'absolute', top: '0'}, pageRowLastChildStyle)} - ,h('x-sandbox', {key: 'sandbox', route: route, width: '820px'}) + ,h('x-sandbox', {key: 'sandbox', route: route, width: '820px', showSubscriptions: true}) ) ]) ); diff --git a/src/components/diagram/diagram-model.js b/src/components/diagram/diagram-model.js index 3582da0..70f8871 100644 --- a/src/components/diagram/diagram-model.js +++ b/src/components/diagram/diagram-model.js @@ -26,8 +26,10 @@ function applyChangeMarbleTime(diagramData, marbleDelta) { } function applyChangeEndTime(diagramData, endDelta) { + var newEnd = diagramData.get('end') + endDelta; return diagramData - .set('end', diagramData.get('end') + endDelta); + .set('end', newEnd) + .set('eventualEnd', newEnd); } function applyMarbleDataConstraints(marbleData) { @@ -45,7 +47,7 @@ function applyEndTimeConstraint(diagramData) { newEndTime = Math.round(newEndTime); newEndTime = Math.min(newEndTime, 100); newEndTime = Math.max(0, newEndTime); - return diagramData.set('end', newEndTime); + return diagramData.set('end', newEndTime).set('eventualEnd', newEndTime); } function applyDiagramDataConstraints(diagramData) { @@ -76,7 +78,8 @@ function diagramModel(props, intent) { intent.changeEndTime$, props.get('interactive') ), - isInteractive$: props.get('interactive').startWith(false) + isInteractive$: props.get('interactive').startWith(false), + isCompact$: props.get('compact').startWith(false) }; } diff --git a/src/components/diagram/diagram-view.js b/src/components/diagram/diagram-view.js index 876b172..34639d0 100644 --- a/src/components/diagram/diagram-view.js +++ b/src/components/diagram/diagram-view.js @@ -8,97 +8,176 @@ import {mergeStyles, textUnselectable} from 'rxmarbles/styles/utils'; const MARBLE_WIDTH = 5; // estimate of a marble width, in percentages const diagramSidePadding = Dimens.spaceMedium; -const diagramVerticalMargin = Dimens.spaceLarge; const diagramArrowThickness = '2px'; const diagramArrowSidePadding = Dimens.spaceLarge; const diagramArrowHeadSize = '8px'; const diagramArrowColor = Colors.black; +const diagramArrowColorGhost = Colors.almostWhite; const diagramMarbleSize = Dimens.spaceLarge; const diagramCompletionHeight = '44px'; -const diagramStyle = mergeStyles({ - position: 'relative', - display: 'block', - width: '100%', - height: `calc(${diagramMarbleSize} + 2 * ${diagramVerticalMargin})`, - overflow: 'visible', - cursor: 'default'}, - textUnselectable -); - -const diagramBodyStyle = { - position: 'absolute', - left: `calc(${diagramArrowSidePadding} + ${diagramSidePadding} - + (${diagramMarbleSize} / 2))`, - right: `calc(${diagramArrowSidePadding} + ${diagramSidePadding} - + (${diagramMarbleSize} / 2))`, - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2))`, - height: diagramCompletionHeight, - marginTop: `calc(0px - (${diagramCompletionHeight} / 2))` -}; - -function renderMarble(marbleData, isDraggable = false) { +function diagramVerticalMargin(isCompact) { + return isCompact ? Dimens.spaceSmall : Dimens.spaceLarge; +} + +function diagramStyle(isCompact) { + return mergeStyles({ + position: 'relative', + display: 'block', + width: '100%', + height: `calc(${diagramMarbleSize} + 2 * ${diagramVerticalMargin(isCompact)})`, + overflow: 'visible', + cursor: 'default' + }, + textUnselectable + ); +} + +const paddingToTimeline = `(${diagramArrowSidePadding} + ${diagramSidePadding} + (${diagramMarbleSize} / 2))`; +const timelineSize = `(100% - (2 * ${paddingToTimeline}))`; +function timeLeftPosition(time) { + return `(${paddingToTimeline} + (${timelineSize} * ${time / 100}))`; +} +function timeRightPosition(time) { + return `(${paddingToTimeline} + (${timelineSize} * ${(100 - time) / 100}))`; +} + +function diagramBodyStyle(isCompact) { + return { + position: 'absolute', + left: `calc(${paddingToTimeline})`, + right: `calc(${paddingToTimeline})`, + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2))`, + height: diagramCompletionHeight, + marginTop: `calc(0px - (${diagramCompletionHeight} / 2))` + }; +} + +function renderMarble(marbleData, isDraggable = false, isGhost = false) { return h('x-marble.diagramMarble', { key: `marble${marbleData.get('id')}`, data: marbleData, isDraggable, - style: {size: diagramMarbleSize} + style: {size: diagramMarbleSize}, + isGhost }); } -function renderCompletion(diagramData, isDraggable = false) { - let endTime = diagramData.get('end'); +function renderEndpoints(diagramData, isDraggable = false) { + var endpoints = [ + renderEndpoint(diagramData, 'start', 'diagramStart', false, false), + renderEndpoint(diagramData, 'end', 'diagramCompletion', isDraggable, false) + ]; + + // add the eventualEndpoint if it is past the actyal end + if (diagramData.get('eventualEnd') > diagramData.get('end')) { + endpoints.push(renderEndpoint(diagramData, 'eventualEnd', 'diagramEventualEnd', false, true)); + } + + return endpoints; +} + +function renderEndpoint(diagramData, timeName, endpointType, isDraggable, isGhost) { + let endTime = diagramData.get(timeName); + // do not render if the time is not defined, or it was at the end of our simulation + if (endTime === undefined || endTime >= 100) { + return undefined; + } + + let color = isGhost ? diagramArrowColorGhost : diagramArrowColor; + let isTall = diagramData.get('notifications').some(marbleData => - Math.abs(marbleData.get('time') - diagramData.get('end')) <= MARBLE_WIDTH*0.5 + Math.abs(marbleData.get('time') - endTime) <= MARBLE_WIDTH*0.5 ); - return h('x-diagram-completion.diagramCompletion', { - key: 'completion', + return h('x-diagram-completion.' + endpointType, { + key: endpointType, time: endTime, isDraggable, isTall, style: { thickness: diagramArrowThickness, - color: diagramArrowColor, + color: color, height: diagramCompletionHeight } }); } -function renderDiagramArrow() { - return h('div.diagramArrow', {style: { - backgroundColor: diagramArrowColor, +function renderDiagramArrow(data, isCompact) { + /* render the line in 3 segments: + * - to the left of 'start' render ghosted + * - render between start & end normal + * - to the right of 'end' render ghosted + */ + const arrowStyle = { height: diagramArrowThickness, position: 'absolute', - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2))`, - left: diagramSidePadding, - right: diagramSidePadding - }}); + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2))` + }; + let sections = []; + let start = data.get('start'); + let end = data.get('end'); + let middleStart = diagramSidePadding; + let middleEnd = diagramSidePadding; + + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: middleStart, + right: `calc(${timeRightPosition(start)})` + }) + })); + middleStart = `calc(${timeLeftPosition(start)})`; + + if (end < 100) { + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: `calc(${timeLeftPosition(end)})`, + right: middleEnd + }) + })); + middleEnd = `calc(${timeRightPosition(end)})`; + } + + if (start < end) { + sections.push(h('div.diagramArrow', { + style: mergeStyles(arrowStyle, { + backgroundColor: diagramArrowColor, + left: middleStart, + right: middleEnd + }) + })); + } + + return sections; } -function renderDiagramArrowHead() { +function renderDiagramArrowHead(data, isCompact) { + let end = data.get('end'); + let isGhost = end < 100; + let color = isGhost ? diagramArrowColorGhost : diagramArrowColor; return h('div.diagramArrowHead', {style: { width: 0, height: 0, borderTop: `${diagramArrowHeadSize} solid transparent`, borderBottom: `${diagramArrowHeadSize} solid transparent`, - borderLeft: `calc(2 * ${diagramArrowHeadSize}) solid ${diagramArrowColor}`, + borderLeft: `calc(2 * ${diagramArrowHeadSize}) solid ${color}`, display: 'inline-block', right: `calc(${diagramSidePadding} - 1px)`, position: 'absolute', - top: `calc(${diagramVerticalMargin} + (${diagramMarbleSize} / 2) + top: `calc(${diagramVerticalMargin(isCompact)} + (${diagramMarbleSize} / 2) - ${diagramArrowHeadSize} + (${diagramArrowThickness} / 2))` }}); } -function renderDiagram(data, isInteractive) { +function renderDiagram(data, isInteractive, isCompact) { let marblesVTree = data.get('notifications') - .map(notification => renderMarble(notification, isInteractive)) + .map(notification => renderMarble(notification, isInteractive, notification.get('time') > (data.get('end') + 0.01))) .toArray(); // from Immutable.List - let completionVTree = renderCompletion(data, isInteractive); - return h('div', {style: diagramStyle}, [ - renderDiagramArrow(), - renderDiagramArrowHead(), - h('div', {style: diagramBodyStyle}, [completionVTree].concat(marblesVTree)) + return h('div', {style: diagramStyle(isCompact)}, [ + renderDiagramArrow(data, isCompact), + renderDiagramArrowHead(data, isCompact), + h('div', {style: diagramBodyStyle(isCompact)}, renderEndpoints(data, isInteractive).concat(marblesVTree)) ]) } @@ -147,6 +226,7 @@ function diagramView(model) { vtree$: Rx.Observable.combineLatest( animateData$(model.data$).merge(model.newData$), model.isInteractive$, + model.isCompact$, renderDiagram ) }; diff --git a/src/components/marble.js b/src/components/marble.js index d2cf8a3..13cc6dd 100644 --- a/src/components/marble.js +++ b/src/components/marble.js @@ -16,9 +16,9 @@ function createContainerStyle(inputStyle) { }; } -function renderSvg(data, isDraggable, inputStyle, isHighlighted) { +function renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost) { let POSSIBLE_COLORS = [Colors.blue, Colors.green, Colors.yellow, Colors.red]; - let color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + let color = isGhost ? Colors.almostWhite : POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; return svg('svg.marbleShape', { style: { overflow: 'visible', @@ -29,7 +29,7 @@ function renderSvg(data, isDraggable, inputStyle, isHighlighted) { [ svg('circle', { style: mergeStyles({ - stroke: Colors.black, + stroke: isGhost ? Colors.greyLight : Colors.black, fill: color }, isDraggable && isHighlighted ? marbleElevation1Style : {}), @@ -42,21 +42,27 @@ function renderSvg(data, isDraggable, inputStyle, isHighlighted) { ); } -function renderInnerContent(data, inputStyle) { +function renderInnerContent(data, inputStyle, isGhost) { + var style = { + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size + }; + + if (isGhost) { + style['color'] = Colors.greyLight; + } + return h('p.marbleContent', { - style: mergeStyles({ - position: 'absolute', - width: '100%', - height: '100%', - top: '0', - margin: '0', - textAlign: 'center', - lineHeight: inputStyle.size}, - textUnselectable) + style: mergeStyles(style, textUnselectable) }, `${data.get('content')}`); } -function render(data, isDraggable, inputStyle, isHighlighted) { +function render(data, isDraggable, inputStyle, isHighlighted, isGhost) { let draggableContainerStyle = { cursor: 'ew-resize' }; @@ -68,8 +74,8 @@ function render(data, isDraggable, inputStyle, isHighlighted) { isDraggable ? draggableContainerStyle : null), attributes: {'data-marble-id': data.get('id')} },[ - renderSvg(data, isDraggable, inputStyle, isHighlighted), - renderInnerContent(data, inputStyle) + renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost), + renderInnerContent(data, inputStyle, isGhost) ]); } @@ -78,13 +84,14 @@ function marbleComponent({DOM, props}) { let stopHighlight$ = DOM.get('.marbleRoot', 'mouseleave'); let data$ = props.get('data'); let isDraggable$ = props.get('isDraggable').startWith(false); + let isGhost$ = props.get('isGhost').startWith(false); let style$ = props.get('style').startWith({}); let isHighlighted$ = Rx.Observable.merge( startHighlight$.map(() => true), stopHighlight$.map(() => false) ).startWith(false); let vtree$ = Rx.Observable.combineLatest( - data$, isDraggable$, style$, isHighlighted$, render + data$, isDraggable$, style$, isHighlighted$, isGhost$, render ); return { diff --git a/src/components/sandbox/sandbox-input.js b/src/components/sandbox/sandbox-input.js index dca421e..156abaf 100644 --- a/src/components/sandbox/sandbox-input.js +++ b/src/components/sandbox/sandbox-input.js @@ -28,11 +28,13 @@ function prepareNotification(input, diagramId) { function prepareInputDiagram(diagram, indexInDiagramArray = 0) { let last = diagram[diagram.length - 1]; - return Immutable.Map({}) + let end = (typeof last === 'number') ? last : 100; + return Immutable.Map({ start: 0 }) .set('notifications', getNotifications(diagram) .map(notification => prepareNotification(notification, indexInDiagramArray)) ) - .set('end', (typeof last === 'number') ? last : 100) + .set('end', end) + .set('eventualEnd', end) .set('id', indexInDiagramArray); } diff --git a/src/components/sandbox/sandbox-output.js b/src/components/sandbox/sandbox-output.js index 7a402d8..fd18ff2 100644 --- a/src/components/sandbox/sandbox-output.js +++ b/src/components/sandbox/sandbox-output.js @@ -20,6 +20,7 @@ function makeScheduler() { return scheduler; } + /** * Creates an (virtual time) Rx.Observable from diagram * data (array of data items). @@ -36,56 +37,138 @@ function toVTStream(diagramData, scheduler) { }); } -function getDiagramPromise(stream, scheduler) { - let diagram = {}; - let subject = new Rx.BehaviorSubject([]); - stream - .observeOn(scheduler) - .timestamp(scheduler) - .map(x => { - if (typeof x.value !== 'object') { - x.value = Immutable.Map({ - content: x.value, - id: Utils.calculateNotificationContentHash(x.value) - }); - } - // converts timestamp to % of MAX_VT_TIME - return x.value.set('time', (x.timestamp / MAX_VT_TIME) * 100); - }) - .reduce((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(); +/** + * Wraps the observable and collects usage information + * Each time the observable is subscribed, produces a notification stream that shows + * - when the subscription started + * - each notification produced + * - when the subscription ended + * - any remaining notifications that would have occurred had the subscription continued + * @param stream + * @param scheduler + * @param correctedMaxTime + */ +function observeUsage(stream, scheduler, correctedMaxTime) { + let subject = new Rx.Subject(); + let diagrams = subject.takeUntilWithTime(new Date(correctedMaxTime), scheduler); + let newStream = Rx.Observable.create(observer => { + let subscribeEnd = new Rx.AsyncSubject(); + let onUnsubscribe = Rx.Disposable.create(() => { + subscribeEnd.onNext(scheduler.now()); + subscribeEnd.onCompleted(); + }); + let p = stream.publish(); + let diagram = diagramStream(p, scheduler, correctedMaxTime); + let finalDiagram = diagram.combineLatest(subscribeEnd, (diagram, e) => { + // eventualEnd is when the stream would have finished had we not unsubscribed + diagram.eventualEnd = diagram.end; + + // end is when the observer unsubscribed (or the stream ended naturally) + diagram.end = e; + return diagram; }); - return subject.asObservable(); + + // Give the observer his information + p.subscribe(observer); + + // watch final diagram ourselves + subject.onNext(finalDiagram); + + // start the flow + p.connect(); + + return onUnsubscribe; + }); + + return { + diagrams, + stream: newStream + }; +} + +function getObservedStreams(diagrams, scheduler, correctedMaxTime) { + let observedStreams = diagrams.get('diagrams') + .map(diagram => toVTStream(diagram, scheduler)) + .map(s => observeUsage(s, scheduler, correctedMaxTime)); + let inputStreams = observedStreams.map(s => s.stream); + // merge all the diagram streams such that we can keep a FIFO order on the final diagrams + let observedInputDiagramStream = Rx.Observable + .merge(observedStreams.map(s => s.diagrams)) + .flatMap((d$, i) => d$.map(diag => { + return {diag, i}; + })) + .toArray() + .map(results => results.sort((a, b) => a.i - b.i).map(r => r.diag)) + .publishLast(); + observedInputDiagramStream.connect(); + let observedInputDiagrams = observedInputDiagramStream.startWith([]); + + return {inputStreams, observedInputDiagrams}; +} + +function diagramStream(stream, scheduler, correctedMaxTime) { + return Rx.Observable.defer(() => { + let diagram = {start: scheduler.now()}; + return stream + .observeOn(scheduler) + .timestamp(scheduler) + .takeUntilWithTime(new Date(correctedMaxTime), scheduler) + .map(x => { + if (typeof x.value !== 'object') { + x.value = Immutable.Map({ + content: x.value, + id: Utils.calculateNotificationContentHash(x.value) + }); + } + // converts timestamp to % of MAX_VT_TIME + return x.value.set('time', (x.timestamp / MAX_VT_TIME) * 100); + }) + .catch(e => { + console.warn('Error in the diagram promise stream: ' + e); + return Rx.Observable.empty(); + }) + .toArray() + .map(notifications => { + diagram.end = scheduler.now(); + diagram.notifications = notifications; + return diagram; + }); + }); +} + +function getDiagramPromise(stream, scheduler, correctedMaxTime) { + let s = diagramStream(stream, scheduler, correctedMaxTime).publishLast(); + s.connect(); + return s.startWith([]); } function toImmutableDiagramData(diagramData) { return Immutable.Map({}) .set('notifications', Immutable.List(diagramData.notifications).map(Immutable.Map)) - .set('end', diagramData.end); + .set('end', diagramData.end) + .set('start', diagramData.start) + .set('eventualEnd', diagramData.eventualEnd || diagramData.end ); } function getOutputDiagram$(example$, inputDiagrams$) { return inputDiagrams$ .withLatestFrom(example$, (diagrams, example) => { let vtscheduler = makeScheduler(); - let inputVTStreams = diagrams.get('diagrams') - .map(diagram => toVTStream(diagram, vtscheduler)); - let outputVTStream = example.get('apply')(inputVTStreams, vtscheduler); // Necessary hack to include marbles at exactly 100.01 let correctedMaxTime = MAX_VT_TIME + 0.02; - outputVTStream = outputVTStream.takeUntilWithTime(correctedMaxTime, vtscheduler); + let { inputStreams, observedInputDiagrams } = getObservedStreams(diagrams, vtscheduler, correctedMaxTime); + let outputVTStream = example.get('apply')(inputStreams, vtscheduler); let outputDiagram = getDiagramPromise(outputVTStream, vtscheduler, MAX_VT_TIME); vtscheduler.start(); - return outputDiagram.map(toImmutableDiagramData); + + return outputDiagram + .map(toImmutableDiagramData) + .zip(observedInputDiagrams.map(diagrams => diagrams.map(toImmutableDiagramData)), (od, ids) => { + return { + outputDiagram: od, + observedInputDiagrams: ids + }; + }); }) .mergeAll(); } diff --git a/src/components/sandbox/sandbox.js b/src/components/sandbox/sandbox.js index a5e0591..ae41340 100644 --- a/src/components/sandbox/sandbox.js +++ b/src/components/sandbox/sandbox.js @@ -12,8 +12,11 @@ import Fonts from 'rxmarbles/styles/fonts'; import {mergeStyles, elevation1Style, elevation2Style, elevation2Before, elevation2After} from 'rxmarbles/styles/utils'; -function renderOperatorLabel(label) { +function renderOperatorLabel(label, small = false) { let fontSize = (label.length >= 45) ? 1.3 : (label.length >= 30) ? 1.5 : 2; + if (small) { + fontSize *= 0.5; + } let style = { fontFamily: Fonts.fontCode, fontWeight: '400', @@ -22,20 +25,29 @@ function renderOperatorLabel(label) { return h('span.operatorLabel', {style}, label); } -function renderOperator(label) { +function renderOperator(label, small = false) { let style = mergeStyles({ border: '1px solid rgba(0,0,0,0.06)', - padding: Dimens.spaceMedium, + padding: small ? Dimens.spaceTiny : Dimens.spaceMedium, textAlign: 'center'}, elevation2Style ); return h('div.operatorBox', {style}, [ elevation2Before, - renderOperatorLabel(label), + renderOperatorLabel(label, small), elevation2After ]); } +function renderObservedInputs(inputs) { + return inputs.map((input, i) => h('x-diagram.sandboxObservedInput', { + key: "observedInput" + i, + data: input, + interactive: false, + compact: true + })); +} + function getSandboxStyle(width) { return mergeStyles({ background: Colors.white, @@ -45,8 +57,8 @@ function getSandboxStyle(width) { ); } -function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { - return h('div.sandboxRoot', {style: getSandboxStyle(width)}, [ +function renderSandbox(inputDiagrams, operatorLabel, outputDiagramData, width, showSubscriptions) { + let children = [ inputDiagrams.get('diagrams').map((diagram, index) => h('x-diagram.sandboxInputDiagram', { key: `inputDiagram${index}`, @@ -57,10 +69,17 @@ function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { renderOperator(operatorLabel), h('x-diagram.sandboxOutputDiagram', { key: 'outputDiagram', - data: outputDiagram, + data: outputDiagramData.outputDiagram, interactive: false - }) - ]); + })]; + + if (showSubscriptions) { + children.push( + renderOperator("subscription details", true), + renderObservedInputs(outputDiagramData.observedInputDiagrams)); + } + + return h('div.sandboxRoot', {style: getSandboxStyle(width)}, children); } function makeInputDiagrams(example) { @@ -87,6 +106,7 @@ function sandboxComponent({DOM, props}) { let changeInputDiagram$ = DOM.get('.sandboxInputDiagram', 'newdata') .map(ev => ev.detail); let width$ = props.get('width').startWith('100%'); + let showSubscriptions$ = props.get('showSubscriptions').startWith(true); let example$ = props.get('route') .filter(isTruthy) .map(key => Immutable.Map(Examples[key]).set('key', key)) @@ -100,11 +120,17 @@ function sandboxComponent({DOM, props}) { ); let operatorLabel$ = example$.map(example => example.get('label')); let firstOutputDiagram$ = getOutputDiagram$(example$, inputDiagrams$) - .map(markAsFirstDiagram); + .map(d => { + return { + outputDiagram: markAsFirstDiagram(d.outputDiagram), + observedInputDiagrams: d.observedInputDiagrams.map(markAsFirstDiagram) + }; + }) let newOutputDiagram$ = getOutputDiagram$(example$, newInputDiagrams$); let outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); let vtree$ = Rx.Observable.combineLatest( inputDiagrams$, operatorLabel$, outputDiagram$, width$, + showSubscriptions$, renderSandbox ); From 422c0e0a8f7c4704848bba2514fd5932b4cda981 Mon Sep 17 00:00:00 2001 From: Brandon Wallace Date: Thu, 4 Jun 2015 00:08:02 -0500 Subject: [PATCH 6/7] Update examples, add new repeat() example --- src/data/combine-examples.js | 12 ++++---- src/data/conditional-examples.js | 12 +++++++- src/data/filter-examples.js | 52 ++++++++++++++++++++++---------- 3 files changed, 53 insertions(+), 23 deletions(-) diff --git a/src/data/combine-examples.js b/src/data/combine-examples.js index e5620d1..e29ebc7 100644 --- a/src/data/combine-examples.js +++ b/src/data/combine-examples.js @@ -15,7 +15,7 @@ module.exports = { }, "concat": { - "label": "concat", + "label": "concat(a, b)", "inputs": [ [{t:0, d:1}, {t:15, d:1}, {t:50, d:1}, 57], [{t:0, d:2}, {t:8, d:2}, 12] @@ -26,7 +26,7 @@ module.exports = { }, "merge": { - "label": "merge", + "label": "merge(a, b)", "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}] @@ -37,7 +37,7 @@ module.exports = { }, "sample": { - "label": "sample", + "label": "a.sample(b)", "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] @@ -58,7 +58,7 @@ module.exports = { }, "withLatestFrom": { - "label": "withLatestFrom((x, y) => \"\" + x + y)", + "label": "xs.withLatestFrom(ys, (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"}] @@ -71,10 +71,10 @@ module.exports = { }, "zip": { - "label": "zip", + "label": "zip(xs, ys, (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"}] + [{t:10, d:"A"}, {t:25, d:"B"}, {t:50, d:"C"}, {t:57, d:"D"}, 70] ], "apply": function(inputs) { return Rx.Observable.zip(inputs[0], inputs[1], diff --git a/src/data/conditional-examples.js b/src/data/conditional-examples.js index 490508c..7131aa1 100644 --- a/src/data/conditional-examples.js +++ b/src/data/conditional-examples.js @@ -2,7 +2,7 @@ import {Rx} from '@cycle/core'; module.exports = { "amb": { - "label": "amb", + "label": "amb(a, b, c)", "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}], @@ -11,5 +11,15 @@ module.exports = { "apply": function(inputs) { return Rx.Observable.amb(inputs); } + }, + + "repeat": { + "label": "a.repeat()", + "inputs": [ + [{t: 5, d: 1}, {t: 10, d: 2}, {t: 20, d: 3}, 35] + ], + "apply": function (inputs) { + return inputs[0].repeat(); + } } }; diff --git a/src/data/filter-examples.js b/src/data/filter-examples.js index 2bb245a..ff8bf83 100644 --- a/src/data/filter-examples.js +++ b/src/data/filter-examples.js @@ -72,30 +72,50 @@ module.exports = { }, "pausable": { - "label": "pausable", + "label": "a.publish(p => p.pausable(signal))", "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}] + [{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}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] + ], + "apply": function(inputs) { + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].publish(p => p.pausable(signal)); + } + }, + + "pausable(cold)": { + "label": "a.pausable(signal)", + "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}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] ], "apply": function(inputs) { - inputs[0].subscribe(() => 0); - var subject = new Rx.Subject(); - inputs[1].subscribe(x => subject.onNext(x.get('content'))); - return inputs[0].pausable(subject); + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].pausable(signal); } }, "pausableBuffered": { - "label": "pausableBuffered", + "label": "a.publish(p => p.pausableBuffered(signal))", "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}] + [{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}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] ], "apply": function(inputs) { - inputs[0].subscribe(() => 0); - var subject = new Rx.Subject(); - inputs[1].subscribe(x => subject.onNext(x.get('content'))); - return inputs[0].pausableBuffered(subject); + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].publish(p => p.pausableBuffered(signal)); + } + }, + + "pausableBuffered(cold)": { + "label": "a.pausableBuffered(signal)", + "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}, 85], + [{t:15, d:true}, {t:35, d:false}, {t:55, d:true}, 70] + ], + "apply": function(inputs) { + let signal = inputs[1].map(x => x.get('content')); + return inputs[0].pausableBuffered(signal); } }, @@ -112,7 +132,7 @@ module.exports = { "skipLast": { "label": "skipLast(2)", "inputs": [ - [{t:30, d:1}, {t:40, d:2}, {t:65, d:3}, {t:75, d:4}] + [{t:30, d:1}, {t:40, d:2}, {t:65, d:3}, {t:75, d:4}, 80 ] ], "apply": function(inputs) { return inputs[0].skipLast(2); @@ -123,7 +143,7 @@ module.exports = { "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}] + [{t:45, d:0}, {t:73, d:0}, 80] ], "apply": function(inputs) { return inputs[0].skipUntil(inputs[1]); From 09b408fe15c202612c8ea7626784bf0c2bb2698a Mon Sep 17 00:00:00 2001 From: Herman Banken Date: Thu, 22 Sep 2016 13:16:29 +0200 Subject: [PATCH 7/7] Build --- dist/js/app.js | 39218 ++++++++++++++++++++++++----------------------- 1 file changed, 20084 insertions(+), 19134 deletions(-) diff --git a/dist/js/app.js b/dist/js/app.js index 8a99ba3..cffba49 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -1,11588 +1,12920 @@ (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 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) { - runTimeout(drainQueue); - } -}; +function run(main, drivers) { + if (typeof main !== "function") { + throw new Error("First argument given to Cycle.run() must be the 'main' " + "function."); + } + if (typeof drivers !== "object" || drivers === null) { + throw new Error("Second argument given to Cycle.run() must be an object " + "with driver functions as properties."); + } + if (isObjectEmpty(drivers)) { + throw new Error("Second argument given to Cycle.run() must be an object " + "with at least one driver function declared as a property."); + } -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; + var requestProxies = makeRequestProxies(drivers); + var rawResponses = callDrivers(drivers, requestProxies); + var responses = makeAppInput(requestProxies, rawResponses); + var requests = main(responses); + setTimeout(function () { + return replicateMany(requests, requestProxies); + }, 1); + return [requests, responses]; } -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; +var Cycle = { + /** + * Takes an `main` function and circularly connects it to the given collection + * of driver functions. + * + * The `main` function expects a collection of "driver response" Observables + * as input, and should return a collection of "driver request" Observables. + * A "collection of Observables" is a JavaScript object where + * keys match the driver names registered by the `drivers` object, and values + * are Observables or a collection of Observables. + * + * @param {Function} main a function that takes `responses` as input + * and outputs a collection of `requests` Observables. + * @param {Object} drivers an object where keys are driver names and values + * are driver functions. + * @return {Array} an array where the first object is the collection of driver + * requests, and the second object is the collection of driver responses, that + * can be used for debugging or testing. + * @function run + */ + run: run, -process.binding = function (name) { - throw new Error('process.binding is not supported'); + /** + * A shortcut to the root object of + * [RxJS](https://github.com/Reactive-Extensions/RxJS). + * @name Rx + */ + Rx: Rx }; -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],3:[function(require,module,exports){ +module.exports = Cycle; +},{"rx":71}],2:[function(require,module,exports){ 'use strict'; -var _core = require('@cycle/core'); +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 packageJson = require('package'); -var RxPackageJson = require('rx/package.json'); +var _require = require('@cycle/core'); -var DEFAULT_EXAMPLE = 'merge'; +var Rx = _require.Rx; -module.exports = function appModel() { - var route$ = _core.Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { - return hashEvent.target.location.hash.replace('#', ''); - }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE); - var appVersion$ = _core.Rx.Observable.just(packageJson.version); - var rxVersion$ = _core.Rx.Observable.just(RxPackageJson.version); - return _core.Rx.Observable.combineLatest(route$, appVersion$, rxVersion$, function (route, appVersion, rxVersion) { - return { route: route, appVersion: appVersion, rxVersion: rxVersion }; - }); -}; -},{"@cycle/core":29,"package":154,"rx/package.json":101}],4:[function(require,module,exports){ -'use strict'; +var ALL_PROPS = '*'; +var PROPS_DRIVER_NAME = 'props'; +var EVENTS_SINK_NAME = 'events'; -var _dom = require('@cycle/dom'); +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); + }; +} -var _colors = require('rxmarbles/styles/colors'); +function subscribeDispatchers(element) { + var customEvents = element.cycleCustomElementMetadata.customEvents; -var _colors2 = _interopRequireDefault(_colors); + 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; +} -var _dimens = require('rxmarbles/styles/dimens'); +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); + }); +} -var _dimens2 = _interopRequireDefault(_dimens); +function subscribeEventDispatchingSink(element, widget) { + element.cycleCustomElementMetadata.eventDispatchingSubscription = subscribeDispatchers(element); + widget.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); + widget.disposables.add(subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)); +} -var _fonts = require('rxmarbles/styles/fonts'); +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]; -var _fonts2 = _interopRequireDefault(_fonts); + 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; +} -var _utils = require('rxmarbles/styles/utils'); +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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +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.'); + } +} -var rxmarblesGithubUrl = 'https://github.com/staltz/rxmarbles'; -var rxjsGithubUrl = 'https://github.com/Reactive-Extensions/RxJS'; +function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) { + var _ref; -var pageRowWidth = '1060px'; -var sandboxWidth = '820px'; + return (_ref = {}, _defineProperty(_ref, domDriverName, domOutput), _defineProperty(_ref, PROPS_DRIVER_NAME, propertiesDriver), _ref); +} -var pageRowStyle = { - position: 'relative', - width: pageRowWidth, - margin: '0 auto' -}; +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(); + }; +} -var pageRowChildStyle = { - display: 'inline-block' -}; +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.')); + } + } + } +} -var pageRowFirstChildStyle = (0, _utils.mergeStyles)(pageRowChildStyle, { - width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _dimens2.default.spaceMedium + ')' -}); +function makeInit(tagName, definitionFn) { + var _require2 = require('./render-dom'); -var pageRowLastChildStyle = (0, _utils.mergeStyles)(pageRowChildStyle, { - width: sandboxWidth -}); + var makeDOMDriverWithRegistry = _require2.makeDOMDriverWithRegistry; -function renderHeader() { - return (0, _dom.h)('div', { style: pageRowStyle }, [(0, _dom.h)('h1', { style: (0, _utils.mergeStyles)({ - fontFamily: _fonts2.default.fontSpecial, - color: _colors2.default.greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), (0, _dom.h)('h3', { style: (0, _utils.mergeStyles)({ - color: _colors2.default.greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); + 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 renderContent(route) { - var style = (0, _utils.mergeStyles)(pageRowStyle, { marginTop: _dimens2.default.spaceSmall }); - return (0, _dom.h)('div', { style: style }, [(0, _dom.h)('div', { style: pageRowFirstChildStyle }, (0, _dom.h)('x-operators-menu', { key: 'operatorsMenu' })), (0, _dom.h)('div', { style: (0, _utils.mergeStyles)({ - position: 'absolute', - top: '0' }, pageRowLastChildStyle) }, (0, _dom.h)('x-sandbox', { key: 'sandbox', route: route, width: '820px' }))]); +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 renderFooter(appVersion, rxVersion) { - var style = { - position: 'fixed', - bottom: '2px', - right: _dimens2.default.spaceMedium, - color: _colors2.default.greyDark - }; - return (0, _dom.h)('section', { style: style }, [(0, _dom.h)('a', { href: rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', (0, _dom.h)('a', { href: rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', (0, _dom.h)('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); -} +function updateCustomElement(previous, element) { + if (previous) { + this.disposables = previous.disposables; + this.firstRootElem$.onNext(0); + this.firstRootElem$.onCompleted(); + } + validatePropertiesDriverInMetadata(element, 'update()'); -module.exports = function appView(state$) { - var wrapperStyle = { - paddingLeft: _dimens2.default.spaceSmall, - paddingRight: 'calc(' + _dimens2.default.spaceHuge + ' + ' + _dimens2.default.spaceSmall + ')' - }; - return state$.map(function (_ref) { - var route = _ref.route; - var appVersion = _ref.appVersion; - var rxVersion = _ref.rxVersion; - return (0, _dom.h)('div', { style: wrapperStyle }, [(0, _utils.renderSvgDropshadow)(), renderHeader(), renderContent(route), renderFooter(appVersion, rxVersion)]); - }); -}; -},{"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28}],5:[function(require,module,exports){ -'use strict'; + //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]); + } + } + } +} -var _core = require('@cycle/core'); +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(); +} -var _core2 = _interopRequireDefault(_core); +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 _dom = require('@cycle/dom'); + 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; +} -var _appModel = require('rxmarbles/app-model'); +module.exports = { + makeDispatchFunction: makeDispatchFunction, + subscribeDispatchers: subscribeDispatchers, + subscribeDispatchersWhenRootChanges: subscribeDispatchersWhenRootChanges, + makePropertiesDriver: makePropertiesDriver, + createContainerElement: createContainerElement, + throwIfVTreeHasPropertyChildren: throwIfVTreeHasPropertyChildren, + makeConstructor: makeConstructor, + makeInit: makeInit, + updateCustomElement: updateCustomElement, + destroyCustomElement: destroyCustomElement, -var _appModel2 = _interopRequireDefault(_appModel); + ALL_PROPS: ALL_PROPS, + makeCustomElementInput: makeCustomElementInput, + makeWidgetClass: makeWidgetClass +}; +},{"./render-dom":5,"@cycle/core":1}],3:[function(require,module,exports){ +'use strict'; -var _appView = require('rxmarbles/app-view'); +var _require = require('./custom-element-widget'); -var _appView2 = _interopRequireDefault(_appView); +var makeWidgetClass = _require.makeWidgetClass; -var _operatorsMenuLink = require('rxmarbles/components/operators-menu-link'); +var Map = Map || require('es6-map'); // eslint-disable-line no-native-reassign -var _operatorsMenuLink2 = _interopRequireDefault(_operatorsMenuLink); +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; +} -var _operatorsMenu = require('rxmarbles/components/operators-menu'); +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; +} -var _operatorsMenu2 = _interopRequireDefault(_operatorsMenu); +module.exports = { + replaceCustomElementsWithSomething: replaceCustomElementsWithSomething, + makeCustomElementsRegistry: makeCustomElementsRegistry +}; +},{"./custom-element-widget":2,"es6-map":53}],4:[function(require,module,exports){ +'use strict'; +var VirtualDOM = require('virtual-dom'); +var svg = require('virtual-dom/virtual-hyperscript/svg'); -var _sandbox = require('rxmarbles/components/sandbox/sandbox'); +var _require = require('./render-dom'); -var _sandbox2 = _interopRequireDefault(_sandbox); +var makeDOMDriver = _require.makeDOMDriver; -var _diagram = require('rxmarbles/components/diagram/diagram'); +var _require2 = require('./render-html'); -var _diagram2 = _interopRequireDefault(_diagram); +var makeHTMLDriver = _require2.makeHTMLDriver; -var _marble = require('rxmarbles/components/marble'); +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, -var _marble2 = _interopRequireDefault(_marble); + /** + * 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, -var _diagramCompletion = require('rxmarbles/components/diagram-completion'); + /** + * 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, -var _diagramCompletion2 = _interopRequireDefault(_diagramCompletion); + /** + * 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]; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return VirtualDOM.h(tag, attrs, children); + }, -function main() { - return { - DOM: (0, _appView2.default)((0, _appModel2.default)()) - }; -} + /** + * A shortcut to the svg hyperscript function. + * @name svg + */ + svg: svg +}; -_core2.default.run(main, { - DOM: (0, _dom.makeDOMDriver)('.js-appContainer', { - 'x-operators-menu-link': _operatorsMenuLink2.default, - 'x-operators-menu': _operatorsMenu2.default, - 'x-sandbox': _sandbox2.default, - 'x-marble': _marble2.default, - 'x-diagram-completion': _diagramCompletion2.default, - 'x-diagram': _diagram2.default - }) -}); -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/app-model":3,"rxmarbles/app-view":4,"rxmarbles/components/diagram-completion":6,"rxmarbles/components/diagram/diagram":10,"rxmarbles/components/marble":11,"rxmarbles/components/operators-menu":13,"rxmarbles/components/operators-menu-link":12,"rxmarbles/components/sandbox/sandbox":16}],6:[function(require,module,exports){ +module.exports = CycleDOM; +},{"./render-dom":5,"./render-html":6,"virtual-dom":480,"virtual-dom/virtual-hyperscript/svg":494}],5:[function(require,module,exports){ 'use strict'; -var _core = require('@cycle/core'); +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 _dom = require('@cycle/dom'); +var _require = require('@cycle/core'); -var _utils = require('rxmarbles/styles/utils'); +var Rx = _require.Rx; -function createContainerStyle(inputStyle) { - return { - display: 'inline-block', - position: 'relative', - width: 'calc(8 * ' + inputStyle.thickness + ')', - height: inputStyle.height, - margin: '0 calc(-4 * ' + inputStyle.thickness + ')' - }; -} +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 () {} +}; -function createInnerStyle(inputStyle) { - return { - width: inputStyle.thickness, - height: '50%', - marginLeft: 'calc(3.5 * ' + inputStyle.thickness + ')', - marginTop: 'calc(' + inputStyle.height + ' / 4.0)', - backgroundColor: inputStyle.color - }; +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 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, _dom.h)('div.completionRoot', { - style: (0, _utils.mergeStyles)({ - left: time + '%' }, containerStyle, isDraggable ? draggableContainerStyle : {}) - }, [(0, _dom.h)('div.completionInner', { - style: (0, _utils.mergeStyles)(innerStyle, isDraggable && isHighlighted ? _utils.elevation1Style : null, isTall ? innerTallStyle : null) - })]); +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 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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { - return true; - }), stopHighlight$.map(function () { - return false; - })).startWith(false); - var vtree$ = _core.Rx.Observable.combineLatest(time$, isDraggable$, isTall$, style$, isHighlighted$, render); +function isVTreeCustomElement(vtree) { + return vtree.type === 'Widget' && vtree.isCustomElementWidget; +} - return { - DOM: vtree$ +function makeReplaceCustomElementsWithWidgets(CERegistry, driverName) { + return function replaceCustomElementsWithWidgets(vtree) { + return replaceCustomElementsWithSomething(vtree, CERegistry, function (_vtree, WidgetClass) { + return new WidgetClass(_vtree, CERegistry, driverName); + }); }; } -module.exports = diagramCompletionComponent; -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/utils":28}],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 _core = require('@cycle/core'); +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; +} -var _immutable = require('immutable'); +function checkRootVTreeNotCustomElement(vtree) { + if (isVTreeCustomElement(vtree)) { + throw new Error('Illegal to use a Cycle custom element as the root of ' + 'a View.'); + } +} -var _immutable2 = _interopRequireDefault(_immutable); +function isRootForCustomElement(rootElem) { + return !!rootElem.cycleCustomElementMetadata; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function wrapTopLevelVTree(vtree, rootElem) { + if (isRootForCustomElement(rootElem)) { + return vtree; + } -var mouseMove$ = _core.Rx.Observable.fromEvent(document, 'mousemove'); -var mouseUp$ = _core.Rx.Observable.fromEvent(document, 'mouseup'); + 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; -function getPxToPercentageRatio(element) { - var pxToPercentage = void 0; - 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 + 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]); } - 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]; +function makeDiffAndPatchToElement$(rootElem) { + return function diffAndPatchToElement$(_ref) { + var _ref2 = _slicedToArray(_ref, 2); - 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(); -} + var oldVTree = _ref2[0]; + var newVTree = _ref2[1]; -function diagramIntent(DOM) { - var marbleMouseDown$ = DOM.get('.diagramMarble', 'mousedown'); - var completionMouseDown$ = DOM.get('.diagramCompletion', 'mousedown'); + if (typeof newVTree === 'undefined') { + return Rx.Observable.empty(); + } - return { - changeMarbleTime$: makeDeltaTime$(marbleMouseDown$, function (deltaTime, target) { - return _immutable2.default.Map({ - deltaTime: deltaTime, - id: target.attributes['data-marble-id'].value - }); - }), - changeEndTime$: makeDeltaTime$(completionMouseDown$) + //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$; + } }; } -module.exports = diagramIntent; -},{"@cycle/core":29,"immutable":94}],8:[function(require,module,exports){ -'use strict'; - -var _core = require('@cycle/core'); +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 findLargestMarbleTime(diagramData) { - return diagramData.get('notifications').max(function (notifA, notifB) { - if (notifA.get('time') < notifB.get('time')) { - return -1; +function makeRootElemToEvent$(selector, eventName) { + return function rootElemToEvent$(rootElem) { + if (!rootElem) { + return Rx.Observable.empty(); } - if (notifA.get('time') > notifB.get('time')) { - return 1; + //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); } - 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); + 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 { - return notif; + //console.log('%c returning empty!', 'color: #0000BB'); + return Rx.Observable.empty(); } - })); + }; } -function applyChangeEndTime(diagramData, endDelta) { - return diagramData.set('end', diagramData.get('end') + endDelta); +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 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 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 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$ = _core.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); +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) }; - })).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":29}],9:[function(require,module,exports){ -'use strict'; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; - -var _core = require('@cycle/core'); - -var _dom = require('@cycle/dom'); - -var _colors = require('rxmarbles/styles/colors'); - -var _colors2 = _interopRequireDefault(_colors); - -var _dimens = require('rxmarbles/styles/dimens'); - -var _dimens2 = _interopRequireDefault(_dimens); +function makeDOMDriver(container) { + var customElementDefinitions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; -var _fonts = require('rxmarbles/styles/fonts'); + // 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 _fonts2 = _interopRequireDefault(_fonts); + var registry = makeCustomElementsRegistry(customElementDefinitions); + return makeDOMDriverWithRegistry(domContainer, registry); +} -var _rxtween = require('rxtween'); +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, -var _rxtween2 = _interopRequireDefault(_rxtween); + makeDOMDriver: makeDOMDriver +}; +},{"./custom-elements":3,"@cycle/core":1,"vdom-parser":470,"virtual-dom":480,"virtual-dom/diff":478,"virtual-dom/patch":481}],6:[function(require,module,exports){ +'use strict'; -var _utils = require('rxmarbles/styles/utils'); +var _require = require('@cycle/core'); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var Rx = _require.Rx; -var MARBLE_WIDTH = 5; // estimate of a marble width, in percentages -var diagramSidePadding = _dimens2.default.spaceMedium; -var diagramVerticalMargin = _dimens2.default.spaceLarge; -var diagramArrowThickness = '2px'; -var diagramArrowSidePadding = _dimens2.default.spaceLarge; -var diagramArrowHeadSize = '8px'; -var diagramArrowColor = _colors2.default.black; -var diagramMarbleSize = _dimens2.default.spaceLarge; -var diagramCompletionHeight = '44px'; +var toHTML = require('vdom-to-html'); -var diagramStyle = (0, _utils.mergeStyles)({ - position: 'relative', - display: 'block', - width: '100%', - height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin + ')', - overflow: 'visible', - cursor: 'default' }, _utils.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))' -}; +var _require2 = require('./custom-elements'); -function renderMarble(marbleData) { - var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; +var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; +var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; - return (0, _dom.h)('x-marble.diagramMarble', { - key: 'marble' + marbleData.get('id'), - data: marbleData, - isDraggable: isDraggable, - style: { size: diagramMarbleSize } - }); -} +var _require3 = require('./custom-element-widget'); -function renderCompletion(diagramData) { - var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; +var makeCustomElementInput = _require3.makeCustomElementInput; +var ALL_PROPS = _require3.ALL_PROPS; - 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, _dom.h)('x-diagram-completion.diagramCompletion', { - key: 'completion', - time: endTime, - isDraggable: isDraggable, - isTall: isTall, - style: { - thickness: diagramArrowThickness, - color: diagramArrowColor, - height: diagramCompletionHeight +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 renderDiagramArrow() { - return (0, _dom.h)('div.diagramArrow', { style: { - backgroundColor: diagramArrowColor, - height: diagramArrowThickness, - position: 'absolute', - top: 'calc(' + diagramVerticalMargin + ' + (' + diagramMarbleSize + ' / 2))', - left: diagramSidePadding, - right: diagramSidePadding - } }); + }; } -function renderDiagramArrowHead() { - return (0, _dom.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))' - } }); -} +/** + * 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]; + } -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, _dom.h)('div', { style: diagramStyle }, [renderDiagramArrow(), renderDiagramArrowHead(), (0, _dom.h)('div', { style: diagramBodyStyle }, [completionVTree].concat(marblesVTree))]); + vtree.children = arr; + return vtree; + }); + } else if (vtree.type === 'VirtualNode') { + return Rx.Observable.just(vtree); + } else { + throw new Error('Unhandled case in transposeVTree()'); + } } -function sanitizeDiagramItem(x) { - return Math.max(0, Math.min(100, x)); +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 interpolate(from, to, x) { - return from * (1 - x) + to * x; +function convertCustomElementsToVTree(vtree$, CERegistry, driverName) { + return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry, driverName)).flatMap(transposeVTree); } -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 _core.Rx.Observable.just(data); +function makeResponseGetter() { + return function get(selector) { + if (selector === ':root') { + return this; } 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 === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + return Rx.Observable.empty(); } - }); -} - -function diagramView(model) { - return { - vtree$: _core.Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, renderDiagram) }; } -module.exports = diagramView; -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28,"rxtween":110}],10:[function(require,module,exports){ -'use strict'; - -var _diagramModel = require('rxmarbles/components/diagram/diagram-model'); - -var _diagramModel2 = _interopRequireDefault(_diagramModel); +function makeHTMLDriver() { + var customElementDefinitions = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; -var _diagramView = require('rxmarbles/components/diagram/diagram-view'); - -var _diagramView2 = _interopRequireDefault(_diagramView); - -var _diagramIntent = require('rxmarbles/components/diagram/diagram-intent'); - -var _diagramIntent2 = _interopRequireDefault(_diagramIntent); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function DiagramComponent(_ref) { - var DOM = _ref.DOM; - var props = _ref.props; - - var intent = (0, _diagramIntent2.default)(DOM); - var model = (0, _diagramModel2.default)(props, intent); - var view = (0, _diagramView2.default)(model); - - return { - DOM: view.vtree$, - events: { - newdata: model.newData$ - } + 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 = DiagramComponent; -},{"rxmarbles/components/diagram/diagram-intent":7,"rxmarbles/components/diagram/diagram-model":8,"rxmarbles/components/diagram/diagram-view":9}],11:[function(require,module,exports){ -'use strict'; - -var _core = require('@cycle/core'); - -var _dom = require('@cycle/dom'); - -var _colors = require('rxmarbles/styles/colors'); - -var _colors2 = _interopRequireDefault(_colors); +module.exports = { + makePropertiesDriverFromVTree: makePropertiesDriverFromVTree, + makeReplaceCustomElementsWithVTree$: makeReplaceCustomElementsWithVTree$, + convertCustomElementsToVTree: convertCustomElementsToVTree, -var _utils = require('rxmarbles/styles/utils'); + makeHTMLDriver: makeHTMLDriver +}; +},{"./custom-element-widget":2,"./custom-elements":3,"@cycle/core":1,"vdom-to-html":474}],7:[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 + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * 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) { -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' - }; -} + var nativeSplit = String.prototype.split, + compliantExecNpcg = /()??/.exec("")[1] === undef, + // NPCG: nonparticipating capturing group + self; -function renderSvg(data, isDraggable, inputStyle, isHighlighted) { - var POSSIBLE_COLORS = [_colors2.default.blue, _colors2.default.green, _colors2.default.yellow, _colors2.default.red]; - var color = POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; - return (0, _dom.svg)('svg.marbleShape', { - style: { - overflow: 'visible', - width: inputStyle.size, - height: inputStyle.size - }, - attributes: { viewBox: '0 0 1 1' } }, [(0, _dom.svg)('circle', { - style: (0, _utils.mergeStyles)({ - stroke: _colors2.default.black, - fill: color - }, isDraggable && isHighlighted ? _utils.marbleElevation1Style : {}), - attributes: { - cx: 0.5, cy: 0.5, r: 0.47, - 'stroke-width': '0.06px' + 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); } - })]); -} - -function renderInnerContent(data, inputStyle) { - return (0, _dom.h)('p.marbleContent', { - style: (0, _utils.mergeStyles)({ - position: 'absolute', - width: '100%', - height: '100%', - top: '0', - margin: '0', - textAlign: 'center', - lineHeight: inputStyle.size }, _utils.textUnselectable) - }, '' + data.get('content')); -} - -function render(data, isDraggable, inputStyle, isHighlighted) { - var draggableContainerStyle = { - cursor: 'ew-resize' + 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 (0, _dom.h)('div.marbleRoot', { - style: (0, _utils.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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { - return true; - }), stopHighlight$.map(function () { - return false; - })).startWith(false); - var vtree$ = _core.Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, render); - - return { - DOM: vtree$ - }; -} + return self; +})(); -module.exports = marbleComponent; -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/utils":28}],12:[function(require,module,exports){ +},{}],8:[function(require,module,exports){ 'use strict'; -var _core = require('@cycle/core'); - -var _dom = require('@cycle/dom'); - -var _colors = require('rxmarbles/styles/colors'); +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') -var _colors2 = _interopRequireDefault(_colors); + , bind = Function.prototype.bind, defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , define; -var _dimens = require('rxmarbles/styles/dimens'); +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; +}; -var _dimens2 = _interopRequireDefault(_dimens); +module.exports = function (props/*, bindTo*/) { + var bindTo = arguments[1]; + return map(props, function (desc, name) { + return define(name, desc, bindTo); + }); +}; -var _utils = require('rxmarbles/styles/utils'); +},{"es5-ext/object/copy":21,"es5-ext/object/map":29,"es5-ext/object/valid-callable":35,"es5-ext/object/valid-value":36}],9:[function(require,module,exports){ +'use strict'; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +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') -function operatorsMenuLink(_ref) { - var DOM = _ref.DOM; - var props = _ref.props; + , d; - 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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { - return true; - }), stopHighlight$.map(function () { - return false; - })).startWith(false); - var highlightingArrow = (0, _dom.h)('span', { - style: { - display: 'inline-block', - position: 'absolute', - right: _dimens2.default.spaceTiny } - }, '❯'); - var vtree$ = _core.Rx.Observable.combineLatest(href$, content$, isHighlighted$, function (href, content, isHighlighted) { - return (0, _dom.h)('a.link', { - style: (0, _utils.mergeStyles)({ - position: 'relative', - display: 'block', - color: _colors2.default.greyDark }, isHighlighted ? { color: _colors2.default.black } : null), - href: href }, [content, isHighlighted ? highlightingArrow : null]); - }); - - return { DOM: vtree$ }; -} +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'); + } -module.exports = operatorsMenuLink; -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/utils":28}],13:[function(require,module,exports){ -'use strict'; + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; -var _core = require('@cycle/core'); +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'); + } -var _dom = require('@cycle/dom'); + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; -var _colors = require('rxmarbles/styles/colors'); +},{"es5-ext/object/assign":18,"es5-ext/object/is-callable":24,"es5-ext/object/normalize-options":30,"es5-ext/string/#/contains":37}],10:[function(require,module,exports){ +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear -var _colors2 = _interopRequireDefault(_colors); +'use strict'; -var _dimens = require('rxmarbles/styles/dimens'); +var value = require('../../object/valid-value'); -var _dimens2 = _interopRequireDefault(_dimens); +module.exports = function () { + value(this).length = 0; + return this; +}; -var _examples = require('rxmarbles/data/examples'); +},{"../../object/valid-value":36}],11:[function(require,module,exports){ +'use strict'; -var _examples2 = _interopRequireDefault(_examples); +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') -var _utils = require('rxmarbles/styles/utils'); + , indexOf = Array.prototype.indexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function (searchElement/*, fromIndex*/) { + var i, l, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return indexOf.apply(this, arguments); + } -/** - * 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; -} + 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)); -var operatorsMenuCategoryStyle = { - textTransform: 'uppercase', - fontSize: '0.7em', - color: _colors2.default.grey, - marginTop: _dimens2.default.spaceMedium + for (i = fromIndex; i < l; ++i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; }; -var operatorsMenuItemStyle = { - color: _colors2.default.greyDark, - fontSize: '1rem', - lineHeight: '1.6rem' +},{"../../number/to-pos-integer":16,"../../object/valid-value":36}],12:[function(require,module,exports){ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sign + : require('./shim'); + +},{"./is-implemented":13,"./shim":14}],13:[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)); }; -function renderExampleItem(example) { - return (0, _dom.h)('li', { style: operatorsMenuItemStyle }, (0, _dom.h)('x-operators-menu-link', { - key: 'operatorsMenuLink' + example.key, - href: '#' + example.key, - content: example.key - })); -} +},{}],14:[function(require,module,exports){ +'use strict'; -function renderExampleItems(examples) { - var items = []; - for (var i = 0; i < examples.length; i++) { - var example = examples[i]; - items.push(renderExampleItem(example)); - } - return items; -} +module.exports = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return (value > 0) ? 1 : -1; +}; -function renderExampleCategory(categoryName, isFirstCategory) { - return (0, _dom.h)('li', { - style: (0, _utils.mergeStyles)(operatorsMenuCategoryStyle, isFirstCategory ? { marginTop: '0' } : {}) }, '' + categoryName); -} +},{}],15:[function(require,module,exports){ +'use strict'; -function renderMenuContent(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, _dom.h)('li', { style: operatorsMenuCategoryStyle }, 'More')); - listItems.push((0, _dom.h)('li', { style: operatorsMenuItemStyle }, 'Coming soon...')); - return listItems; -} +var sign = require('../math/sign') -function operatorsMenuComponent() { - var categoryMap$ = _core.Rx.Observable.just(organizeExamplesByCategory(_examples2.default)); + , abs = Math.abs, floor = Math.floor; - return { - DOM: categoryMap$.map(function (categoryMap) { - return (0, _dom.h)('div', { style: { - paddingRight: '36px', - boxSizing: 'border-box', - // 100px is the estimated header page row height - height: 'calc(100vh - 100px)' } }, [(0, _dom.h)('ul', { style: { - margin: '0', - padding: '0', - listStyleType: 'none', - overflowY: 'scroll', - height: '100%' } }, renderMenuContent(categoryMap))]); - }) - }; -} +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)); +}; -module.exports = operatorsMenuComponent; -},{"@cycle/core":29,"@cycle/dom":32,"rxmarbles/data/examples":21,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/utils":28}],14:[function(require,module,exports){ +},{"../math/sign":12}],16:[function(require,module,exports){ 'use strict'; -var _core = require('@cycle/core'); - -var _utils = require('rxmarbles/components/sandbox/utils'); +var toInteger = require('./to-integer') -var _utils2 = _interopRequireDefault(_utils); + , max = Math.max; -var _immutable = require('immutable'); +module.exports = function (value) { return max(0, toInteger(value)); }; -var _immutable2 = _interopRequireDefault(_immutable); +},{"./to-integer":15}],17:[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 -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +'use strict'; -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); - } -} /* - * Functions to handle data of input diagrams in the example shown in the - * sandbox. - */ +var callable = require('./valid-callable') + , value = require('./valid-value') + , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; -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', _utils2.default.calculateNotificationHash({ time: input.t, content: input.d })); -} - -function prepareInputDiagram(diagram) { - var indexInDiagramArray = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; +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); - 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); -} + 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); + }); + }; +}; -function augmentWithExampleKey(diagramData, exampleKey) { - return diagramData.set('example', exampleKey).set('notifications', diagramData.get('notifications').map(function (notif) { - return notif.set('example', exampleKey); - })); -} +},{"./valid-callable":35,"./valid-value":36}],18:[function(require,module,exports){ +'use strict'; -function replaceDiagramDataIn(diagrams, newDiagramData) { - return diagrams.map(function (diagramData) { - if (diagramData.get('id') === newDiagramData.get('id')) { - return newDiagramData; - } else { - return diagramData; - } - }); -} +module.exports = require('./is-implemented')() + ? Object.assign + : require('./shim'); -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)); - }); - }); -} +},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){ +'use strict'; -module.exports = { - prepareInputDiagram: prepareInputDiagram, - augmentWithExampleKey: augmentWithExampleKey, - makeNewInputDiagramsData$: makeNewInputDiagramsData$ +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'; }; -},{"@cycle/core":29,"immutable":94,"rxmarbles/components/sandbox/utils":17}],15:[function(require,module,exports){ -'use strict'; -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* - * Functions to handle data of the output diagram in the example shown in the - * sandbox. - */ +},{}],20:[function(require,module,exports){ +'use strict'; +var keys = require('../keys') + , value = require('../valid-value') -var _core = require('@cycle/core'); + , max = Math.max; -var _utils = require('rxmarbles/components/sandbox/utils'); +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; +}; -var _utils2 = _interopRequireDefault(_utils); +},{"../keys":26,"../valid-value":36}],21:[function(require,module,exports){ +'use strict'; -var _immutable = require('immutable'); +var assign = require('./assign') + , value = require('./valid-value'); -var _immutable2 = _interopRequireDefault(_immutable); +module.exports = function (obj) { + var copy = Object(value(obj)); + if (copy !== obj) return copy; + return assign({}, obj); +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./assign":18,"./valid-value":36}],22:[function(require,module,exports){ +// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 -var MAX_VT_TIME = 100; // Time of completion +'use strict'; -function makeScheduler() { - var scheduler = new _core.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; -} +var create = Object.create, shim; -function justIncomplete(item, scheduler) { - return new _core.Rx.AnonymousObservable(function (observer) { - return scheduler.schedule(function () { - observer.onNext(item); - }); - }); +if (!require('./set-prototype-of/is-implemented')()) { + shim = require('./set-prototype-of/shim'); } -/** - * 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 _core.Rx.Observable.merge(singleMarbleStreams).takeUntilWithTime(correctedEndTime, scheduler).publish().refCount(); -} +module.exports = (function () { + var nullObject, props, desc; + if (!shim) return create; + if (shim.level !== 1) return create; -function getDiagramPromise(stream, scheduler) { - var diagram = {}; - var subject = new _core.Rx.BehaviorSubject([]); - stream.observeOn(scheduler).timestamp(scheduler).map(function (x) { - if (_typeof(x.value) !== 'object') { - x.value = _immutable2.default.Map({ - content: x.value, - id: _utils2.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(); -} + 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); -function toImmutableDiagramData(diagramData) { - return _immutable2.default.Map({}).set('notifications', _immutable2.default.List(diagramData.notifications).map(_immutable2.default.Map)).set('end', diagramData.end); -} + Object.defineProperty(shim, 'nullPolyfill', { configurable: false, + enumerable: false, writable: false, value: nullObject }); -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(); -} + return function (prototype, props) { + return create((prototype === null) ? nullObject : prototype, props); + }; +}()); -module.exports = { - getOutputDiagram$: getOutputDiagram$ -}; -},{"@cycle/core":29,"immutable":94,"rxmarbles/components/sandbox/utils":17}],16:[function(require,module,exports){ +},{"./set-prototype-of/is-implemented":33,"./set-prototype-of/shim":34}],23:[function(require,module,exports){ 'use strict'; -var _core = require('@cycle/core'); +module.exports = require('./_iterate')('forEach'); -var _dom = require('@cycle/dom'); +},{"./_iterate":17}],24:[function(require,module,exports){ +// Deprecated -var _rxtween = require('rxtween'); +'use strict'; -var _rxtween2 = _interopRequireDefault(_rxtween); +module.exports = function (obj) { return typeof obj === 'function'; }; -var _examples = require('rxmarbles/data/examples'); +},{}],25:[function(require,module,exports){ +'use strict'; -var _examples2 = _interopRequireDefault(_examples); +var map = { function: true, object: true }; -var _sandboxInput = require('rxmarbles/components/sandbox/sandbox-input'); +module.exports = function (x) { + return ((x != null) && map[typeof x]) || false; +}; -var _sandboxOutput = require('rxmarbles/components/sandbox/sandbox-output'); +},{}],26:[function(require,module,exports){ +'use strict'; -var _immutable = require('immutable'); +module.exports = require('./is-implemented')() + ? Object.keys + : require('./shim'); -var _immutable2 = _interopRequireDefault(_immutable); +},{"./is-implemented":27,"./shim":28}],27:[function(require,module,exports){ +'use strict'; -var _colors = require('rxmarbles/styles/colors'); +module.exports = function () { + try { + Object.keys('primitive'); + return true; + } catch (e) { return false; } +}; -var _colors2 = _interopRequireDefault(_colors); +},{}],28:[function(require,module,exports){ +'use strict'; -var _dimens = require('rxmarbles/styles/dimens'); +var keys = Object.keys; -var _dimens2 = _interopRequireDefault(_dimens); +module.exports = function (object) { + return keys(object == null ? object : Object(object)); +}; -var _fonts = require('rxmarbles/styles/fonts'); +},{}],29:[function(require,module,exports){ +'use strict'; -var _fonts2 = _interopRequireDefault(_fonts); +var callable = require('./valid-callable') + , forEach = require('./for-each') -var _utils = require('rxmarbles/styles/utils'); + , call = Function.prototype.call; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +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; +}; -function renderOperatorLabel(label) { - var fontSize = label.length >= 45 ? 1.3 : label.length >= 30 ? 1.5 : 2; - var style = { - fontFamily: _fonts2.default.fontCode, - fontWeight: '400', - fontSize: fontSize + 'rem' - }; - return (0, _dom.h)('span.operatorLabel', { style: style }, label); -} +},{"./for-each":23,"./valid-callable":35}],30:[function(require,module,exports){ +'use strict'; -function renderOperator(label) { - var style = (0, _utils.mergeStyles)({ - border: '1px solid rgba(0,0,0,0.06)', - padding: _dimens2.default.spaceMedium, - textAlign: 'center' }, _utils.elevation2Style); - return (0, _dom.h)('div.operatorBox', { style: style }, [_utils.elevation2Before, renderOperatorLabel(label), _utils.elevation2After]); -} +var forEach = Array.prototype.forEach, create = Object.create; -function getSandboxStyle(width) { - return (0, _utils.mergeStyles)({ - background: _colors2.default.white, - width: width, - borderRadius: '2px' }, _utils.elevation1Style); -} - -function renderSandbox(inputDiagrams, operatorLabel, outputDiagram, width) { - return (0, _dom.h)('div.sandboxRoot', { style: getSandboxStyle(width) }, [inputDiagrams.get('diagrams').map(function (diagram, index) { - return (0, _dom.h)('x-diagram.sandboxInputDiagram', { - key: 'inputDiagram' + index, - data: diagram, - interactive: true - }); - }), renderOperator(operatorLabel), (0, _dom.h)('x-diagram.sandboxOutputDiagram', { - key: 'outputDiagram', - data: outputDiagram, - interactive: false - })]); -} - -function makeInputDiagrams(example) { - return _immutable2.default.Map({ - 'diagrams': example.get('inputs').map(_sandboxInput.prepareInputDiagram).map(function (diag) { - return (0, _sandboxInput.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 process = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; -var isTruthy = function isTruthy(x) { - return !!x; +module.exports = function (options/*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (options == null) return; + process(Object(options), result); + }); + return result; }; -function sandboxComponent(_ref) { - var DOM = _ref.DOM; - var props = _ref.props; +},{}],31:[function(require,module,exports){ +'use strict'; - 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(_examples2.default[key]).set('key', key); - }).shareReplay(1); - var inputDiagrams$ = example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1); - var newInputDiagrams$ = (0, _sandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$, inputDiagrams$); - var operatorLabel$ = example$.map(function (example) { - return example.get('label'); - }); - var firstOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, inputDiagrams$).map(markAsFirstDiagram); - var newOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, newInputDiagrams$); - var outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); - var vtree$ = _core.Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, renderSandbox); +var forEach = Array.prototype.forEach, create = Object.create; - return { - DOM: vtree$ - }; -} +module.exports = function (arg/*, …args*/) { + var set = create(null); + forEach.call(arguments, function (name) { set[name] = true; }); + return set; +}; -module.exports = sandboxComponent; -},{"@cycle/core":29,"@cycle/dom":32,"immutable":94,"rxmarbles/components/sandbox/sandbox-input":14,"rxmarbles/components/sandbox/sandbox-output":15,"rxmarbles/data/examples":21,"rxmarbles/styles/colors":25,"rxmarbles/styles/dimens":26,"rxmarbles/styles/fonts":27,"rxmarbles/styles/utils":28,"rxtween":110}],17:[function(require,module,exports){ -"use strict"; +},{}],32:[function(require,module,exports){ +'use strict'; -/* - * Conversion from virtual time streams out to diagram data, and - * vice-versa, and related functions. - */ +module.exports = require('./is-implemented')() + ? Object.setPrototypeOf + : require('./shim'); -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; - } -} +},{"./is-implemented":33,"./shim":34}],33:[function(require,module,exports){ +'use strict'; -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; -} +var create = Object.create, getPrototypeOf = Object.getPrototypeOf + , x = {}; -module.exports = { - calculateNotificationHash: calculateNotificationHash, - calculateNotificationContentHash: calculateNotificationContentHash +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; }; -},{}],18:[function(require,module,exports){ -"use strict"; -var _core = require("@cycle/core"); +},{}],34:[function(require,module,exports){ +// Big thanks to @WebReflection for sorting this out +// https://gist.github.com/WebReflection/5593554 -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; - }); - } - }, +'use strict'; - "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; - }); - } - }, +var isObject = require('../is-object') + , value = require('../valid-value') - "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); - } - }, + , isPrototypeOf = Object.prototype.isPrototypeOf + , defineProperty = Object.defineProperty + , nullDesc = { configurable: true, enumerable: false, writable: true, + value: undefined } + , validate; - "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'); - }); - } - } +validate = function (obj, prototype) { + value(obj); + if ((prototype === null) || isObject(prototype)) return obj; + throw new TypeError('Prototype must be null or an object'); }; -},{"@cycle/core":29}],19:[function(require,module,exports){ -"use strict"; -var _core = require("@cycle/core"); +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__'); -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 _core.Rx.Observable.combineLatest(inputs[0], inputs[1], function (x, y) { - return "" + x.get('content') + y.get('content'); - }); - } - }, + 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 }; + } - "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 _core.Rx.Observable.concat(inputs); - } - }, + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 2 }; - "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 _core.Rx.Observable.merge(inputs); - } - }, + x = {}; + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 1 }; - "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]); - } - }, + return false; +}()))); - "startWith": { - "label": "startWith(1)", - "inputs": [[{ t: 30, d: 2 }, { t: 40, d: 3 }]], - "apply": function apply(inputs, scheduler) { - return inputs[0].startWith(scheduler, 1); - } - }, +require('../create'); - "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'); - }); - } - }, +},{"../create":22,"../is-object":25,"../valid-value":36}],35:[function(require,module,exports){ +'use strict'; - "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 _core.Rx.Observable.zip(inputs[0], inputs[1], function (x, y) { - return "" + x.get('content') + y.get('content'); - }); - } - } +module.exports = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; }; -},{"@cycle/core":29}],20:[function(require,module,exports){ -"use strict"; -var _core = 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 _core.Rx.Observable.amb(inputs); - } - } -}; -},{"@cycle/core":29}],21:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ 'use strict'; -/* - * The database of all predefined examples in the app. - */ -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 < 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; +module.exports = function (value) { + if (value == null) throw new TypeError("Cannot use null or undefined"); + return value; }; -module.exports = 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")); -},{"rxmarbles/data/boolean-examples":18,"rxmarbles/data/combine-examples":19,"rxmarbles/data/conditional-examples":20,"rxmarbles/data/filter-examples":22,"rxmarbles/data/math-examples":23,"rxmarbles/data/transform-examples":24}],22:[function(require,module,exports){ -"use strict"; - -var _core = require("@cycle/core"); +},{}],37:[function(require,module,exports){ +'use strict'; -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'); - }); - } - }, +module.exports = require('./is-implemented')() + ? String.prototype.contains + : require('./shim'); - "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'); - }); - } - }, +},{"./is-implemented":38,"./shim":39}],38:[function(require,module,exports){ +'use strict'; - "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); - } - }, +var str = 'razdwatrzy'; - "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; - }); - } - }, +module.exports = function () { + if (typeof str.contains !== 'function') return false; + return ((str.contains('dwa') === true) && (str.contains('foo') === false)); +}; - "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; - }); - } - }, +},{}],39:[function(require,module,exports){ +'use strict'; - "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(); - } - }, +var indexOf = String.prototype.indexOf; - "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(); - } - }, +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; - "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 _core.Rx.Subject(); - inputs[1].subscribe(function (x) { - return subject.onNext(x.get('content')); - }); - return inputs[0].pausable(subject); - } - }, +},{}],40:[function(require,module,exports){ +'use strict'; - "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 _core.Rx.Subject(); - inputs[1].subscribe(function (x) { - return subject.onNext(x.get('content')); - }); - return inputs[0].pausableBuffered(subject); - } - }, +var toString = Object.prototype.toString - "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); - } - }, + , id = toString.call(''); - "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); - } - }, +module.exports = function (x) { + return (typeof x === 'string') || (x && (typeof x === 'object') && + ((x instanceof String) || (toString.call(x) === id))) || false; +}; - "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]); - } - }, +},{}],41:[function(require,module,exports){ +'use strict'; - "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); - } - }, +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , Iterator = require('./') - "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); - } - }, + , defineProperty = Object.defineProperty + , ArrayIterator; - "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]); - } - } +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)); }; -},{"@cycle/core":29}],23:[function(require,module,exports){ -"use strict"; +if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); -var _core = require("@cycle/core"); +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]'; }) +}); -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} - // ) - // } +},{"./":44,"d":9,"es5-ext/object/set-prototype-of":32,"es5-ext/string/#/contains":37}],42:[function(require,module,exports){ +'use strict'; - "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'); - }); - } - }, +var callable = require('es5-ext/object/valid-callable') + , isString = require('es5-ext/string/is-string') + , get = require('./get') - "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":29}],24:[function(require,module,exports){ -"use strict"; - -var _core = 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 _core.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); - }); - } - }, + , isArray = Array.isArray, call = Function.prototype.call; - "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')); - }); - } - }, +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); - "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); - } - }, + 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(); - "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 _core.Rx.Observable.timer(Number(x.get('content')) * 10, 1000, scheduler); - }); - } - } + while (!result.done) { + call.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } }; -},{"@cycle/core":29}],25:[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' -}; -},{}],26:[function(require,module,exports){ +},{"./get":43,"es5-ext/object/valid-callable":35,"es5-ext/string/is-string":40}],43:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = { - spaceTiny: '5px', - spaceSmall: '10px', - spaceMedium: '22px', - spaceLarge: '32px', - spaceHuge: '42px', +var isString = require('es5-ext/string/is-string') + , ArrayIterator = require('./array') + , StringIterator = require('./string') + , iterable = require('./valid-iterable') + , iteratorSymbol = require('es6-symbol').iterator; - animationDurationQuick: '100ms', - animationDurationNormal: '200ms', - animationDurationSlow: '400ms' +module.exports = function (obj) { + if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); + if (isString(obj)) return new StringIterator(obj); + return new ArrayIterator(obj); }; -},{}],27:[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" -}; -},{}],28:[function(require,module,exports){ +},{"./array":41,"./string":51,"./valid-iterable":52,"es5-ext/string/is-string":40,"es6-symbol":46}],44:[function(require,module,exports){ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.textUnselectable = exports.renderSvgDropshadow = exports.marbleElevation1Style = exports.elevation3After = exports.elevation3Before = exports.elevation2After = exports.elevation2Before = exports.elevation2Style = exports.elevation1Style = exports.mergeStyles = undefined; - -var _immutable = require('immutable'); - -var _immutable2 = _interopRequireDefault(_immutable); - -var _dom = require('@cycle/dom'); +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') -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + , defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , Iterator; -var isTruthy = function isTruthy(x) { - return !!x; +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); }; -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, _dom.svg)('svg', { attributes: { height: '0' } }, [(0, _dom.svg)('filter#' + DROPSHADOW_FILTER_ID, { attributes: { height: '130%' } }, [ - // stdDeviation is blur: - (0, _dom.svg)('feGaussianBlur', { attributes: { in: 'SourceAlpha', stdDeviation: '0.05' } }), - // position relative to marble viewBox: - (0, _dom.svg)('feOffset', { attributes: { dx: '0', dy: '0.05', result: 'offsetblur' } }), (0, _dom.svg)('feFlood', { attributes: { 'flood-color': 'rgba(0,0,0,0.4)' } }), (0, _dom.svg)('feComposite', { attributes: { in2: 'offsetblur', operator: 'in' } }), (0, _dom.svg)('feMerge', [(0, _dom.svg)('feMergeNode'), (0, _dom.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)' -}; +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; + }) +}))); -var elevation2Style = { - position: 'relative' -}; +defineProperty(Iterator.prototype, Symbol.iterator, d(function () { + return this; +})); +defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); -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 + ')' - }; -} +},{"d":9,"d/auto-bind":8,"es5-ext/array/#/clear":10,"es5-ext/object/assign":18,"es5-ext/object/valid-callable":35,"es5-ext/object/valid-value":36,"es6-symbol":46}],45:[function(require,module,exports){ +'use strict'; -var elevation2Before = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '10px', '0.17') -}, ''); -var elevation2After = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '5px', '0.26') -}, ''); +var isString = require('es5-ext/string/is-string') + , iteratorSymbol = require('es6-symbol').iterator -var elevation3Before = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('6px', '20px', '0.19') -}, ''); -var elevation3After = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('6px', '17px', '0.2') -}, ''); + , isArray = Array.isArray; -var textUnselectable = { - '-webkit-user-select': 'none', - '-khtml-user-select': 'none', - '-moz-user-select': 'none', - '-o-user-select': 'none', - 'user-select': 'none' +module.exports = function (value) { + if (value == null) return false; + if (isArray(value)) return true; + if (isString(value)) return true; + return (typeof value[iteratorSymbol] === 'function'); }; -exports.mergeStyles = mergeStyles; -exports.elevation1Style = elevation1Style; -exports.elevation2Style = elevation2Style; -exports.elevation2Before = elevation2Before; -exports.elevation2After = elevation2After; -exports.elevation3Before = elevation3Before; -exports.elevation3After = elevation3After; -exports.marbleElevation1Style = marbleElevation1Style; -exports.renderSvgDropshadow = renderSvgDropshadow; -exports.textUnselectable = textUnselectable; -},{"@cycle/dom":32,"immutable":94}],29:[function(require,module,exports){ -"use strict"; +},{"es5-ext/string/is-string":40,"es6-symbol":46}],46:[function(require,module,exports){ +'use strict'; -var Rx = require("rx"); +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); -function makeRequestProxies(drivers) { - var requestProxies = {}; - for (var _name in drivers) { - if (drivers.hasOwnProperty(_name)) { - requestProxies[_name] = new Rx.ReplaySubject(1); - } - } - return requestProxies; -} +},{"./is-implemented":47,"./polyfill":49}],47:[function(require,module,exports){ +'use strict'; -function callDrivers(drivers, requestProxies) { - var responses = {}; - for (var _name2 in drivers) { - if (drivers.hasOwnProperty(_name2)) { - responses[_name2] = drivers[_name2](requestProxies[_name2], _name2); - } - } - return responses; -} +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; -function makeDispose(requestProxies, rawResponses) { - return function dispose() { - for (var x in requestProxies) { - if (requestProxies.hasOwnProperty(x)) { - requestProxies[x].dispose(); - } - } - for (var _name3 in rawResponses) { - if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === "function") { - rawResponses[_name3].dispose(); - } - } - }; -} + // 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; -function makeAppInput(requestProxies, rawResponses) { - Object.defineProperty(rawResponses, "dispose", { - enumerable: false, - value: makeDispose(requestProxies, rawResponses) - }); - return rawResponses; -} + return true; +}; -function logToConsoleError(err) { - var target = err.stack || err; - if (console && console.error) { - console.error(target); - } -} +},{}],48:[function(require,module,exports){ +'use strict'; -function replicateMany(original, imitators) { - for (var _name4 in original) { - if (original.hasOwnProperty(_name4)) { - if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) { - original[_name4].doOnError(logToConsoleError).subscribe(imitators[_name4].asObserver()); - } - } - } -} +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; -function isObjectEmpty(obj) { - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - return false; - } - } - return true; -} +},{}],49:[function(require,module,exports){ +'use strict'; -function run(main, drivers) { - if (typeof main !== "function") { - throw new Error("First argument given to Cycle.run() must be the 'main' " + "function."); - } - if (typeof drivers !== "object" || drivers === null) { - throw new Error("Second argument given to Cycle.run() must be an object " + "with driver functions as properties."); - } - if (isObjectEmpty(drivers)) { - throw new Error("Second argument given to Cycle.run() must be an object " + "with at least one driver function declared as a property."); - } +var d = require('d') + , validateSymbol = require('./validate-symbol') - var requestProxies = makeRequestProxies(drivers); - var rawResponses = callDrivers(drivers, requestProxies); - var responses = makeAppInput(requestProxies, rawResponses); - var requests = main(responses); - setTimeout(function () { - return replicateMany(requests, requestProxies); - }, 1); - return [requests, responses]; -} + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty, objPrototype = Object.prototype + , Symbol, HiddenSymbol, globalSymbols = create(null); -var Cycle = { - /** - * Takes an `main` function and circularly connects it to the given collection - * of driver functions. - * - * The `main` function expects a collection of "driver response" Observables - * as input, and should return a collection of "driver request" Observables. - * A "collection of Observables" is a JavaScript object where - * keys match the driver names registered by the `drivers` object, and values - * are Observables or a collection of Observables. - * - * @param {Function} main a function that takes `responses` as input - * and outputs a collection of `requests` Observables. - * @param {Object} drivers an object where keys are driver names and values - * are driver functions. - * @return {Array} an array where the first object is the collection of driver - * requests, and the second object is the collection of driver responses, that - * can be used for debugging or testing. - * @function run - */ - run: run, +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; + }; +}()); - /** - * A shortcut to the root object of - * [RxJS](https://github.com/Reactive-Extensions/RxJS). - * @name Rx - */ - Rx: Rx +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__; }) +}); -module.exports = Cycle; -},{"rx":100}],30:[function(require,module,exports){ -'use strict'; +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')); -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; } +defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, + d('c', Symbol.prototype[Symbol.toPrimitive])); +defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, + d('c', Symbol.prototype[Symbol.toStringTag])); -var _require = require('@cycle/core'); +},{"./validate-symbol":50,"d":9}],50:[function(require,module,exports){ +'use strict'; -var Rx = _require.Rx; +var isSymbol = require('./is-symbol'); -var ALL_PROPS = '*'; -var PROPS_DRIVER_NAME = 'props'; -var EVENTS_SINK_NAME = 'events'; +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; -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); - }; -} +},{"./is-symbol":48}],51:[function(require,module,exports){ +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols -function subscribeDispatchers(element) { - var customEvents = element.cycleCustomElementMetadata.customEvents; +'use strict'; - 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; -} +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('./') -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); - }); -} + , defineProperty = Object.defineProperty + , StringIterator; -function subscribeEventDispatchingSink(element, widget) { - element.cycleCustomElementMetadata.eventDispatchingSubscription = subscribeDispatchers(element); - widget.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); - widget.disposables.add(subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)); -} +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)); -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 (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); - 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; -} +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]'; }) +}); -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; -} +},{"./":44,"d":9,"es5-ext/object/set-prototype-of":32}],52:[function(require,module,exports){ +'use strict'; -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.'); - } -} +var isIterable = require('./is-iterable'); -function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) { - var _ref; +module.exports = function (value) { + if (!isIterable(value)) throw new TypeError(value + " is not iterable"); + return value; +}; - return (_ref = {}, _defineProperty(_ref, domDriverName, domOutput), _defineProperty(_ref, PROPS_DRIVER_NAME, propertiesDriver), _ref); -} +},{"./is-iterable":45}],53:[function(require,module,exports){ +'use strict'; -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(); - }; -} +module.exports = require('./is-implemented')() ? Map : require('./polyfill'); -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.')); - } - } - } -} +},{"./is-implemented":54,"./polyfill":58}],54:[function(require,module,exports){ +'use strict'; -function makeInit(tagName, definitionFn) { - var _require2 = require('./render-dom'); +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; - var makeDOMDriverWithRegistry = _require2.makeDOMDriverWithRegistry; + 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; +}; - 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; - }; -} +},{}],55:[function(require,module,exports){ +// Exports true if environment provides native `Map` implementation, +// whatever that is. -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 + '.'); - } -} +'use strict'; -function updateCustomElement(previous, element) { - if (previous) { - this.disposables = previous.disposables; - this.firstRootElem$.onNext(0); - this.firstRootElem$.onCompleted(); - } - validatePropertiesDriverInMetadata(element, 'update()'); +module.exports = (function () { + if (typeof Map === 'undefined') return false; + return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); +}()); - //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]); - } - } - } -} +},{}],56:[function(require,module,exports){ +'use strict'; -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(); -} +module.exports = require('es5-ext/object/primitive-set')('key', + 'value', 'key+value'); -function makeWidgetClass(tagName, definitionFn) { - if (typeof definitionFn !== 'function') { - throw new Error('A custom element definition given to the DOM driver ' + 'should be a function.'); - } +},{"es5-ext/object/primitive-set":31}],57:[function(require,module,exports){ +'use strict'; - 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; -} +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') -module.exports = { - makeDispatchFunction: makeDispatchFunction, - subscribeDispatchers: subscribeDispatchers, - subscribeDispatchersWhenRootChanges: subscribeDispatchersWhenRootChanges, - makePropertiesDriver: makePropertiesDriver, - createContainerElement: createContainerElement, - throwIfVTreeHasPropertyChildren: throwIfVTreeHasPropertyChildren, - makeConstructor: makeConstructor, - makeInit: makeInit, - updateCustomElement: updateCustomElement, - destroyCustomElement: destroyCustomElement, + , defineProperties = Object.defineProperties + , unBind = Iterator.prototype._unBind + , MapIterator; - ALL_PROPS: ALL_PROPS, - makeCustomElementInput: makeCustomElementInput, - makeWidgetClass: makeWidgetClass +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__) + }); }; -},{"./render-dom":33,"@cycle/core":29}],31:[function(require,module,exports){ -'use strict'; - -var _require = require('./custom-element-widget'); +if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); -var makeWidgetClass = _require.makeWidgetClass; +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')); -var Map = Map || require('es6-map'); // eslint-disable-line no-native-reassign +},{"./iterator-kinds":56,"d":9,"es5-ext/object/set-prototype-of":32,"es6-iterator":44,"es6-symbol":59}],58:[function(require,module,exports){ +'use strict'; -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; -} +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') -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; -} + , call = Function.prototype.call, defineProperties = Object.defineProperties + , MapPoly; -module.exports = { - replaceCustomElementsWithSomething: replaceCustomElementsWithSomething, - makeCustomElementsRegistry: makeCustomElementsRegistry +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); }; -},{"./custom-element-widget":30,"es6-map":81}],32:[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, +if (isNative) { + if (setPrototypeOf) setPrototypeOf(MapPoly, Map); + MapPoly.prototype = Object.create(Map.prototype, { + constructor: d(MapPoly) + }); +} - /** - * 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, +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')); - /** - * 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, +},{"./is-native-implemented":55,"./lib/iterator":57,"d":9,"es5-ext/array/#/clear":10,"es5-ext/array/#/e-index-of":11,"es5-ext/object/set-prototype-of":32,"es5-ext/object/valid-callable":35,"es5-ext/object/valid-value":36,"es6-iterator/for-of":42,"es6-iterator/valid-iterable":52,"es6-symbol":59,"event-emitter":64}],59:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":60,"./polyfill":61,"dup":46}],60:[function(require,module,exports){ +'use strict'; - /** - * 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]; - } +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 VirtualDOM.h(tag, attrs, children); - }, + // 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; - /** - * A shortcut to the svg hyperscript function. - * @name svg - */ - svg: svg + return true; }; -module.exports = CycleDOM; -},{"./render-dom":33,"./render-html":34,"virtual-dom":125,"virtual-dom/virtual-hyperscript/svg":139}],33:[function(require,module,exports){ +},{}],61:[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 d = require('d') -var _require = require('@cycle/core'); + , create = Object.create, defineProperties = Object.defineProperties + , generateName, Symbol; -var Rx = _require.Rx; +generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + return '@@' + desc; + }; +}()); -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 () {} +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)) + }); }; -var _require2 = require('./custom-elements'); +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')) +}); -var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; -var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; +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')); -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'; -} +},{"d":9}],62:[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 + */ -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); -} +'use strict'; -function isVTreeCustomElement(vtree) { - return vtree.type === 'Widget' && vtree.isCustomElementWidget; -} +/** + * Module variables. + * @private + */ -function makeReplaceCustomElementsWithWidgets(CERegistry, driverName) { - return function replaceCustomElementsWithWidgets(vtree) { - return replaceCustomElementsWithSomething(vtree, CERegistry, function (_vtree, WidgetClass) { - return new WidgetClass(_vtree, CERegistry, driverName); - }); - }; -} +var matchHtmlRegExp = /["'&<>]/; -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.'); - } -} +/** + * Module exports. + * @public + */ -function isRootForCustomElement(rootElem) { - return !!rootElem.cycleCustomElementMetadata; -} +module.exports = escapeHtml; -function wrapTopLevelVTree(vtree, rootElem) { - if (isRootForCustomElement(rootElem)) { - return vtree; - } +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ - 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; +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); - 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]); + if (!match) { + return str; } -} - -function makeDiffAndPatchToElement$(rootElem) { - return function diffAndPatchToElement$(_ref) { - var _ref2 = _slicedToArray(_ref, 2); - var oldVTree = _ref2[0]; - var newVTree = _ref2[1]; + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; - if (typeof newVTree === 'undefined') { - return Rx.Observable.empty(); + 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; } - //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$; + if (lastIndex !== index) { + html += str.substring(lastIndex, index); } - }; -} -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$); -} + lastIndex = index + 1; + html += escape; + } -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(); - } - }; + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; } -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.'); - } +},{}],63:[function(require,module,exports){ +'use strict'; - //console.log(`%cget("${selector}", "${eventName}")`, 'color: #0000BB'); - return rootElem$.flatMapLatest(makeRootElemToEvent$(selector, eventName)).share(); - }; -} +var OneVersionConstraint = require('individual/one-version'); -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'); - } -} +var MY_VERSION = '7'; +OneVersionConstraint('ev-store', MY_VERSION); -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) - }; - }; -} +var hashKey = '__EV_STORE_KEY@' + MY_VERSION; -function makeDOMDriver(container) { - var customElementDefinitions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; +module.exports = EvStore; - // 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.'); - } +function EvStore(elem) { + var hash = elem[hashKey]; - var registry = makeCustomElementsRegistry(customElementDefinitions); - return makeDOMDriverWithRegistry(domContainer, registry); -} + if (!hash) { + hash = elem[hashKey] = {}; + } -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, + return hash; +} - makeDOMDriver: makeDOMDriver -}; -},{"./custom-elements":31,"@cycle/core":29,"vdom-parser":115,"virtual-dom":125,"virtual-dom/diff":123,"virtual-dom/patch":126}],34:[function(require,module,exports){ +},{"individual/one-version":67}],64:[function(require,module,exports){ 'use strict'; -var _require = require('@cycle/core'); +var d = require('d') + , callable = require('es5-ext/object/valid-callable') -var Rx = _require.Rx; + , 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 } -var toHTML = require('vdom-to-html'); + , on, once, off, emit, methods, descriptors, base; -var _require2 = require('./custom-elements'); +on = function (type, listener) { + var data; -var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; -var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; + callable(listener); -var _require3 = require('./custom-element-widget'); + 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]; -var makeCustomElementInput = _require3.makeCustomElementInput; -var ALL_PROPS = _require3.ALL_PROPS; + return this; +}; -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]); - } +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":9,"es5-ext/object/valid-callable":35}],65:[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; } -/** - * 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]; - } +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"min-document":509}],66:[function(require,module,exports){ +(function (global){ +'use strict'; - vtree.children = arr; - return vtree; - }); - } else if (vtree.type === 'VirtualNode') { - return Rx.Observable.just(vtree); - } else { - throw new Error('Unhandled case in transposeVTree()'); - } -} +/*global window, global*/ -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 */ - }); - }; -} +var root = typeof window !== 'undefined' ? + window : typeof global !== 'undefined' ? + global : {}; -function convertCustomElementsToVTree(vtree$, CERegistry, driverName) { - return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry, driverName)).flatMap(transposeVTree); -} +module.exports = Individual; -function makeResponseGetter() { - return function get(selector) { - if (selector === ':root') { - return this; - } else { - return Rx.Observable.empty(); +function Individual(key, value) { + if (key in root) { + return root[key]; } - }; + + root[key] = value; + + return value; } -function makeHTMLDriver() { - var customElementDefinitions = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],67:[function(require,module,exports){ +'use strict'; - 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$; - }; +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); } -module.exports = { - makePropertiesDriverFromVTree: makePropertiesDriverFromVTree, - makeReplaceCustomElementsWithVTree$: makeReplaceCustomElementsWithVTree$, - convertCustomElementsToVTree: convertCustomElementsToVTree, +},{"./index.js":66}],68:[function(require,module,exports){ +"use strict"; - makeHTMLDriver: makeHTMLDriver +module.exports = function isObject(x) { + return typeof x === "object" && x !== null; }; -},{"./custom-element-widget":30,"./custom-elements":31,"@cycle/core":29,"vdom-to-html":119}],35:[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 - */ +},{}],69:[function(require,module,exports){ /** - * 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'] + * Special language-specific overrides. * - * // With limit - * split('a b c d', ' ', 2); - * // -> ['a', 'b'] + * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt * - * // Backreferences in result array - * split('..word1 word2..', /([a-z]+)(\d+)/i); - * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] + * @type {Object} */ -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); +var LANGUAGES = { + tr: { + regexp: /\u0130|\u0049|\u0049\u0307/g, + map: { + '\u0130': '\u0069', + '\u0049': '\u0131', + '\u0049\u0307': '\u0069' } - /* 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 - } + }, + az: { + regexp: /[\u0130]/g, + map: { + '\u0130': '\u0069', + '\u0049': '\u0131', + '\u0049\u0307': '\u0069' } - if (lastLastIndex === str.length) { - if (lastLength || !separator.test("")) { - output.push(""); - } - } else { - output.push(str.slice(lastLastIndex)); + }, + 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' } - return output.length > limit ? output.slice(0, limit) : output; - }; - - return self; -})(); + } +} -},{}],36:[function(require,module,exports){ -'use strict'; +/** + * Lowercase a string. + * + * @param {String} str + * @return {String} + */ +module.exports = function (str, locale) { + var lang = LANGUAGES[locale] -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') + str = str == null ? '' : String(str) - , bind = Function.prototype.bind, defineProperty = Object.defineProperty - , hasOwnProperty = Object.prototype.hasOwnProperty - , define; + if (lang) { + str = str.replace(lang.regexp, function (m) { return lang.map[m] }) + } -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; -}; + return str.toLowerCase() +} -module.exports = function (props/*, bindTo*/) { - var bindTo = arguments[1]; - return map(props, function (desc, name) { - return define(name, desc, bindTo); - }); -}; +},{}],70:[function(require,module,exports){ +var sentenceCase = require('sentence-case') -},{"es5-ext/object/copy":49,"es5-ext/object/map":57,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64}],37:[function(require,module,exports){ -'use strict'; +/** + * Param case a string. + * + * @param {String} string + * @param {String} [locale] + * @return {String} + */ +module.exports = function (string, locale) { + return sentenceCase(string, locale, '-') +} -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') +},{"sentence-case":466}],71:[function(require,module,exports){ +(function (process,global){ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +;(function (undefined) { - , d; + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; -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'); - } + var root = (objectTypes[typeof window] && window) || this, + freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, + freeModule = objectTypes[typeof module] && module && !module.nodeType && module, + moduleExports = freeModule && freeModule.exports === freeExports && freeExports, + freeGlobal = objectTypes[typeof global] && global; - desc = { value: value, configurable: c, enumerable: e, writable: w }; - return !options ? desc : assign(normalizeOpts(options), desc); -}; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } -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'); - } + var Rx = { + internals: {}, + config: { + Promise: root.Promise + }, + helpers: { } + }; + + // Defaults + var noop = Rx.helpers.noop = function () { }, + notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, + identity = Rx.helpers.identity = function (x) { return x; }, + pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, + just = Rx.helpers.just = function (value) { return function () { return value; }; }, + defaultNow = Rx.helpers.defaultNow = Date.now, + defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, + defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > 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 () { - desc = { get: get, set: set, configurable: c, enumerable: e }; - return !options ? desc : assign(normalizeOpts(options), desc); -}; + var isFn = function (value) { + return typeof value == 'function' || false; + } -},{"es5-ext/object/assign":46,"es5-ext/object/is-callable":52,"es5-ext/object/normalize-options":58,"es5-ext/string/#/contains":65}],38:[function(require,module,exports){ -// Inspired by Google Closure: -// http://closure-library.googlecode.com/svn/docs/ -// closure_goog_array_array.js.html#goog.array.clear + // fallback for older versions of Chrome and Safari + if (isFn(/x/)) { + isFn = function(value) { + return typeof value == 'function' && toString.call(value) == '[object Function]'; + }; + } -'use strict'; + return isFn; + }()); -var value = require('../../object/valid-value'); + 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; + } -module.exports = function () { - value(this).length = 0; - return this; -}; + // 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:"; -},{"../../object/valid-value":64}],39:[function(require,module,exports){ -'use strict'; + 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 toPosInt = require('../../number/to-pos-integer') - , value = require('../../object/valid-value') + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + error.stack = filterStackString(concatedStacks); + } + } - , indexOf = Array.prototype.indexOf - , hasOwnProperty = Object.prototype.hasOwnProperty - , abs = Math.abs, floor = Math.floor; + function filterStackString(stackString) { + var lines = stackString.split("\n"), + desiredLines = []; + for (var i = 0, len = lines.length; i < len; i++) { + var line = lines[i]; -module.exports = function (searchElement/*, fromIndex*/) { - var i, l, fromIndex, val; - if (searchElement === searchElement) { //jslint: ignore - return indexOf.apply(this, arguments); - } + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); + } - 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)); + function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + if (!fileNameAndLineNumber) { + return false; + } + var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; - for (i = fromIndex; i < l; ++i) { - if (hasOwnProperty.call(this, i)) { - val = this[i]; - if (val !== val) return i; //jslint: ignore - } - } - return -1; -}; + return fileName === rFileName && + lineNumber >= rStartingLine && + lineNumber <= rEndingLine; + } -},{"../../number/to-pos-integer":44,"../../object/valid-value":64}],40:[function(require,module,exports){ -'use strict'; + function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; + } -module.exports = require('./is-implemented')() - ? Math.sign - : require('./shim'); + function captureLine() { + if (!hasStacks) { return; } -},{"./is-implemented":41,"./shim":42}],41:[function(require,module,exports){ -'use strict'; + 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; } -module.exports = function () { - var sign = Math.sign; - if (typeof sign !== 'function') return false; - return ((sign(10) === 1) && (sign(-20) === -1)); -}; + rFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; + } + } -},{}],42:[function(require,module,exports){ -'use strict'; + 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])]; } -module.exports = function (value) { - value = Number(value); - if (isNaN(value) || (value === 0)) return value; - return (value > 0) ? 1 : -1; -}; + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } -},{}],43:[function(require,module,exports){ -'use strict'; + // 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 sign = require('../math/sign') + var ObjectDisposedError = Rx.ObjectDisposedError = function() { + this.message = 'Object has been disposed'; + Error.call(this); + }; + ObjectDisposedError.prototype = Error.prototype; - , abs = Math.abs, floor = Math.floor; + var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { + this.message = 'Argument out of range'; + Error.call(this); + }; + ArgumentOutOfRangeError.prototype = Error.prototype; -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)); -}; + var NotSupportedError = Rx.NotSupportedError = function (message) { + this.message = message || 'This operation is not supported'; + Error.call(this); + }; + NotSupportedError.prototype = Error.prototype; -},{"../math/sign":40}],44:[function(require,module,exports){ -'use strict'; + var NotImplementedError = Rx.NotImplementedError = function (message) { + this.message = message || 'This operation is not implemented'; + Error.call(this); + }; + NotImplementedError.prototype = Error.prototype; -var toInteger = require('./to-integer') + var notImplemented = Rx.helpers.notImplemented = function () { + throw new NotImplementedError(); + }; - , max = Math.max; + 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'; + } -module.exports = function (value) { return max(0, toInteger(value)); }; + var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; -},{"./to-integer":43}],45:[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 + var isIterable = Rx.helpers.isIterable = function (o) { + return o[$iterator$] !== undefined; + } -'use strict'; + var isArrayLike = Rx.helpers.isArrayLike = function (o) { + return o && o.length !== undefined; + } -var callable = require('./valid-callable') - , value = require('./valid-value') + 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); + }; + } - , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys - , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + 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]'; -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); - }); - }; -}; + var toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + supportsArgsClass = toString.call(arguments) == argsClass, // For less -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); -var forEach = Array.prototype.forEach, create = Object.create; + return result; + } + + var hasProp = {}.hasOwnProperty, + slice = Array.prototype.slice; -var process = function (src, obj) { - var key; - for (key in src) obj[key] = src[key]; -}; + var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { + function __() { this.constructor = child; } + __.prototype = parent.prototype; + child.prototype = new __(); + }; -module.exports = function (options/*, …options*/) { - var result = create(null); - forEach.call(arguments, function (options) { - if (options == null) return; - process(Object(options), result); - }); - return result; -}; + 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]; + } + } + }; -},{}],59:[function(require,module,exports){ -'use strict'; + // Rx Utils + var addRef = Rx.internals.addRef = function (xs, r) { + return new AnonymousObservable(function (observer) { + return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); + }); + }; -var forEach = Array.prototype.forEach, create = Object.create; + 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; + } -module.exports = function (arg/*, …args*/) { - var set = create(null); - forEach.call(arguments, function (name) { set[name] = true; }); - return set; -}; + IndexedItem.prototype.compareTo = function (other) { + var c = this.value.compareTo(other.value); + c === 0 && (c = this.id - other.id); + return c; + }; -},{}],60:[function(require,module,exports){ -'use strict'; + // Priority Queue for Scheduling + var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { + this.items = new Array(capacity); + this.length = 0; + }; -module.exports = require('./is-implemented')() - ? Object.setPrototypeOf - : require('./shim'); + var priorityProto = PriorityQueue.prototype; + priorityProto.isHigherPriority = function (left, right) { + return this.items[left].compareTo(this.items[right]) < 0; + }; -},{"./is-implemented":61,"./shim":62}],61:[function(require,module,exports){ -'use strict'; + 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); + } + }; -var create = Object.create, getPrototypeOf = Object.getPrototypeOf - , x = {}; + 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); + } + }; -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; -}; + priorityProto.peek = function () { return this.items[0].value; }; -},{}],62:[function(require,module,exports){ -// Big thanks to @WebReflection for sorting this out -// https://gist.github.com/WebReflection/5593554 + priorityProto.removeAt = function (index) { + this.items[index] = this.items[--this.length]; + this.items[this.length] = undefined; + this.heapify(); + }; -'use strict'; + priorityProto.dequeue = function () { + var result = this.peek(); + this.removeAt(0); + return result; + }; -var isObject = require('../is-object') - , value = require('../valid-value') + priorityProto.enqueue = function (item) { + var index = this.length++; + this.items[index] = new IndexedItem(PriorityQueue.count++, item); + this.percolate(index); + }; - , 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__'); + 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; + }; - 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 }; - } + var CompositeDisposablePrototype = CompositeDisposable.prototype; - x.__proto__ = y; - if (Object.getPrototypeOf(x) === y) return { level: 2 }; + /** + * 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++; + } + }; - x = {}; - x.__proto__ = y; - if (Object.getPrototypeOf(x) === y) return { level: 1 }; + /** + * 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; + }; - return false; -}()))); + /** + * 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; -require('../create'); + 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; + }; -},{"../create":50,"../is-object":53,"../valid-value":64}],63:[function(require,module,exports){ -'use strict'; + /** Performs the task of cleaning up resources. */ + Disposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.action(); + this.isDisposed = true; + } + }; -module.exports = function (fn) { - if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); - return fn; -}; + /** + * 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); }; -},{}],64:[function(require,module,exports){ -'use strict'; + /** + * Gets the disposable that does nothing when disposed. + */ + var disposableEmpty = Disposable.empty = { dispose: noop }; -module.exports = function (value) { - if (value == null) throw new TypeError("Cannot use null or undefined"); - return value; -}; + /** + * 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); + }; -},{}],65:[function(require,module,exports){ -'use strict'; + 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(); + }; -module.exports = require('./is-implemented')() - ? String.prototype.contains - : require('./shim'); + // 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 () { -},{"./is-implemented":66,"./shim":67}],66:[function(require,module,exports){ -'use strict'; + function InnerDisposable(disposable) { + this.disposable = disposable; + this.disposable.count++; + this.isInnerDisposed = false; + } -var str = 'razdwatrzy'; + 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(); + } + } + }; -module.exports = function () { - if (typeof str.contains !== 'function') return false; - return ((str.contains('dwa') === true) && (str.contains('foo') === false)); -}; + /** + * 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; + } -},{}],67:[function(require,module,exports){ -'use strict'; + /** + * 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(); + } + } + }; -var indexOf = String.prototype.indexOf; + /** + * 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); + }; -module.exports = function (searchString/*, position*/) { - return indexOf.call(this, searchString, arguments[1]) > -1; -}; + return RefCountDisposable; + })(); + + function ScheduledDisposable(scheduler, disposable) { + this.scheduler = scheduler; + this.disposable = disposable; + this.isDisposed = false; + } -},{}],68:[function(require,module,exports){ -'use strict'; + function scheduleItem(s, self) { + if (!self.isDisposed) { + self.isDisposed = true; + self.disposable.dispose(); + } + } -var toString = Object.prototype.toString + 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(); + } - , id = toString.call(''); + ScheduledItem.prototype.invoke = function () { + this.disposable.setDisposable(this.invokeCore()); + }; -module.exports = function (x) { - return (typeof x === 'string') || (x && (typeof x === 'object') && - ((x instanceof String) || (toString.call(x) === id))) || false; -}; + ScheduledItem.prototype.compareTo = function (other) { + return this.comparer(this.dueTime, other.dueTime); + }; -},{}],69:[function(require,module,exports){ -'use strict'; + ScheduledItem.prototype.isCancelled = function () { + return this.disposable.isDisposed; + }; -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , contains = require('es5-ext/string/#/contains') - , d = require('d') - , Iterator = require('./') + 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 () { - , defineProperty = Object.defineProperty - , ArrayIterator; + function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { + this.now = now; + this._schedule = schedule; + this._scheduleRelative = scheduleRelative; + this._scheduleAbsolute = scheduleAbsolute; + } -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); + /** Determines whether the given object is a scheduler */ + Scheduler.isScheduler = function (s) { + return s instanceof Scheduler; + } -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]'; }) -}); + function invokeAction(scheduler, action) { + action(); + return disposableEmpty; + } -},{"./":72,"d":37,"es5-ext/object/set-prototype-of":60,"es5-ext/string/#/contains":65}],70:[function(require,module,exports){ -'use strict'; + var schedulerProto = Scheduler.prototype; -var callable = require('es5-ext/object/valid-callable') - , isString = require('es5-ext/string/is-string') - , get = require('./get') + /** + * 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); + }; - , isArray = Array.isArray, call = Function.prototype.call; + /** + * 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); + }; -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); + /** + * 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); + }; - 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(); + /** + * 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); + }; - while (!result.done) { - call.call(cb, thisArg, result.value, doBreak); - if (broken) return; - result = iterable.next(); - } -}; + /** + * 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); + }; -},{"./get":71,"es5-ext/object/valid-callable":63,"es5-ext/string/is-string":68}],71:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -var isString = require('es5-ext/string/is-string') - , ArrayIterator = require('./array') - , StringIterator = require('./string') - , iterable = require('./valid-iterable') - , iteratorSymbol = require('es6-symbol').iterator; + /** Gets the current time according to the local machine's system clock. */ + Scheduler.now = defaultNow; -module.exports = function (obj) { - if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); - if (isString(obj)) return new StringIterator(obj); - return new ArrayIterator(obj); -}; + /** + * 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; + }; -},{"./array":69,"./string":79,"./valid-iterable":80,"es5-ext/string/is-string":68,"es6-symbol":74}],72:[function(require,module,exports){ -'use strict'; + return Scheduler; + }()); -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":37,"d/auto-bind":36,"es5-ext/array/#/clear":38,"es5-ext/object/assign":46,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64,"es6-symbol":74}],73:[function(require,module,exports){ -'use strict'; - -var isString = require('es5-ext/string/is-string') - , iteratorSymbol = require('es6-symbol').iterator + var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; + + (function (schedulerProto) { - , isArray = Array.isArray; + function invokeRecImmediate(scheduler, pair) { + var state = pair[0], action = pair[1], group = new CompositeDisposable(); -module.exports = function (value) { - if (value == null) return false; - if (isArray(value)) return true; - if (isString(value)) return true; - return (typeof value[iteratorSymbol] === 'function'); -}; + 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; + } -},{"es5-ext/string/is-string":68,"es6-symbol":74}],74:[function(require,module,exports){ -'use strict'; + 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; + } -module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); + function scheduleInnerRecursive(action, self) { + action(function(dt) { self(action, dt); }); + } -},{"./is-implemented":75,"./polyfill":77}],75:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -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; + /** + * 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); + }; - // 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; + /** + * 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); + }; - return true; -}; + /** + * 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'); + }); + }; -},{}],76:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -module.exports = function (x) { - return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; -}; + /** + * 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) { -},{}],77:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -var d = require('d') - , validateSymbol = require('./validate-symbol') + /** + * 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); }); + }; - , create = Object.create, defineProperties = Object.defineProperties - , defineProperty = Object.defineProperty, objPrototype = Object.prototype - , Symbol, HiddenSymbol, globalSymbols = create(null); + }(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; + } + } -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; - }; -}()); + function SchedulePeriodicRecursive(scheduler, state, period, action) { + this._scheduler = scheduler; + this._state = state; + this._period = period; + this._action = action; + } -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__; }) -}); + SchedulePeriodicRecursive.prototype.start = function () { + var d = new SingleAssignmentDisposable(); + this._cancel = d; + d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); -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')); + return d; + }; -defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, - d('c', Symbol.prototype[Symbol.toPrimitive])); -defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, - d('c', Symbol.prototype[Symbol.toStringTag])); + 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; -},{"./validate-symbol":78,"d":37}],78:[function(require,module,exports){ -'use strict'; + function runTrampoline () { + while (queue.length > 0) { + var item = queue.dequeue(); + !item.isCancelled() && item.invoke(); + } + } -var isSymbol = require('./is-symbol'); + function scheduleNow(state, action) { + var si = new ScheduledItem(this, state, action, this.now()); -module.exports = function (value) { - if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); - return value; -}; + if (!queue) { + queue = new PriorityQueue(4); + queue.enqueue(si); -},{"./is-symbol":76}],79:[function(require,module,exports){ -// Thanks @mathiasbynens -// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + var result = tryCatch(runTrampoline)(); + queue = null; + if (result === errorObj) { return thrower(result.e); } + } else { + queue.enqueue(si); + } + return si.disposable; + } -'use strict'; + var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); + currentScheduler.scheduleRequired = function () { return !queue; }; -var setPrototypeOf = require('es5-ext/object/set-prototype-of') - , d = require('d') - , Iterator = require('./') + return currentScheduler; + }()); + + var scheduleMethod, clearMethod; - , defineProperty = Object.defineProperty - , StringIterator; + 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(); + } -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)); + return { + setTimeout: localSetTimeout, + clearTimeout: localClearTimeout + }; + }()); + var localSetTimeout = localTimer.setTimeout, + localClearTimeout = localTimer.clearTimeout; -}; -if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); + (function () { -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]'; }) -}); + var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; -},{"./":72,"d":37,"es5-ext/object/set-prototype-of":60}],80:[function(require,module,exports){ -'use strict'; + clearMethod = function (handle) { + delete tasksByHandle[handle]; + }; -var isIterable = require('./is-iterable'); + 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); } + } + } + } -module.exports = function (value) { - if (!isIterable(value)) throw new TypeError(value + " is not iterable"); - return value; -}; + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); -},{"./is-iterable":73}],81:[function(require,module,exports){ -'use strict'; + var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && + !reNative.test(setImmediate) && setImmediate; -module.exports = require('./is-implemented')() ? Map : require('./polyfill'); + 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; -},{"./is-implemented":82,"./polyfill":86}],82:[function(require,module,exports){ -'use strict'; + return isAsync; + } -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; -}; + // 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); }); -},{}],83:[function(require,module,exports){ -// Exports true if environment provides native `Map` implementation, -// whatever that is. + 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); }); -'use strict'; + return id; + }; + } else if (postMessageSupported()) { + var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); -module.exports = (function () { - if (typeof Map === 'undefined') return false; - return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); -}()); + 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)); + } + } -},{}],84:[function(require,module,exports){ -'use strict'; + if (root.addEventListener) { + root.addEventListener('message', onGlobalPostMessage, false); + } else if (root.attachEvent) { + root.attachEvent('onmessage', onGlobalPostMessage); + } else { + root.onmessage = onGlobalPostMessage; + } -module.exports = require('es5-ext/object/primitive-set')('key', - 'value', 'key+value'); + 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(); -},{"es5-ext/object/primitive-set":59}],85:[function(require,module,exports){ -'use strict'; + channel.port1.onmessage = function (e) { runTask(e.data); }; -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') + 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')) { - , defineProperties = Object.defineProperties - , unBind = Iterator.prototype._unBind - , MapIterator; + scheduleMethod = function (action) { + var scriptElement = root.document.createElement('script'); + var id = nextHandle++; + tasksByHandle[id] = action; -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); + scriptElement.onreadystatechange = function () { + runTask(id); + scriptElement.onreadystatechange = null; + scriptElement.parentNode.removeChild(scriptElement); + scriptElement = null; + }; + root.document.documentElement.appendChild(scriptElement); + return id; + }; -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')); + } else { + scheduleMethod = function (action) { + var id = nextHandle++; + tasksByHandle[id] = action; + localSetTimeout(function () { + runTask(id); + }, 0); -},{"./iterator-kinds":84,"d":37,"es5-ext/object/set-prototype-of":60,"es6-iterator":72,"es6-symbol":87}],86:[function(require,module,exports){ -'use strict'; + return id; + }; + } + }()); -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') + /** + * Gets a scheduler that schedules work via a timed callback based upon platform. + */ + var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { - , call = Function.prototype.call, defineProperties = Object.defineProperties - , MapPoly; + 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); + })); + } -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); -}; + 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); + })); + } -if (isNative) { - if (setPrototypeOf) setPrototypeOf(MapPoly, Map); - MapPoly.prototype = Object.create(Map.prototype, { - constructor: d(MapPoly) - }); -} + function scheduleAbsolute(state, dueTime, action) { + return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); + } -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')); + return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); + })(); + + var CatchScheduler = (function (__super__) { -},{"./is-native-implemented":83,"./lib/iterator":85,"d":37,"es5-ext/array/#/clear":38,"es5-ext/array/#/e-index-of":39,"es5-ext/object/set-prototype-of":60,"es5-ext/object/valid-callable":63,"es5-ext/object/valid-value":64,"es6-iterator/for-of":70,"es6-iterator/valid-iterable":80,"es6-symbol":87,"event-emitter":92}],87:[function(require,module,exports){ -arguments[4][74][0].apply(exports,arguments) -},{"./is-implemented":88,"./polyfill":89,"dup":74}],88:[function(require,module,exports){ -'use strict'; + function scheduleNow(state, action) { + return this._scheduler.scheduleWithState(state, this._wrap(action)); + } -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; + function scheduleRelative(state, dueTime, action) { + return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); + } - // 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; + function scheduleAbsolute(state, dueTime, action) { + return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); + } - return true; -}; + inherits(CatchScheduler, __super__); -},{}],89:[function(require,module,exports){ -'use strict'; + 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); + } -var d = require('d') + CatchScheduler.prototype._clone = function (scheduler) { + return new CatchScheduler(scheduler, this._handler); + }; - , create = Object.create, defineProperties = Object.defineProperties - , generateName, Symbol; + 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; + } + }; + }; -generateName = (function () { - var created = create(null); - return function (desc) { - var postfix = 0; - while (created[desc + (postfix || '')]) ++postfix; - desc += (postfix || ''); - created[desc] = true; - return '@@' + desc; - }; -}()); + 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; + }; -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)) - }); -}; + CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { + var self = this, failed = false, d = new SingleAssignmentDisposable(); -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')) -}); + 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; + } + })); -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')); + return d; + }; -},{"d":37}],90:[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 - */ + 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; + } -'use strict'; + /** + * 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); + }; -/** - * Module variables. - * @private - */ + /** + * 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(); + }); + }); + }; -var matchHtmlRegExp = /["'&<>]/; + return Notification; + })(); -/** - * Module exports. - * @public - */ + /** + * 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 + ')'; } -module.exports = escapeHtml; + return function (value) { + return new Notification('N', value, null, _accept, _acceptObservable, toString); + }; + }()); -/** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public - */ + /** + * 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 + ')'; } -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); + return function (e) { + return new Notification('E', null, e, _accept, _acceptObservable, toString); + }; + }()); - if (!match) { - return str; - } + /** + * 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()'; } - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + return function () { + return new Notification('C', null, null, _accept, _acceptObservable, toString); + }; + }()); + + /** + * Supports push-style iteration over an observable sequence. + */ + var Observer = Rx.Observer = function () { }; - 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); - } + /** + * 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); }; + }; - lastIndex = index + 1; - html += escape; - } + /** + * 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)); + }; - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; -} + /** + * 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); }; -},{}],91:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -var OneVersionConstraint = require('individual/one-version'); + /** + * 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()); + }); + }; -var MY_VERSION = '7'; -OneVersionConstraint('ev-store', MY_VERSION); + /** + * 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); + }; -var hashKey = '__EV_STORE_KEY@' + MY_VERSION; + 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__); -module.exports = EvStore; + /** + * Creates a new observer in a non-stopped state. + */ + function AbstractObserver() { + this.isStopped = false; + __super__.call(this); + } -function EvStore(elem) { - var hash = elem[hashKey]; + // Must be implemented by other observers + AbstractObserver.prototype.next = notImplemented; + AbstractObserver.prototype.error = notImplemented; + AbstractObserver.prototype.completed = notImplemented; - if (!hash) { - hash = elem[hashKey] = {}; - } + /** + * 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); } + }; - return hash; -} + /** + * 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); + } + }; -},{"individual/one-version":96}],92:[function(require,module,exports){ -'use strict'; + /** + * Notifies the observer of the end of the sequence. + */ + AbstractObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.completed(); + } + }; -var d = require('d') - , callable = require('es5-ext/object/valid-callable') + /** + * Disposes the observer, causing it to transition to the stopped state. + */ + AbstractObserver.prototype.dispose = function () { + this.isStopped = true; + }; - , 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 } + AbstractObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.error(e); + return true; + } - , on, once, off, emit, methods, descriptors, base; + return false; + }; -on = function (type, listener) { - var data; + 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__); - callable(listener); + /** + * 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; + } - 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]; + /** + * Calls the onNext action. + * @param {Any} value Next element in the sequence. + */ + AnonymousObserver.prototype.next = function (value) { + this._onNext(value); + }; - return this; -}; + /** + * Calls the onError action. + * @param {Any} error The error that has occurred. + */ + AnonymousObserver.prototype.error = function (error) { + this._onError(error); + }; -once = function (type, listener) { - var once, self; + /** + * Calls the onCompleted action. + */ + AnonymousObserver.prototype.completed = function () { + this._onCompleted(); + }; - callable(listener); - self = this; - on.call(this, type, once = function () { - off.call(self, type, once); - apply.call(listener, this, arguments); - }); + return AnonymousObserver; + }(AbstractObserver)); + + var CheckedObserver = (function (__super__) { + inherits(CheckedObserver, __super__); - once.__eeOnceListener__ = listener; - return this; -}; + function CheckedObserver(observer) { + __super__.call(this); + this._observer = observer; + this._state = 0; // 0 - idle, 1 - busy, 2 - done + } -off = function (type, listener) { - var data, listeners, candidate, i; + var CheckedObserverPrototype = CheckedObserver.prototype; - callable(listener); + CheckedObserverPrototype.onNext = function (value) { + this.checkAccess(); + var res = tryCatch(this._observer.onNext).call(this._observer, value); + this._state = 0; + res === errorObj && thrower(res.e); + }; - if (!hasOwnProperty.call(this, '__ee__')) return this; - data = this.__ee__; - if (!data[type]) return this; - listeners = data[type]; + CheckedObserverPrototype.onError = function (err) { + this.checkAccess(); + var res = tryCatch(this._observer.onError).call(this._observer, err); + this._state = 2; + res === errorObj && thrower(res.e); + }; - 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; + CheckedObserverPrototype.onCompleted = function () { + this.checkAccess(); + var res = tryCatch(this._observer.onCompleted).call(this._observer); + this._state = 2; + res === errorObj && thrower(res.e); + }; - if (!hasOwnProperty.call(this, '__ee__')) return; - listeners = this.__ee__[type]; - if (!listeners) return; + 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; } + }; - if (typeof listeners === 'object') { - l = arguments.length; - args = new Array(l - 1); - for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + return CheckedObserver; + }(Observer)); + + var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { + inherits(ScheduledObserver, __super__); - 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); - } - } -}; + 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(); + } -methods = { - on: on, - once: once, - off: off, - emit: emit -}; + ScheduledObserver.prototype.next = function (value) { + var self = this; + this.queue.push(function () { self.observer.onNext(value); }); + }; -descriptors = { - on: d(on), - once: d(once), - off: d(off), - emit: d(emit) -}; + ScheduledObserver.prototype.error = function (e) { + var self = this; + this.queue.push(function () { self.observer.onError(e); }); + }; -base = defineProperties({}, descriptors); + ScheduledObserver.prototype.completed = function () { + var self = this; + this.queue.push(function () { self.observer.onCompleted(); }); + }; -module.exports = exports = function (o) { - return (o == null) ? create(base) : defineProperties(Object(o), descriptors); -}; -exports.methods = methods; + 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(); + })); + } + }; -},{"d":37,"es5-ext/object/valid-callable":63}],93:[function(require,module,exports){ -(function (global){ -var topLevel = typeof global !== 'undefined' ? global : - typeof window !== 'undefined' ? window : {} -var minDoc = require('min-document'); + ScheduledObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this.disposable.dispose(); + }; -if (typeof document !== 'undefined') { - module.exports = document; -} else { - var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; + return ScheduledObserver; + }(AbstractObserver)); + + var ObserveOnObserver = (function (__super__) { + inherits(ObserveOnObserver, __super__); - if (!doccy) { - doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; + function ObserveOnObserver(scheduler, observer, cancel) { + __super__.call(this, scheduler, observer); + this._cancel = cancel; } - module.exports = doccy; -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"min-document":1}],94:[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. - */ + ObserveOnObserver.prototype.next = function (value) { + __super__.prototype.next.call(this, value); + this.ensureActive(); + }; -(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; + ObserveOnObserver.prototype.error = function (e) { + __super__.prototype.error.call(this, e); + this.ensureActive(); + }; - function createClass(ctor, superClass) { - if (superClass) { - ctor.prototype = Object.create(superClass.prototype); - } - ctor.prototype.constructor = ctor; - } + ObserveOnObserver.prototype.completed = function () { + __super__.prototype.completed.call(this); + this.ensureActive(); + }; - function Iterable(value) { - return isIterable(value) ? value : Seq(value); - } + ObserveOnObserver.prototype.dispose = function () { + __super__.prototype.dispose.call(this); + this._cancel && this._cancel.dispose(); + this._cancel = null; + }; + return ObserveOnObserver; + })(ScheduledObserver); + + var observableProto; - createClass(KeyedIterable, Iterable); - function KeyedIterable(value) { - return isKeyed(value) ? value : KeyedSeq(value); - } + /** + * 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); + } - createClass(IndexedIterable, Iterable); - function IndexedIterable(value) { - return isIndexed(value) ? value : IndexedSeq(value); - } + var self = this; + this._subscribe = function (observer) { + var oldOnError = observer.onError.bind(observer); + observer.onError = function (err) { + makeStackTraceLong(err, self); + oldOnError(err); + }; - createClass(SetIterable, Iterable); - function SetIterable(value) { - return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); + 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)); + }; - 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 }; + /** + * 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)); + }; - function MakeRef(ref) { - ref.value = false; - return ref; - } + /** + * 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)); + }; - function SetRef(ref) { - ref && (ref.value = true); - } + /** + * 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)); + }; - // 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() {} + return Observable; + })(); + + var ObservableBase = Rx.ObservableBase = (function (__super__) { + inherits(ObservableBase, __super__); - // 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]; + function fixSubscriber(subscriber) { + return subscriber && isFunction(subscriber.dispose) ? subscriber : + isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } - return newArr; - } - function ensureSize(iter) { - if (iter.size === undefined) { - iter.size = iter.__iterate(returnTrue); - } - return iter.size; - } + function setDisposable(s, state) { + var ado = state[0], self = state[1]; + var sub = tryCatch(self.subscribeCore).call(self, ado); - 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; + if (sub === errorObj) { + if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } - index = uint32Index; + ado.setDisposable(fixSubscriber(sub)); } - 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 subscribe(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, this]; - function resolveBegin(begin, size) { - return resolveIndex(begin, size, 0); - } + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; + } - function resolveEnd(end, size) { - return resolveIndex(end, size, size); - } + function ObservableBase() { + __super__.call(this, subscribe); + } - function resolveIndex(index, size, defaultIndex) { - return index === undefined ? - defaultIndex : - index < 0 ? - Math.max(0, size + index) : - size === undefined ? - index : - Math.min(size, index); - } + ObservableBase.prototype.subscribeCore = notImplemented; - /* global Symbol */ + return ObservableBase; + }(Observable)); + + var Enumerable = Rx.internals.Enumerable = function () { }; - var ITERATE_KEYS = 0; - var ITERATE_VALUES = 1; - var ITERATE_ENTRIES = 2; + 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); } - var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = '@@iterator'; + if (currentItem.done) { + return o.onCompleted(); + } - var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; + // 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))); + }); - function Iterator(next) { - this.next = next; + 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; } - - Iterator.prototype.toString = function() { - return '[Iterator]'; + 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)); - - 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; + 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); } - 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); - } + if (currentItem.done) { + return lastException !== null ? o.onError(lastException) : o.onCompleted(); + } - Seq.of = function(/*...values*/) { - return Seq(arguments); - }; + // Check if promise + var currentValue = currentItem.value; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); - Seq.prototype.toSeq = function() { - return this; + 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)); - Seq.prototype.toString = function() { - return this.__toString('Seq {', '}'); - }; + Enumerable.prototype.catchError = function () { + return new CatchErrorObservable(this); + }; - Seq.prototype.cacheResult = function() { - if (!this._cache && this.__iterateUncached) { - this._cache = this.entrySeq().toArray(); - this.size = this._cache.length; - } - return 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); - // abstract __iterateUncached(fn, reverse) + var e = sources[$iterator$](); - Seq.prototype.__iterate = function(fn, reverse) { - return seqIterate(this, fn, reverse, true); - }; + 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); } - // abstract __iteratorUncached(type, reverse) + if (currentItem.done) { + if (lastException) { + o.onError(lastException); + } else { + o.onCompleted(); + } + return; + } - Seq.prototype.__iterator = function(type, reverse) { - return seqIterator(this, type, reverse, true); - }; + // 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(); })); + }); - createClass(KeyedSeq, Seq); - function KeyedSeq(value) { - return value === null || value === undefined ? - emptySequence().toKeyedSeq() : - isIterable(value) ? - (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : - keyedSeqFromValue(value); + 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; } - - KeyedSeq.prototype.toKeyedSeq = function() { - return this; + RepeatEnumerable.prototype[$iterator$] = function () { + return new RepeatEnumerator(this); }; - - - - createClass(IndexedSeq, Seq); - function IndexedSeq(value) { - return value === null || value === undefined ? emptySequence() : - !isIterable(value) ? indexedSeqFromValue(value) : - isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); + + function RepeatEnumerator(p) { + this.v = p.v; + this.l = p.c; } - - 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); + 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)); - - - createClass(SetSeq, Seq); - function SetSeq(value) { - return ( - value === null || value === undefined ? emptySequence() : - !isIterable(value) ? indexedSeqFromValue(value) : - isKeyed(value) ? value.entrySeq() : value - ).toSetSeq(); + 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; } - - SetSeq.of = function(/*...values*/) { - return SetSeq(arguments); - }; - - SetSeq.prototype.toSetSeq = function() { - return this; + OfEnumerable.prototype[$iterator$] = function () { + return new OfEnumerator(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; + + function OfEnumerator(p) { + this.i = -1; + this.s = p.s; + this.l = this.s.length; + this.fn = p.fn; } - - 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++])} - ); + 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. - createClass(ObjectSeq, KeyedSeq); - function ObjectSeq(object) { - var keys = Object.keys(object); - this._object = object; - this._keys = keys; - this.size = keys.length; + * @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); } - ObjectSeq.prototype.get = function(key, notSetValue) { - if (notSetValue !== undefined && !this.has(key)) { - return notSetValue; - } - return this._object[key]; + ToArrayObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o)); }; - ObjectSeq.prototype.has = function(key) { - return this._object.hasOwnProperty(key); + 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); + } }; - - 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; - } + InnerObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.o.onNext(this.a); + this.o.onCompleted(); } - 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]); - }); + 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; }; - ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; - + return ToArrayObservable; + }(ObservableBase)); - createClass(IterableSeq, IndexedSeq); - function IterableSeq(iterable) { - this._iterable = iterable; - this.size = iterable.length || iterable.size; + /** + * 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); } - 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; + EmptyObservable.prototype.subscribeCore = function (observer) { + var sink = new EmptySink(observer, this); + return sink.run(); }; - 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); - }); + 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)); - createClass(IteratorSeq, IndexedSeq); - function IteratorSeq(iterator) { - this._iterator = iterator; - this._iteratorCache = []; + var FromSink = (function () { + function FromSink(observer, parent) { + this.observer = observer; + this.parent = parent; } - 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; + 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); } - } - var step; - while (!(step = iterator.next()).done) { - var val = step.value; - cache[iterations] = val; - if (fn(val, iterations++, this) === false) { - break; + if (next.done) { + return observer.onCompleted(); } - } - 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; + var result = next.value; + + if (mapper) { + try { + result = mapper(result, i); + } catch (e) { + return observer.onError(e); } - cache[iterations] = step.value; } - return iteratorValue(type, iterations, cache[iterations++]); - }); - }; + observer.onNext(result); + recurse(i + 1); + } + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; + return FromSink; + }()); - // # pragma Helper functions + var maxSafeInteger = Math.pow(2, 53) - 1; - function isSeq(maybeSeq) { - return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); + function StringIterable(str) { + this._s = s; } - var EMPTY_SEQ; + StringIterable.prototype[$iterator$] = function () { + return new StringIterator(this._s); + }; - function emptySequence() { - return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); + function StringIterator(str) { + this._s = s; + this._l = s.length; + this._i = 0; } - 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; - } + StringIterator.prototype[$iterator$] = function () { + return this; + }; - function indexedSeqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (!seq) { - throw new TypeError( - 'Expected Array or iterable object of values: ' + value - ); - } - return seq; - } + StringIterator.prototype.next = function () { + return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; + }; - 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 ArrayIterable(a) { + this._a = a; } - function maybeIndexedSeqFromValue(value) { - return ( - isArrayLike(value) ? new ArraySeq(value) : - isIterator(value) ? new IteratorSeq(value) : - hasIterator(value) ? new IterableSeq(value) : - undefined - ); - } + ArrayIterable.prototype[$iterator$] = function () { + return new ArrayIterator(this._a); + }; - 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 ArrayIterator(a) { + this._a = a; + this._l = toLength(a); + this._i = 0; } - 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); + 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 fromJS(json, converter) { - return converter ? - fromJSWith(converter, json, '', {'': json}) : - fromJSDefault(json); + function isNan(n) { + return n !== n; } - 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)})); + function getIterable(o) { + var i = o[$iterator$], it; + if (!i && typeof o === 'string') { + it = new StringIterable(o); + return it[$iterator$](); } - if (isPlainObj(json)) { - return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); + if (!i && o.length !== undefined) { + it = new ArrayIterable(o); + return it[$iterator$](); } - return json; + if (!i) { throw new TypeError('Object is not iterable'); } + return o[$iterator$](); } - 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 sign(value) { + var number = +value; + if (number === 0) { return number; } + if (isNaN(number)) { return number; } + return number < 0 ? -1 : 1; } - function isPlainObj(value) { - return value && (value.constructor === Object || value.constructor === undefined); + 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; } /** - * 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; + * 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 (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 (mapFn && !isFunction(mapFn)) { + throw new Error('mapFn when provided must be a function'); } - if (typeof valueA.equals === 'function' && - typeof valueB.equals === 'function' && - valueA.equals(valueB)) { - return true; + if (mapFn) { + var mapper = bindCallback(mapFn, thisArg, 2); } - return false; + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromObservable(iterable, mapper, scheduler); } - - 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 FromArrayObservable = (function(__super__) { + inherits(FromArrayObservable, __super__); + function FromArrayObservable(args, scheduler) { + this.args = args; + this.scheduler = scheduler; + __super__.call(this); } - var notAssociative = !isAssociative(a); + FromArrayObservable.prototype.subscribeCore = function (observer) { + var sink = new FromArraySink(observer, this); + return sink.run(); + }; - 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; - } + return FromArrayObservable; + }(ObservableBase)); - var flipped = false; + function FromArraySink(observer, parent) { + this.observer = observer; + this.parent = parent; + } - if (a.size === undefined) { - if (b.size === undefined) { - if (typeof a.cacheResult === 'function') { - a.cacheResult(); - } + 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 { - flipped = true; - var _ = a; - a = b; - b = _; + observer.onCompleted(); } } - 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 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(); + } + }); }); - - return allEqual && a.size === bSize; + }; + + function observableOf (scheduler, array) { + isScheduler(scheduler) || (scheduler = currentThreadScheduler); + return new FromArrayObservable(array, scheduler); } - createClass(Repeat, IndexedSeq); + /** + * 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); + }; - 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; + /** + * 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]); } - EMPTY_REPEAT = this; } - } + + Array.observe(array, observerFn); - Repeat.prototype.toString = function() { - if (this.size === 0) { - return 'Repeat []'; + 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]); + } } - 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; - }; + Object.observe(obj, observerFn); - Repeat.prototype.indexOf = function(searchValue) { - if (is(this._value, searchValue)) { - return 0; - } - return -1; - }; + return function () { + Object.unobserve(obj, observerFn); + }; + }); + }; + + var NeverObservable = (function(__super__) { + inherits(NeverObservable, __super__); + function NeverObservable() { + __super__.call(this); + } - Repeat.prototype.lastIndexOf = function(searchValue) { - if (is(this._value, searchValue)) { - return this.size; - } - return -1; + NeverObservable.prototype.subscribeCore = function (observer) { + return disposableEmpty; }; - 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; - }; + return NeverObservable; + }(ObservableBase)); - 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()} - ); - }; + /** + * 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); + } - Repeat.prototype.equals = function(other) { - return other instanceof Repeat ? - is(this._value, other._value) : - deepEqual(other); + PairsObservable.prototype.subscribeCore = function (observer) { + var sink = new PairsSink(observer, this); + return sink.run(); }; + return PairsObservable; + }(ObservableBase)); - var EMPTY_REPEAT; - - function invariant(condition, error) { - if (!condition) throw new Error(error); + function PairsSink(observer, parent) { + this.observer = observer; + this.parent = parent; } - 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; + 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(); } } - Range.prototype.toString = function() { - if (this.size === 0) { - return 'Range []'; - } - return 'Range [ ' + - this._start + '...' + this._end + - (this._step !== 1 ? ' by ' + this._step : '') + - ' ]'; - }; + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); + }; - Range.prototype.get = function(index, notSetValue) { - return this.has(index) ? - this._start + wrapIndex(this, index) * this._step : - notSetValue; - }; + /** + * 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); + } - Range.prototype.includes = function(searchValue) { - var possibleIndex = (searchValue - this._start) / this._step; - return possibleIndex >= 0 && - possibleIndex < this.size && - possibleIndex === Math.floor(possibleIndex); + RangeObservable.prototype.subscribeCore = function (observer) { + var sink = new RangeSink(observer, this); + return sink.run(); }; - 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); - }; + return RangeObservable; + }(ObservableBase)); - 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 + 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 -1; + + return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; - 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; - }; + return RangeSink; + }()); - 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); - }); - }; + /** + * 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); + } - Range.prototype.equals = function(other) { - return other instanceof Range ? - this._start === other._start && - this._end === other._end && - this._step === other._step : - deepEqual(this, other); + RepeatObservable.prototype.subscribeCore = function (observer) { + var sink = new RepeatSink(observer, this); + return sink.run(); }; + return RepeatObservable; + }(ObservableBase)); - var EMPTY_RANGE; + function RepeatSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } - createClass(Collection, Iterable); - function Collection() { - throw TypeError('Abstract'); + 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); + }; - createClass(KeyedCollection, Collection);function KeyedCollection() {} - - createClass(IndexedCollection, Collection);function IndexedCollection() {} + /** + * 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); + } - createClass(SetCollection, Collection);function SetCollection() {} + JustObservable.prototype.subscribeCore = function (observer) { + var sink = new JustSink(observer, this); + return sink.run(); + }; + function JustSink(observer, parent) { + this.observer = observer; + this.parent = parent; + } - Collection.Keyed = KeyedCollection; - Collection.Indexed = IndexedCollection; - Collection.Set = SetCollection; + function scheduleItem(s, state) { + var value = state[0], observer = state[1]; + observer.onNext(value); + observer.onCompleted(); + } - 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 + JustSink.prototype.run = function () { + return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; - // 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); - } + return JustObservable; + }(ObservableBase)); - 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') { - if (o !== o || o === Infinity) { - return 0; - } - 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()); + /** + * 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) { - switch (node.nodeType) { - case 1: // Element - return node.uniqueID; - case 9: // Document - return node.documentElement && node.documentElement.uniqueID; + function choiceL() { + if (!choice) { + choice = leftChoice; + rightSubscription.dispose(); + } } - } - } - - // 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.' - ); - } + function choiceR() { + if (!choice) { + choice = rightChoice; + leftSubscription.dispose(); + } + } - createClass(Map, KeyedCollection); + 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(); + })); - // @pragma Construction + 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(); + })); - 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)}); - }); + return new CompositeDisposable(leftSubscription, rightSubscription); + }); + }; + + /** + * Propagates the observable sequence or Promise that reacts first. + * + * @example + * var = Rx.Observable.amb(xs, ys, zs); + * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + Observable.amb = function () { + var acc = observableNever(), items = []; + if (Array.isArray(arguments[0])) { + items = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } - Map.of = function() {var keyValues = SLICE$0.call(arguments, 0); - return emptyMap().withMutations(function(map ) { - for (var i = 0; i < keyValues.length; i += 2) { - if (i + 1 >= keyValues.length) { - throw new Error('Missing value for key: ' + keyValues[i]); - } - map.set(keyValues[i], keyValues[i + 1]); + function func(previous, current) { + return previous.amb(current); + } + for (var i = 0, len = items.length; i < len; i++) { + acc = func(acc, items[i]); + } + return acc; + }; + + function observableCatchHandler(source, handler) { + return new AnonymousObservable(function (o) { + var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); + subscription.setDisposable(d1); + d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { + try { + var result = handler(e); + } catch (ex) { + return o.onError(ex); } - }); - }; - - 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}); - }; + isPromise(result) && (result = observableFromPromise(result)); - Map.prototype.remove = function(k) { - return updateMap(this, k, NOT_SET); - }; + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(result.subscribe(o)); + }, function (x) { o.onCompleted(x); })); - Map.prototype.deleteIn = function(keyPath) { - return this.updateIn(keyPath, function() {return NOT_SET}); - }; + return subscription; + }, source); + } - Map.prototype.update = function(k, notSetValue, updater) { - return arguments.length === 1 ? - k(this) : - this.updateIn([k], notSetValue, updater); - }; + /** + * Continues an observable sequence that is terminated by an exception with the next observable sequence. + * @example + * 1 - xs.catchException(ys) + * 2 - xs.catchException(function (ex) { return ys(ex); }) + * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. + * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. + */ + observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { + return typeof handlerOrSecond === 'function' ? + observableCatchHandler(this, handlerOrSecond) : + observableCatch([this, handlerOrSecond]); + }; + + /** + * Continues an observable sequence that is terminated by an exception with the next observable sequence. + * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. + * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { + var items = []; + if (Array.isArray(arguments[0])) { + items = arguments[0]; + } else { + for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } + } + return enumerableOf(items).catchError(); + }; + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. + * This can be in the form of an argument list of observables or an array. + * + * @example + * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); + * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + observableProto.combineLatest = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + if (Array.isArray(args[0])) { + args[0].unshift(this); + } else { + args.unshift(this); + } + return combineLatest.apply(this, args); + }; + + /** + * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. + * + * @example + * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); + * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); + * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + var combineLatest = Observable.combineLatest = function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } + var resultSelector = args.pop(); + Array.isArray(args[0]) && (args = args[0]); - 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; - }; + return new AnonymousObservable(function (o) { + var n = args.length, + falseFactory = function () { return false; }, + hasValue = arrayInitialize(n, falseFactory), + hasValueAll = false, + isDone = arrayInitialize(n, falseFactory), + values = new Array(n); - 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; + function next(i) { + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + try { + var res = resultSelector.apply(null, values); + } catch (e) { + return o.onError(e); + } + o.onNext(res); + } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { + o.onCompleted(); + } } - return emptyMap(); - }; - // @pragma Composition + function done (i) { + isDone[i] = true; + isDone.every(identity) && o.onCompleted(); + } - Map.prototype.merge = function(/*...iters*/) { - return mergeIntoMapWith(this, undefined, arguments); - }; + 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) { + values[i] = x; + next(i); + }, + function(e) { o.onError(e); }, + function () { done(i); } + )); + subscriptions[i] = sad; + }(idx)); + } - Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); - return mergeIntoMapWith(this, merger, iters); - }; + return new CompositeDisposable(subscriptions); + }, this); + }; + + /** + * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. + * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. + */ + observableProto.concat = function () { + for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } + args.unshift(this); + return observableConcat.apply(null, args); + }; + + var ConcatObservable = (function(__super__) { + inherits(ConcatObservable, __super__); + function ConcatObservable(sources) { + this.sources = sources; + __super__.call(this); + } + + ConcatObservable.prototype.subscribeCore = function(o) { + var sink = new ConcatSink(this.sources, o); + return sink.run(); + }; + + function ConcatSink(sources, o) { + this.sources = sources; + this.o = o; + } + ConcatSink.prototype.run = function () { + var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; + var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { + if (isDisposed) { return; } + if (i === length) { + return o.onCompleted(); + } + + // Check if promise + var currentValue = sources[i]; + isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + + var d = new SingleAssignmentDisposable(); + subscription.setDisposable(d); + d.setDisposable(currentValue.subscribe( + function (x) { o.onNext(x); }, + function (e) { o.onError(e); }, + function () { self(i + 1); } + )); + }); + + return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { + isDisposed = true; + })); + }; + + + return ConcatObservable; + }(ObservableBase)); + + /** + * Concatenates all the observable sequences. + * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. + * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. + */ + var observableConcat = Observable.concat = function () { + var args; + if (Array.isArray(arguments[0])) { + args = arguments[0]; + } else { + args = new Array(arguments.length); + for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } + } + return new ConcatObservable(args); + }; + + /** + * Concatenates an observable sequence of observable sequences. + * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + observableProto.concatAll = observableProto.concatObservable = function () { + return this.merge(1); + }; + + var MergeObservable = (function (__super__) { + inherits(MergeObservable, __super__); - 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]} - ); - }; + function MergeObservable(source, maxConcurrent) { + this.source = source; + this.maxConcurrent = maxConcurrent; + __super__.call(this); + } - Map.prototype.mergeDeep = function(/*...iters*/) { - return mergeIntoMapWith(this, deepMerger, arguments); + MergeObservable.prototype.subscribeCore = function(observer) { + var g = new CompositeDisposable(); + g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); + return g; }; - Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); - return mergeIntoMapWith(this, deepMergerWith(merger), iters); - }; + return MergeObservable; - 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]} - ); - }; + }(ObservableBase)); - 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); + var MergeObserver = (function () { + function MergeObserver(o, max, g) { + this.o = o; + this.max = max; + this.g = g; + this.done = false; + this.q = []; + this.activeCount = 0; + this.isStopped = false; + } + MergeObserver.prototype.handleSubscribe = function (xs) { + var sad = new SingleAssignmentDisposable(); + this.g.add(sad); + isPromise(xs) && (xs = observableFromPromise(xs)); + sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; + MergeObserver.prototype.onNext = function (innerSource) { + if (this.isStopped) { return; } + if(this.activeCount < this.max) { + this.activeCount++; + this.handleSubscribe(innerSource); + } else { + this.q.push(innerSource); + } + }; + MergeObserver.prototype.onError = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + } + }; + MergeObserver.prototype.onCompleted = function () { + if (!this.isStopped) { + this.isStopped = true; + this.done = true; + this.activeCount === 0 && this.o.onCompleted(); + } + }; + MergeObserver.prototype.dispose = function() { this.isStopped = true; }; + MergeObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; + } - 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; - }; + return false; + }; - Map.prototype.__ensureOwner = function(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - this.__ownerID = ownerID; - this.__altered = false; - return this; + function InnerObserver(parent, sad) { + this.parent = parent; + this.sad = sad; + this.isStopped = false; } - return makeMap(this.size, this._root, ownerID, this.__hash); - }; - - - function isMap(maybeMap) { - return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); - } + 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) { + this.isStopped = true; + var parent = this.parent; + parent.g.remove(this.sad); + if (parent.q.length > 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; + } - Map.isMap = isMap; + return false; + }; - var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; + return MergeObserver; + }()); - var MapPrototype = Map.prototype; - MapPrototype[IS_MAP_SENTINEL] = true; - MapPrototype[DELETE] = MapPrototype.remove; - MapPrototype.removeIn = MapPrototype.deleteIn; - // #pragma Trie Nodes + /** + * 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 ArrayMapNode(ownerID, entries) { - this.ownerID = ownerID; - this.entries = entries; + function MergeAllObservable(source) { + this.source = source; + __super__.call(this); } - 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; + 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); - 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; + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); - if (exists ? entries[idx][1] === value : removed) { - return this; + 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); } - - SetRef(didAlter); - (removed || !exists) && SetRef(didChangeSize); - - if (removed && entries.length === 1) { - return; // undefined + }; + MergeAllObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.done = true; + this.g.length === 1 && this.o.onCompleted(); } - - if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { - return createNodes(ownerID, entries, key, value); + }; + MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; + MergeAllObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; } - 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); + return false; }; - - - - function BitmapIndexedNode(ownerID, bitmap, nodes) { - this.ownerID = ownerID; - this.bitmap = bitmap; - this.nodes = nodes; + function InnerObserver(parent, g, sad) { + this.parent = parent; + this.g = g; + this.sad = sad; + this.isStopped = false; } - - 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; + 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); } - - 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); + 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(); } - 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; + 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 new HashArrayMapNode(ownerID, newCount, newNodes); + 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; - - function HashCollisionNode(ownerID, keyHash, entries) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entries = entries; + /** + * 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); - 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]); - } + return new AnonymousObservable(function (o) { + var group = new CompositeDisposable(), + m = new SingleAssignmentDisposable(), + isStopped = false, + errors = []; - var entries = this.entries; - var idx = 0; - for (var len = entries.length; idx < len; idx++) { - if (is(key, entries[idx][0])) { - break; + function setCompletion() { + if (errors.length === 0) { + o.onCompleted(); + } else if (errors.length === 1) { + o.onError(errors[0]); + } else { + o.onError(new CompositeError(errors)); } } - var exists = idx < len; - if (exists ? entries[idx][1] === value : removed) { - return this; - } + group.add(m); - SetRef(didAlter); - (removed || !exists) && SetRef(didChangeSize); + m.setDisposable(source.subscribe( + function (innerSource) { + var innerSubscription = new SingleAssignmentDisposable(); + group.add(innerSubscription); - 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); + // Check for promises support + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); - if (exists) { - if (removed) { - idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); + 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 { - newEntries[idx] = [key, value]; + observer.onCompleted(); } - } else { - newEntries.push([key, value]); - } - - if (isEditable) { - this.entries = newEntries; - return this; - } - - return new HashCollisionNode(ownerID, this.keyHash, newEntries); - }; - + }); + 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(); + })); - function ValueNode(ownerID, keyHash, entry) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entry = entry; + return disposables; + }, source); + }; + + var SwitchObservable = (function(__super__) { + inherits(SwitchObservable, __super__); + function SwitchObservable(source) { + this.source = source; + __super__.call(this); } - ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { - return is(key, this.entry[0]) ? this.entry[1] : notSetValue; + SwitchObservable.prototype.subscribeCore = function (o) { + var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); + return new CompositeDisposable(s, inner); }; - 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; + 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); } - - SetRef(didAlter); - - if (removed) { - SetRef(didChangeSize); - return; // undefined + }; + 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; + }; - if (keyMatch) { - if (ownerID && ownerID === this.ownerID) { - this.entry[1] = value; - return this; + 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(); } - return new ValueNode(ownerID, this.keyHash, [key, value]); } - - SetRef(didChangeSize); - return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); + }; + 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__); - // #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; - } + function TakeUntilObservable(source, other) { + this.source = source; + this.other = isPromise(other) ? observableFromPromise(other) : other; + __super__.call(this); } - } - ValueNode.prototype.iterate = function (fn, reverse) { - return fn(this.entry); - } - - createClass(MapIterator, Iterator); + TakeUntilObservable.prototype.subscribeCore = function(o) { + return new CompositeDisposable( + this.source.subscribe(o), + this.other.subscribe(new InnerObserver(o)) + ); + }; - function MapIterator(map, type, reverse) { - this._type = type; - this._reverse = reverse; - this._stack = map._root && mapIteratorFrame(map._root); + function InnerObserver(o) { + this.o = o; + this.isStopped = false; } - - 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; + 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); } - return iteratorDone(); + }; + 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)); - function mapIteratorValue(type, entry) { - return iteratorValue(type, entry[0], entry[1]); - } - - function mapIteratorFrame(node, prev) { - return { - node: node, - index: 0, - __prev: prev - }; - } + /** + * 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; } - 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; - } + /** + * 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]); - var EMPTY_MAP; - function emptyMap() { - return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); - } + return new AnonymousObservable(function (observer) { + var n = args.length, + hasValue = arrayInitialize(n, falseFactory), + hasValueAll = false, + values = new Array(n); - 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; + 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)); } - 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); - } + 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; - function isLeafNode(node) { - return node.constructor === ValueNode || node.constructor === HashCollisionNode; + 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 mergeIntoNode(node, ownerID, shift, keyHash, entry) { - if (node.keyHash === keyHash) { - return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); - } + function falseFactory() { return false; } + function emptyArrayFactory() { return []; } - var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; - var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + /** + * 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 newNode; - var nodes = idx1 === idx2 ? - [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : - ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); + 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); - return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); - } + 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); + } - 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 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 node; - } + return new AnonymousObservable(function (o) { + var n = sources.length, + queues = arrayInitialize(n, arrayFactory), + isDone = arrayInitialize(n, falseFactory); - 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; + 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 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; + 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; } - 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 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); } - 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; + TapObservable.prototype.subscribeCore = function(o) { + return this.source.subscribe(new InnerObserver(o, this.t)); }; - } - 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]); + function InnerObserver(o, t) { + this.o = o; + this.t = t; + this.isStopped = false; } - 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); + 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; + }; - 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); - } + return TapObservable; + }(ObservableBase)); - 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; - } + /** + * 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); + }; - function setIn(array, idx, val, canEdit) { - var newArray = canEdit ? array : arrCopy(array); - newArray[idx] = val; - return newArray; - } + /** + * 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); + }; - 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; - } + /** + * 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); + }; - 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; + /** + * 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; } - 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); + return disposableCreate(function () { + try { + subscription.dispose(); + } catch (e) { + throw e; + } finally { + action(); + } + }); + }, this); + }; - // @pragma Construction + /** + * @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 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)}); - }); + function IgnoreElementsObservable(source) { + this.source = source; + __super__.call(this); } - List.of = function(/*...values*/) { - return this(arguments); - }; - - List.prototype.toString = function() { - return this.__toString('List [', ']'); + IgnoreElementsObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o)); }; - // @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]; + 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); } - 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; + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { + this.isStopped = true; + this.o.onCompleted(); } - return emptyList(); }; + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function (e) { + if (!this.isStopped) { + this.isStopped = true; + this.observer.onError(e); + return true; + } - 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]); - } - }); + return false; }; - List.prototype.pop = function() { - return setListBounds(this, 0, -1); - }; + return IgnoreElementsObservable; + }(ObservableBase)); - 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); + /** + * 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(); }); - }; - - 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; - }; + }, 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); + } - 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); + ScanObservable.prototype.subscribeCore = function(observer) { + return this.source.subscribe(new ScanObserver(observer,this)); }; + return ScanObservable; + }(ObservableBase)); - function isList(maybeList) { - return !!(maybeList && maybeList[IS_LIST_SENTINEL]); + 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; } - - 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; + 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; + }; - // 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; - } + /** + * 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); - 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; - } - } + if (skip <= 0) { throw new ArgumentOutOfRangeError(); } + return new AnonymousObservable(function (observer) { + var m = new SingleAssignmentDisposable(), + refCountDisposable = new RefCountDisposable(m), + n = 0, + q = []; - var editable = editableVNode(this, ownerID); - editable.array.splice(sizeIndex + 1); - if (newChild) { - editable.array[sizeIndex] = newChild; + function createWindow () { + var s = new Subject(); + q.push(s); + observer.onNext(addRef(s, refCountDisposable)); } - 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); - } + createWindow(); - 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; + 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(); } - 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; + )); + 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(); } - 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; - } + /** + * 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)); - 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) + return selectorResult.map(function (y, i2) { + return resultSelector(x, y, i, i2); + }); }); } - - 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 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 newNode; + return -1; } - function editableVNode(node, ownerID) { - if (ownerID && node && ownerID === node.ownerID) { - return node; - } - return new VNode(node ? node.array.slice() : [], ownerID); + 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; + }; - 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; - } - } + /** + * 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; - 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; - } + 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); - var oldTailOffset = getTailOffset(oldCapacity); - var newTailOffset = getTailOffset(newCapacity); + groupDisposable.add(source.subscribe(function (x) { + var key; + try { + key = keySelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } - // New size might need creating a higher root. - while (newTailOffset >= 1 << (newLevel + SHIFT)) { - newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); - newLevel += SHIFT; - } + var fireNewMapEntry = false, + writer = map.tryGetValue(key); + if (!writer) { + writer = new Subject(); + map.set(key, writer); + fireNewMapEntry = true; + } - // Locate or create the new tail. - var oldTail = list._tail; - var newTail = newTailOffset < oldTailOffset ? - listNodeFor(list, newCapacity - 1) : - newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; + 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; + } - // 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; - } + observer.onNext(group); - // 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); - } + var md = new SingleAssignmentDisposable(); + groupDisposable.add(md); - // 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); + var expire = function () { + map.remove(key) && writer.onCompleted(); + groupDisposable.remove(md); + }; - // Otherwise, if the root has been trimmed, garbage collect. - } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { - offsetShift = 0; + md.setDisposable(duration.take(1).subscribe( + noop, + function (exn) { + map.getValues().forEach(handleError(exn)); + observer.onError(exn); + }, + expire) + ); + } - // 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]; - } + var element; + try { + element = elementSelector(x); + } catch (e) { + map.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } - // 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; - } - } + writer.onNext(element); + }, function (ex) { + map.getValues().forEach(handleError(ex)); + observer.onError(ex); + }, function () { + map.getValues().forEach(function (item) { item.onCompleted(); }); + observer.onCompleted(); + })); - 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); - } + return refCountDisposable; + }, source); + }; + + var MapObservable = (function (__super__) { + inherits(MapObservable, __super__); - 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); + function MapObservable(source, selector, thisArg) { + this.source = source; + this.selector = bindCallback(selector, thisArg, 3); + __super__.call(this); } - if (maxSize > list.size) { - list = list.setSize(maxSize); + + function innerMap(selector, self) { + return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } } - return mergeIntoCollectionWith(list, merger, iters); - } - - function getTailOffset(size) { - return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); - } - - createClass(OrderedMap, Map); - // @pragma Construction + MapObservable.prototype.internalMap = function (selector, thisArg) { + return new MapObservable(this.source, innerMap(selector, this), thisArg); + }; - 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; + MapObservable.prototype.subscribeCore = function (o) { + return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; - - // @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; + + 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); } - 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(); + this.o.onNext(result); }; - - 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 - ); + InnerObserver.prototype.onError = function (e) { + if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; - - OrderedMap.prototype.__iterator = function(type, reverse) { - return this._list.fromEntrySeq().__iterator(type, reverse); + InnerObserver.prototype.onCompleted = function () { + if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; - - 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; + 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 makeOrderedMap(newMap, newList, ownerID, this.__hash); + + return false; }; + return MapObservable; - 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())); - } + }(ObservableBase)); - 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; + /** + * 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; } - 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); + 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(); } - createClass(ToKeyedSequence, KeyedSeq); - function ToKeyedSequence(indexed, useKeys) { - this._iter = indexed; - this._useKeys = useKeys; - this.size = indexed.size; - } + /** + * 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)); - ToKeyedSequence.prototype.get = function(key, notSetValue) { - return this._iter.get(key, notSetValue); - }; + 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; - ToKeyedSequence.prototype.has = function(key) { - return this._iter.has(key); - }; - - ToKeyedSequence.prototype.valueSeq = function() { - return this._iter.valueSeq(); + 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)); }; - - 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()}; + + 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--; } - 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; + InnerObserver.prototype.onError = function(e) { + if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; - - 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 - ); + InnerObserver.prototype.onCompleted = function() { + if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; - - ToKeyedSequence.prototype.__iterator = function(type, reverse) { - if (this._useKeys) { - return this._iter.__iterator(type, reverse); + InnerObserver.prototype.dispose = function() { this.isStopped = true; }; + InnerObserver.prototype.fail = function(e) { + if (!this.isStopped) { + this.isStopped = true; + this.o.onError(e); + return true; } - 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); - }); + 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 2) { + for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } + } - // @pragma Modification + if (err) { + try { + ret = gen[throwString](err); + } catch (e) { + return exit(e); + } + } - Set.prototype.add = function(value) { - return updateSet(this, this._map.set(value, true)); - }; + if (!err) { + try { + ret = gen.next(res); + } catch (e) { + return exit(e); + } + } - Set.prototype.remove = function(value) { - return updateSet(this, this._map.remove(value)); - }; + if (ret.done) { + return exit(null, ret.value); + } - Set.prototype.clear = function() { - return updateSet(this, this._map.clear()); - }; + ret.value = toThunk(ret.value, ctx); - // @pragma Composition + if (typeof ret.value === fnString) { + var called = false; + try { + ret.value.call(ctx, function() { + if (called) { + return; + } - 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)}); + called = true; + next.apply(ctx, arguments); + }); + } catch (e) { + timeoutScheduler.schedule(function () { + if (called) { + return; + } + + called = true; + next.call(ctx, e); + }); + } + return; } - }); - }; - Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); - if (iters.length === 0) { - return this; + // Not supported + next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } - 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); - } - }); + function handleError(err) { + if (!err) { return; } + timeoutScheduler.schedule(function() { + throw err; + }); + } + + /** + * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. + * + * @example + * var res = Rx.Observable.start(function () { console.log('hello'); }); + * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); + * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); + * + * @param {Function} func Function to run asynchronously. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + * + * Remarks + * * The function is called immediately, not during the subscription of the resulting sequence. + * * Multiple subscriptions to the resulting sequence can observe the function's result. + */ + Observable.start = function (func, context, scheduler) { + return observableToAsync(func, context, scheduler)(); + }; + + /** + * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. + * @param {Function} function Function to convert to an asynchronous function. + * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @returns {Function} Asynchronous function. + */ + var observableToAsync = Observable.toAsync = function (func, context, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return function () { + var args = arguments, + subject = new AsyncSubject(); + + scheduler.schedule(function () { + var result; + try { + result = func.apply(context, args); + } catch (e) { + subject.onError(e); + return; + } + subject.onNext(result); + subject.onCompleted(); }); + return subject.asObservable(); }; + }; + + /** + * Converts a callback function to an observable sequence. + * + * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. + * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. + */ + Observable.fromCallback = function (func, context, selector) { + return function () { + var len = arguments.length, args = new Array(len) + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } - Set.prototype.merge = function() { - return this.union.apply(this, arguments); - }; + return new AnonymousObservable(function (observer) { + function handler() { + var len = arguments.length, results = new Array(len); + for(var i = 0; i < len; i++) { results[i] = arguments[i]; } - Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); - return this.union.apply(this, iters); - }; + if (selector) { + try { + results = selector.apply(context, results); + } catch (e) { + return observer.onError(e); + } - Set.prototype.sort = function(comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator)); - }; + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } - Set.prototype.sortBy = function(mapper, comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator, mapper)); - }; + observer.onCompleted(); + } - Set.prototype.wasAltered = function() { - return this._map.wasAltered(); + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); }; + }; + + /** + * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. + * @param {Function} func The function to call + * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. + * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. + * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. + */ + Observable.fromNodeCallback = function (func, context, selector) { + return function () { + var len = arguments.length, args = new Array(len); + for(var i = 0; i < len; i++) { args[i] = arguments[i]; } - Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; - return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); - }; + return new AnonymousObservable(function (observer) { + function handler(err) { + if (err) { + observer.onError(err); + return; + } - Set.prototype.__iterator = function(type, reverse) { - return this._map.map(function(_, k) {return k}).__iterator(type, reverse); - }; + var len = arguments.length, results = []; + for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } - 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); - }; + if (selector) { + try { + results = selector.apply(context, results); + } catch (e) { + return observer.onError(e); + } + observer.onNext(results); + } else { + if (results.length <= 1) { + observer.onNext.apply(observer, results); + } else { + observer.onNext(results); + } + } + observer.onCompleted(); + } - function isSet(maybeSet) { - return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); + args.push(handler); + func.apply(context, args); + }).publishLast().refCount(); + }; + }; + + function createListener (element, name, handler) { + if (element.addEventListener) { + element.addEventListener(name, handler, false); + return disposableCreate(function () { + element.removeEventListener(name, handler, false); + }); + } + throw new Error('No listener found'); } - 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 createEventListener (el, eventName, handler) { + var disposables = new CompositeDisposable(); - function updateSet(set, newMap) { - if (set.__ownerID) { - set.size = newMap.size; - set._map = newMap; - return set; + // Asume NodeList or HTMLCollection + var toStr = Object.prototype.toString; + if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') { + for (var i = 0, len = el.length; i < len; i++) { + disposables.add(createEventListener(el.item(i), eventName, handler)); + } + } else if (el) { + disposables.add(createListener(el, eventName, handler)); } - 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())); + return disposables; } - 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)}); - }); - } + /** + * Configuration option to determine whether to use native events only + */ + Rx.config.useNativeEvents = false; - OrderedSet.of = function(/*...values*/) { - return this(arguments); - }; + /** + * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. + * + * @example + * var source = Rx.Observable.fromEvent(element, 'mouseup'); + * + * @param {Object} element The DOMElement or NodeList to attach a listener. + * @param {String} eventName The event name to attach the observable sequence. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence of events from the specified element and the specified event. + */ + Observable.fromEvent = function (element, eventName, selector) { + // Node.js specific + if (element.addListener) { + return fromEventPattern( + function (h) { element.addListener(eventName, h); }, + function (h) { element.removeListener(eventName, h); }, + selector); + } - OrderedSet.fromKeys = function(value) { - return this(KeyedIterable(value).keySeq()); - }; + // Use only if non-native events are allowed + if (!Rx.config.useNativeEvents) { + // Handles jq, Angular.js, Zepto, Marionette, Ember.js + if (typeof element.on === 'function' && typeof element.off === 'function') { + return fromEventPattern( + function (h) { element.on(eventName, h); }, + function (h) { element.off(eventName, h); }, + selector); + } + } + return new AnonymousObservable(function (observer) { + return createEventListener( + element, + eventName, + function handler (e) { + var results = e; - OrderedSet.prototype.toString = function() { - return this.__toString('OrderedSet {', '}'); - }; + if (selector) { + try { + results = selector(arguments); + } catch (err) { + return observer.onError(err); + } + } + observer.onNext(results); + }); + }).publish().refCount(); + }; + + /** + * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. + * @param {Function} addHandler The function to add a handler to the emitter. + * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. + * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. + * @returns {Observable} An observable sequence which wraps an event from an event emitter + */ + var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { + return new AnonymousObservable(function (observer) { + function innerHandler (e) { + var result = e; + if (selector) { + try { + result = selector(arguments); + } catch (err) { + return observer.onError(err); + } + } + observer.onNext(result); + } - function isOrderedSet(maybeOrderedSet) { - return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); + var returnValue = addHandler(innerHandler); + return disposableCreate(function () { + if (removeHandler) { + removeHandler(innerHandler, returnValue); + } + }); + }).publish().refCount(); + }; + + /** + * Invokes the asynchronous function, surfacing the result through an observable sequence. + * @param {Function} functionAsync Asynchronous function which returns a Promise to run. + * @returns {Observable} An observable sequence exposing the function's result value, or an exception. + */ + Observable.startAsync = function (functionAsync) { + var promise; + try { + promise = functionAsync(); + } catch (e) { + return observableThrow(e); + } + return observableFromPromise(promise); } + + var PausableObservable = (function (__super__) { - OrderedSet.isOrderedSet = isOrderedSet; - - var OrderedSetPrototype = OrderedSet.prototype; - OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; + inherits(PausableObservable, __super__); - OrderedSetPrototype.__empty = emptyOrderedSet; - OrderedSetPrototype.__make = makeOrderedSet; + function subscribe(observer) { + var conn = this.source.publish(), + subscription = conn.subscribe(observer), + connection = disposableEmpty; - function makeOrderedSet(map, ownerID) { - var set = Object.create(OrderedSetPrototype); - set.size = map ? map.size : 0; - set._map = map; - set.__ownerID = ownerID; - return set; - } + var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { + if (b) { + connection = conn.connect(); + } else { + connection.dispose(); + connection = disposableEmpty; + } + }); - var EMPTY_ORDERED_SET; - function emptyOrderedSet() { - return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); - } + return new CompositeDisposable(subscription, connection, pausable); + } - createClass(Stack, IndexedCollection); + function PausableObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); - // @pragma Construction + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; + } - function Stack(value) { - return value === null || value === undefined ? emptyStack() : - isStack(value) ? value : - emptyStack().unshiftAll(value); + __super__.call(this, subscribe, source); } - Stack.of = function(/*...values*/) { - return this(arguments); + PausableObservable.prototype.pause = function () { + this.controller.onNext(false); }; - Stack.prototype.toString = function() { - return this.__toString('Stack [', ']'); + PausableObservable.prototype.resume = function () { + this.controller.onNext(true); }; - // @pragma Access + return PausableObservable; - Stack.prototype.get = function(index, notSetValue) { - var head = this._head; - index = wrapIndex(this, index); - while (head && index--) { - head = head.next; + }(Observable)); + + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausable(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausable = function (pauser) { + return new PausableObservable(this, pauser); + }; + + function combineLatestSource(source, subject, resultSelector) { + return new AnonymousObservable(function (o) { + var hasValue = [false, false], + hasValueAll = false, + isDone = false, + values = new Array(2), + err; + + function next(x, i) { + values[i] = x + hasValue[i] = true; + if (hasValueAll || (hasValueAll = hasValue.every(identity))) { + if (err) { return o.onError(err); } + var res = tryCatch(resultSelector).apply(null, values); + if (res === errorObj) { return o.onError(res.e); } + o.onNext(res); + } + isDone && values[1] && o.onCompleted(); } - return head ? head.value : notSetValue; - }; - Stack.prototype.peek = function() { - return this._head && this._head.value; - }; + return new CompositeDisposable( + source.subscribe( + function (x) { + next(x, 0); + }, + function (e) { + if (values[1]) { + o.onError(e); + } else { + err = e; + } + }, + function () { + isDone = true; + values[1] && o.onCompleted(); + }), + subject.subscribe( + function (x) { + next(x, 1); + }, + function (e) { o.onError(e); }, + function () { + isDone = true; + next(true, 1); + }) + ); + }, source); + } - // @pragma Modification + var PausableBufferedObservable = (function (__super__) { - 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); - }; + inherits(PausableBufferedObservable, __super__); - 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); - }; + function subscribe(o) { + var q = [], previousShouldFire; - Stack.prototype.unshiftAll = function(iter) { - return this.pushAll(iter); - }; + function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } - Stack.prototype.shift = function() { - return this.pop.apply(this, arguments); - }; + 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; + // change in shouldFire + if (results.shouldFire) { drainQueue(); } + } else { + previousShouldFire = results.shouldFire; + // new data + if (results.shouldFire) { + o.onNext(results.data); + } else { + q.push(results.data); + } + } + }, + function (err) { + drainQueue(); + o.onError(err); + }, + function () { + drainQueue(); + o.onCompleted(); + } + ); + return subscription; + } - 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(); - }; + function PausableBufferedObservable(source, pauser) { + this.source = source; + this.controller = new Subject(); - 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; + if (pauser && pauser.subscribe) { + this.pauser = this.controller.merge(pauser); + } else { + this.pauser = this.controller; } - return makeStack(newSize, head); - }; - // @pragma Mutability + __super__.call(this, subscribe, source); + } - 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); + PausableBufferedObservable.prototype.pause = function () { + this.controller.onNext(false); }; - // @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; + PausableBufferedObservable.prototype.resume = function () { + this.controller.onNext(true); }; - 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(); - }); - }; + return PausableBufferedObservable; + }(Observable)); - function isStack(maybeStack) { - return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); - } + /** + * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, + * and yields the values that were buffered while paused. + * @example + * var pauser = new Rx.Subject(); + * var source = Rx.Observable.interval(100).pausableBuffered(pauser); + * @param {Observable} pauser The observable sequence used to pause the underlying sequence. + * @returns {Observable} The observable sequence which is paused based upon the pauser. + */ + observableProto.pausableBuffered = function (subject) { + return new PausableBufferedObservable(this, subject); + }; + + var ControlledObservable = (function (__super__) { - Stack.isStack = isStack; + inherits(ControlledObservable, __super__); - var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; + function subscribe (observer) { + return this.source.subscribe(observer); + } - 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 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); + }; - 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; - } + return ControlledObservable; - var EMPTY_STACK; - function emptyStack() { - return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); - } + }(Observable)); - /** - * 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; - } + var ControlledSubject = (function (__super__) { - Iterable.Iterator = Iterator; + function subscribe (observer) { + return this.subject.subscribe(observer); + } - mixin(Iterable, { + inherits(ControlledSubject, __super__); - // ### Conversion to other types + function ControlledSubject(enableQueue, scheduler) { + enableQueue == null && (enableQueue = true); - toArray: function() { - assertNotInfinite(this.size); - var array = new Array(this.size || 0); - this.valueSeq().__iterate(function(v, i) { array[i] = v; }); - return array; - }, + __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; + } - toIndexedSeq: function() { - return new ToIndexedSequence(this); - }, + 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; - toJS: function() { - return this.toSeq().map( - function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} - ).__toJS(); - }, + 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 = []; + } + } - toJSON: function() { - return this.toSeq().map( - function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} - ).__toJS(); - }, + return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; + } - toKeyedSeq: function() { - return new ToKeyedSequence(this, true); - }, + return { numberOfItems: numberOfItems, returnValue: false }; + }, + request: function (number) { + this.disposeCurrentRequest(); + var self = this; - toMap: function() { - // Use Late Binding here to solve the circular dependency. - return Map(this.toKeyedSeq()); - }, + 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; + }); + } + }); - toObject: function() { - assertNotInfinite(this.size); - var object = {}; - this.__iterate(function(v, k) { object[k] = v; }); - return object; - }, + return this.requestedDisposable; + }, + disposeCurrentRequest: function () { + this.requestedDisposable.dispose(); + this.requestedDisposable = disposableEmpty; + } + }); - toOrderedMap: function() { - // Use Late Binding here to solve the circular dependency. - return OrderedMap(this.toKeyedSeq()); - }, + return ControlledSubject; + }(Observable)); - toOrderedSet: function() { - // Use Late Binding here to solve the circular dependency. - return OrderedSet(isKeyed(this) ? this.valueSeq() : this); - }, + /** + * Attaches a controller to the observable sequence with the ability to queue. + * @example + * var source = Rx.Observable.interval(100).controlled(); + * source.request(3); // Reads 3 values + * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request + * @param {Scheduler} scheduler determines how the requests will be scheduled + * @returns {Observable} The observable sequence which only propagates values on request. + */ + observableProto.controlled = function (enableQueue, scheduler) { - toSet: function() { - // Use Late Binding here to solve the circular dependency. - return Set(isKeyed(this) ? this.valueSeq() : this); - }, + if (enableQueue && isScheduler(enableQueue)) { + scheduler = enableQueue; + enableQueue = true; + } - toSetSeq: function() { - return new ToSetSequence(this); - }, + if (enableQueue == null) { enableQueue = true; } + return new ControlledObservable(this, enableQueue, scheduler); + }; + + var StopAndWaitObservable = (function (__super__) { - toSeq: function() { - return isIndexed(this) ? this.toIndexedSeq() : - isKeyed(this) ? this.toKeyedSeq() : - this.toSetSeq(); - }, + function subscribe (observer) { + this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); - toStack: function() { - // Use Late Binding here to solve the circular dependency. - return Stack(isKeyed(this) ? this.valueSeq() : this); - }, + var self = this; + timeoutScheduler.schedule(function () { self.source.request(1); }); - toList: function() { - // Use Late Binding here to solve the circular dependency. - return List(isKeyed(this) ? this.valueSeq() : this); - }, + return this.subscription; + } + + inherits(StopAndWaitObservable, __super__); + function StopAndWaitObservable (source) { + __super__.call(this, subscribe, source); + this.source = source; + } - // ### Common JavaScript methods and properties + var StopAndWaitObserver = (function (__sub__) { - toString: function() { - return '[Iterable]'; - }, + inherits(StopAndWaitObserver, __sub__); - __toString: function(head, tail) { - if (this.size === 0) { - return head + tail; + function StopAndWaitObserver (observer, observable, cancel) { + __sub__.call(this); + this.observer = observer; + this.observable = observable; + this.cancel = cancel; } - return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; - }, + var stopAndWaitObserverProto = StopAndWaitObserver.prototype; - // ### ES6 Collection methods (ES6 Array and Map) + stopAndWaitObserverProto.completed = function () { + this.observer.onCompleted(); + this.dispose(); + }; - concat: function() {var values = SLICE$0.call(arguments, 0); - return reify(this, concatFactory(this, values)); - }, + stopAndWaitObserverProto.error = function (error) { + this.observer.onError(error); + this.dispose(); + } - includes: function(searchValue) { - return this.some(function(value ) {return is(value, searchValue)}); - }, + stopAndWaitObserverProto.next = function (value) { + this.observer.onNext(value); - entries: function() { - return this.__iterator(ITERATE_ENTRIES); - }, + var self = this; + timeoutScheduler.schedule(function () { + self.observable.source.request(1); + }); + }; - 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; + stopAndWaitObserverProto.dispose = function () { + this.observer = null; + if (this.cancel) { + this.cancel.dispose(); + this.cancel = null; } - }); - return returnValue; - }, + __sub__.prototype.dispose.call(this); + }; - filter: function(predicate, context) { - return reify(this, filterFactory(this, predicate, context, true)); - }, + return StopAndWaitObserver; + }(AbstractObserver)); - find: function(predicate, context, notSetValue) { - var entry = this.findEntry(predicate, context); - return entry ? entry[1] : notSetValue; - }, + return StopAndWaitObservable; + }(Observable)); - 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; - }, + /** + * Attaches a stop and wait observable to the current observable. + * @returns {Observable} A stop and wait observable. + */ + ControlledObservable.prototype.stopAndWait = function () { + return new StopAndWaitObservable(this); + }; + + var WindowedObservable = (function (__super__) { - keys: function() { - return this.__iterator(ITERATE_KEYS); - }, + function subscribe (observer) { + this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); - map: function(mapper, context) { - return reify(this, mapFactory(this, mapper, context)); - }, + var self = this; + timeoutScheduler.schedule(function () { + self.source.request(self.windowSize); + }); - 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); - }, + return this.subscription; + } - isEmpty: function() { - return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); - }, + inherits(WindowedObservable, __super__); - count: function(predicate, context) { - return ensureSize( - predicate ? this.toSeq().filter(predicate, context) : this - ); - }, + function WindowedObservable(source, windowSize) { + __super__.call(this, subscribe, source); + this.source = source; + this.windowSize = windowSize; + } - countBy: function(grouper, context) { - return countByFactory(this, grouper, context); - }, + var WindowedObserver = (function (__sub__) { - equals: function(other) { - return deepEqual(this, other); - }, + inherits(WindowedObserver, __sub__); - 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); + function WindowedObserver(observer, observable, cancel) { + this.observer = observer; + this.observable = observable; + this.cancel = cancel; + this.received = 0; } - 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); - }, - - findEntry: function(predicate, context, notSetValue) { - var found = notSetValue; - this.__iterate(function(v, k, c) { - if (predicate.call(context, v, k, c)) { - found = [k, v]; - return false; - } - }); - return found; - }, - - findKey: function(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry && entry[0]; - }, - - findLast: function(predicate, context, notSetValue) { - return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); - }, - findLastEntry: function(predicate, context, notSetValue) { - return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); - }, - - findLastKey: function(predicate, context) { - return this.toKeyedSeq().reverse().findKey(predicate, context); - }, - - first: function() { - return this.find(returnTrue); - }, - - flatMap: function(mapper, context) { - return reify(this, flatMapFactory(this, mapper, context)); - }, + var windowedObserverPrototype = WindowedObserver.prototype; - flatten: function(depth) { - return reify(this, flattenFactory(this, depth, true)); - }, + windowedObserverPrototype.completed = function () { + this.observer.onCompleted(); + this.dispose(); + }; - fromEntrySeq: function() { - return new FromEntriesSequence(this); - }, + windowedObserverPrototype.error = function (error) { + this.observer.onError(error); + this.dispose(); + }; - get: function(searchKey, notSetValue) { - return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); - }, + windowedObserverPrototype.next = function (value) { + this.observer.onNext(value); - 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; + this.received = ++this.received % this.observable.windowSize; + if (this.received === 0) { + var self = this; + timeoutScheduler.schedule(function () { + self.observable.source.request(self.observable.windowSize); + }); } - } - 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); - }, + windowedObserverPrototype.dispose = function () { + this.observer = null; + if (this.cancel) { + this.cancel.dispose(); + this.cancel = null; + } + __sub__.prototype.dispose.call(this); + }; - keyOf: function(searchValue) { - return this.findKey(function(value ) {return is(value, searchValue)}); - }, + return WindowedObserver; + }(AbstractObserver)); - keySeq: function() { - return this.toSeq().map(keyMapper).toIndexedSeq(); - }, + return WindowedObservable; + }(Observable)); - last: function() { - return this.toSeq().reverse().first(); - }, + /** + * Creates a sliding windowed observable based upon the window size. + * @param {Number} windowSize The number of items in the window + * @returns {Observable} A windowed observable based upon the window size. + */ + ControlledObservable.prototype.windowed = function (windowSize) { + return new WindowedObservable(this, windowSize); + }; + + /** + * Pipes the existing Observable sequence into a Node.js Stream. + * @param {Stream} dest The destination Node.js stream. + * @returns {Stream} The destination stream. + */ + observableProto.pipe = function (dest) { + var source = this.pausableBuffered(); - lastKeyOf: function(searchValue) { - return this.toKeyedSeq().reverse().keyOf(searchValue); - }, + function onDrain() { + source.resume(); + } - max: function(comparator) { - return maxFactory(this, comparator); - }, + dest.addListener('drain', onDrain); - maxBy: function(mapper, comparator) { - return maxFactory(this, comparator, mapper); - }, + source.subscribe( + function (x) { + !dest.write(String(x)) && source.pause(); + }, + function (err) { + dest.emit('error', err); + }, + function () { + // Hack check because STDIO is not closable + !dest._isStdio && dest.end(); + dest.removeListener('drain', onDrain); + }); - min: function(comparator) { - return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); - }, + source.resume(); - minBy: function(mapper, comparator) { - return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); - }, + return dest; + }; + + /** + * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each + * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's + * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. + * + * @example + * 1 - res = source.multicast(observable); + * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); + * + * @param {Function|Subject} subjectOrSubjectSelector + * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + * Or: + * Subject to push source elements into. + * + * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if 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(); + } - sortBy: function(mapper, comparator) { - return reify(this, sortFactory(this, comparator, mapper)); - }, + 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; - take: function(amount) { - return this.slice(0, Math.max(0, amount)); - }, + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } - 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(); - }, + 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__) { - // ### Hashable Object + var maxSafeInteger = Math.pow(2, 53) - 1; - hashCode: function() { - return this.__hash || (this.__hash = hashIterable(this)); + 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); - // ### 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; - - mixin(KeyedIterable, { - - // ### More sequential methods - - flip: function() { - return reify(this, flipFactory(this)); - }, + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } - 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() - ); - }, + if (this.hasError) { + so.onError(this.error); + } else if (this.isStopped) { + so.onCompleted(); + } - 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() - ); + so.ensureActive(); + return subscription; } - }); - - 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)}; + 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); - mixin(IndexedIterable, { + 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; + } + }); - // ### Conversion to other types + return ReplaySubject; + }(Observable)); + + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); - toKeyedSeq: function() { - return new ToKeyedSequence(this, false); - }, + 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; + }; - // ### ES6 Collection methods (ES6 Array and Map) + __super__.call(this, function (o) { return subject.subscribe(o); }); + } - filter: function(predicate, context) { - return reify(this, filterFactory(this, predicate, context, false)); - }, + 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(); + }; + }); + }; - findIndex: function(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry ? entry[0] : -1; - }, - - indexOf: function(searchValue) { - var key = this.keyOf(searchValue); - return key === undefined ? -1 : key; - }, - - lastIndexOf: function(searchValue) { - var key = this.lastKeyOf(searchValue); - return key === undefined ? -1 : key; - }, - - reverse: function() { - return reify(this, reverseFactory(this, false)); - }, - - slice: function(begin, end) { - return reify(this, sliceFactory(this, begin, end, false)); - }, + 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; - splice: function(index, removeNum /*, ...values*/) { - var numArgs = arguments.length; - removeNum = Math.max(removeNum | 0, 0); - if (numArgs === 0 || (numArgs === 2 && !removeNum)) { - return this; + function getObservable() { + if (!hasObservable) { + hasObservable = true; + observable = source.finally(function() { hasObservable = false; }).publish().refCount(); } - // 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 entry = this.findLastEntry(predicate, context); - return entry ? entry[0] : -1; - }, - - 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); - }, + return observable; + }; - has: function(index) { - index = wrapIndex(this, index); - return index >= 0 && (this.size !== undefined ? - this.size === Infinity || index < this.size : - this.indexOf(index) !== -1 - ); - }, + return new AnonymousObservable(function(o) { + return getObservable().subscribe(o); + }); + }; + + var Dictionary = (function () { - interpose: function(separator) { - return reify(this, interposeFactory(this, separator)); - }, + 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"; - 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; + 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 reify(this, interleaved); - }, - - keySeq: function() { - return Range(0, this.size); - }, - - 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)); + return true; } - }); - - 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); - }, - + 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; + } - // ### More sequential methods + 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; + } - keySeq: function() { - return this.valueSeq(); + 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; - SetIterable.prototype.has = IterablePrototype.includes; - SetIterable.prototype.contains = SetIterable.prototype.includes; + 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(); } - // Mixin subclasses + var id = 17 * uniqueIdCounter++; + obj.hashCode = function () { return id; }; + return id; + }; + }()); - mixin(KeyedSeq, KeyedIterable.prototype); - mixin(IndexedSeq, IndexedIterable.prototype); - mixin(SetSeq, SetIterable.prototype); + function newEntry() { + return { key: null, value: null, next: 0, hashCode: 0 }; + } - mixin(KeyedCollection, KeyedIterable.prototype); - mixin(IndexedCollection, IndexedIterable.prototype); - mixin(SetCollection, SetIterable.prototype); + 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; + } - // #pragma Helper functions + var dictionaryProto = Dictionary.prototype; - function keyMapper(v, k) { - return k; - } + 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; + }; - function entryMapper(v, k) { - return [k, v]; - } + dictionaryProto.add = function (key, value) { + this._insert(key, value, true); + }; - function not(predicate) { - return function() { - return !predicate.apply(this, arguments); - } - } - - function neg(predicate) { - return function() { - return -predicate.apply(this, arguments); - } - } + 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; + }; - function quoteString(value) { - return typeof value === 'string' ? JSON.stringify(value) : String(value); - } + 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; + }; - function defaultZipper() { - return arrCopy(arguments); - } + 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; + }; - function defaultNegComparator(a, b) { - return a < b ? 1 : a > b ? -1 : 0; - } + 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; + }; - 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); - } + 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; + }; - 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; - } + dictionaryProto.count = function () { + return this.size - this.freeCount; + }; - function hashMerge(a, b) { - return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int - } + dictionaryProto.tryGetValue = function (key) { + var entry = this._findEntry(key); + return entry >= 0 ? + this.entries[entry].value : + undefined; + }; - var Immutable = { + 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; + }; - Iterable: Iterable, + dictionaryProto.get = function (key) { + var entry = this._findEntry(key); + if (entry >= 0) { return this.entries[entry].value; } + throw new Error(noSuchkey); + }; - Seq: Seq, - Collection: Collection, - Map: Map, - OrderedMap: OrderedMap, - List: List, - Stack: Stack, - Set: Set, - OrderedSet: OrderedSet, + dictionaryProto.set = function (key, value) { + this._insert(key, value, false); + }; - Record: Record, - Range: Range, - Repeat: Repeat, + dictionaryProto.containskey = function (key) { + return this._findEntry(key) >= 0; + }; - is: is, - fromJS: fromJS + 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(); - return Immutable; + leftMap.add(id, value); + group.add(md); -})); -},{}],95:[function(require,module,exports){ -(function (global){ -'use strict'; + var expire = function () { + leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); + group.remove(md); + }; -/*global window, global*/ + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } -var root = typeof window !== 'undefined' ? - window : typeof global !== 'undefined' ? - global : {}; + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); -module.exports = Individual; + rightMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(value, v); + } catch (exn) { + observer.onError(exn); + return; + } -function Individual(key, value) { - if (key in root) { - return root[key]; - } + observer.onNext(result); + }); + }, + observer.onError.bind(observer), + function () { + leftDone = true; + (rightDone || leftMap.count() === 0) && observer.onCompleted(); + }) + ); - root[key] = value; - - return value; -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],96:[function(require,module,exports){ -'use strict'; + group.add(right.subscribe( + function (value) { + var id = rightId++; + var md = new SingleAssignmentDisposable(); -var Individual = require('./index.js'); + rightMap.add(id, value); + group.add(md); -module.exports = OneVersion; + var expire = function () { + rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); + group.remove(md); + }; -function OneVersion(moduleName, version, defaultValue) { - var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName; - var enforceKey = key + '_ENFORCE_SINGLETON'; + var duration; + try { + duration = rightDurationSelector(value); + } catch (e) { + observer.onError(e); + return; + } - var versionValue = Individual(enforceKey, version); + md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); - 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); - } + leftMap.getValues().forEach(function (v) { + var result; + try { + result = resultSelector(v, value); + } catch (exn) { + observer.onError(exn); + return; + } - return Individual(key, defaultValue); -} + 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; -},{"./index.js":95}],97:[function(require,module,exports){ -"use strict"; + function handleError(e) { return function (v) { v.onError(e); }; }; -module.exports = function isObject(x) { - return typeof x === "object" && x !== null; -}; + group.add(left.subscribe( + function (value) { + var s = new Subject(); + var id = leftId++; + leftMap.add(id, s); -},{}],98:[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' - } - } -} + var result; + try { + result = resultSelector(value, addRef(s, r)); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } + observer.onNext(result); -/** - * Lowercase a string. - * - * @param {String} str - * @return {String} - */ -module.exports = function (str, locale) { - var lang = LANGUAGES[locale] + rightMap.getValues().forEach(function (v) { s.onNext(v); }); - str = str == null ? '' : String(str) + var md = new SingleAssignmentDisposable(); + group.add(md); - if (lang) { - str = str.replace(lang.regexp, function (m) { return lang.map[m] }) - } + var expire = function () { + leftMap.remove(id) && s.onCompleted(); + group.remove(md); + }; - return str.toLowerCase() -} + var duration; + try { + duration = leftDurationSelector(value); + } catch (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + return; + } -},{}],99:[function(require,module,exports){ -var sentenceCase = require('sentence-case') + 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)) + ); -/** - * Param case a string. - * - * @param {String} string - * @param {String} [locale] - * @return {String} - */ -module.exports = function (string, locale) { - return sentenceCase(string, locale, '-') -} + group.add(right.subscribe( + function (value) { + var id = rightId++; + rightMap.add(id, value); -},{"sentence-case":111}],100:[function(require,module,exports){ -(function (process,global){ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -;(function (undefined) { + var md = new SingleAssignmentDisposable(); + group.add(md); - var objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false - }; + var expire = function () { + rightMap.remove(id); + group.remove(md); + }; - var root = (objectTypes[typeof window] && window) || this, - freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, - freeModule = objectTypes[typeof module] && module && !module.nodeType && module, - moduleExports = freeModule && freeModule.exports === freeExports && freeExports, - freeGlobal = objectTypes[typeof global] && global; + 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) + ); - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; - } + leftMap.getValues().forEach(function (v) { v.onNext(value); }); + }, + function (e) { + leftMap.getValues().forEach(handleError(e)); + observer.onError(e); + }) + ); - var Rx = { - internals: {}, - config: { - Promise: root.Promise - }, - helpers: { } + return r; + }, left); }; - // Defaults - var noop = Rx.helpers.noop = function () { }, - notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, - identity = Rx.helpers.identity = function (x) { return x; }, - pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, - just = Rx.helpers.just = function (value) { return function () { return value; }; }, - defaultNow = Rx.helpers.defaultNow = Date.now, - defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, - defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > 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; + /** + * 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(); }); + }; - 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); + /** + * 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); } - } - - function filterStackString(stackString) { - var lines = stackString.split("\n"), - desiredLines = []; - for (var i = 0, len = lines.length; i < len; i++) { - var line = lines[i]; + return typeof windowOpeningsOrClosingSelector === 'function' ? + observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : + observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); + }; - if (!isInternalFrame(line) && !isNodeFrame(line) && line) { - desiredLines.push(line); - } - } - return desiredLines.join("\n"); + function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { + return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { + return win; + }); } - function isInternalFrame(stackLine) { - var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); - if (!fileNameAndLineNumber) { - return false; - } - var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; + function observableWindowWithBoundaries(windowBoundaries) { + var source = this; + return new AnonymousObservable(function (observer) { + var win = new Subject(), + d = new CompositeDisposable(), + r = new RefCountDisposable(d); - return fileName === rFileName && - lineNumber >= rStartingLine && - lineNumber <= rEndingLine; - } + observer.onNext(addRef(win, r)); - function isNodeFrame(stackLine) { - return stackLine.indexOf("(module.js:") !== -1 || - stackLine.indexOf("(node.js:") !== -1; - } + d.add(source.subscribe(function (x) { + win.onNext(x); + }, function (err) { + win.onError(err); + observer.onError(err); + }, function () { + win.onCompleted(); + observer.onCompleted(); + })); - function captureLine() { - if (!hasStacks) { return; } + isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); - 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; } + 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(); + })); - rFileName = fileNameAndLineNumber[0]; - return fileNameAndLineNumber[1]; - } + return r; + }, source); } - 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])]; } + 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(); + })); - // Anonymous functions: "at filename:lineNumber:columnNumber" - var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); - if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } + function createWindowClose () { + var windowClose; + try { + windowClose = windowClosingSelector(); + } catch (e) { + observer.onError(e); + return; + } - // Firefox style: "function@filename:lineNumber or @filename:lineNumber" - var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); - if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } + 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); } - var EmptyError = Rx.EmptyError = function() { - this.message = 'Sequence contains no elements.'; - Error.call(this); + /** + * 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); }; - EmptyError.prototype = Error.prototype; - - var ObjectDisposedError = Rx.ObjectDisposedError = function() { - this.message = 'Object has been disposed'; - Error.call(this); + + /** + * 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); }) + ]; }; - ObjectDisposedError.prototype = Error.prototype; - - var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { - this.message = 'Argument out of range'; - Error.call(this); + + 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); }; - ArgumentOutOfRangeError.prototype = Error.prototype; + + /** + * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers 0) { + isOwner = !isAcquired; + isAcquired = true; } - 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); - }; - } + 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(); + })); + } + }; - return function() { - return func.apply(thisArg, arguments); - }; + q.push(source); + activeCount++; + ensureActive(); + return d; + }, this); }; - /** 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; }; + JoinObserverPrototype.error = noop; + JoinObserverPrototype.completed = noop; - priorityProto.removeAt = function (index) { - this.items[index] = this.items[--this.length]; - this.items[this.length] = undefined; - this.heapify(); - }; + JoinObserverPrototype.addActivePlan = function (activePlan) { + this.activePlans.push(activePlan); + }; - priorityProto.dequeue = function () { - var result = this.peek(); - this.removeAt(0); - return result; - }; + JoinObserverPrototype.subscribe = function () { + this.subscription.setDisposable(this.source.materialize().subscribe(this)); + }; - priorityProto.enqueue = function (item) { - var index = this.length++; - this.items[index] = new IndexedItem(PriorityQueue.count++, item); - this.percolate(index); - }; + JoinObserverPrototype.removeActivePlan = function (activePlan) { + this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); + this.activePlans.length === 0 && this.dispose(); + }; - priorityProto.remove = function (item) { - for (var i = 0; i < this.length; i++) { - if (this.items[i].value === item) { - this.removeAt(i); - return true; + JoinObserverPrototype.dispose = function () { + __super__.prototype.dispose.call(this); + if (!this.isDisposed) { + this.isDisposed = true; + this.subscription.dispose(); } - } - return false; - }; - PriorityQueue.count = 0; + }; + + return JoinObserver; + } (AbstractObserver)); /** - * Represents a group of disposable resources that are disposed together. - * @constructor + * 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. */ - 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; + observableProto.and = function (right) { + return new Pattern([this, right]); }; - - 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. + * 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. */ - CompositeDisposablePrototype.add = function (item) { - if (this.isDisposed) { - item.dispose(); - } else { - this.disposables.push(item); - this.length++; - } + observableProto.thenDo = function (selector) { + return new Pattern([this]).thenDo(selector); }; - + /** - * 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. + * 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. */ - 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; - }; + 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); + }); + } + /** - * Disposes all disposables in the group and removes them from the group. + * 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. */ - 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(); - } - } + var observableinterval = Observable.interval = function (period, scheduler) { + return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** - * 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. + * 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 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; + 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); + } - /** - * 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 }; + function observableDelayDate(source, dueTime, scheduler) { + return observableDefer(function () { + return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); + }); + } /** - * 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. + * 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. */ - var isDisposable = Disposable.isDisposable = function (d) { - return d && isFunction(d.dispose); - }; - - var checkDisposed = Disposable.checkDisposed = function (disposable) { - if (disposable.isDisposed) { throw new ObjectDisposedError(); } + observableProto.delay = function (dueTime, scheduler) { + isScheduler(scheduler) || (scheduler = timeoutScheduler); + return dueTime instanceof Date ? + observableDelayDate(this, dueTime.getTime(), scheduler) : + observableDelayTimeSpan(this, dueTime, scheduler); }; - // 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(); + /** + * 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); }; - // 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(); + /** + * @deprecated use #debounce or #throttleWithTimeout instead. + */ + observableProto.throttle = function(dueTime, scheduler) { + //deprecate('throttle', 'debounce or throttleWithTimeout'); + return this.debounce(dueTime, scheduler); }; /** - * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. + * 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. */ - var RefCountDisposable = Rx.RefCountDisposable = (function () { - - function InnerDisposable(disposable) { - this.disposable = disposable; - this.disposable.count++; - this.isInnerDisposed = false; + 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); - 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(); + 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); + })); } - }; - /** - * 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; - } + observer.onNext(addRef(s, refCountDisposable)); + createTimer(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(); + 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); + }; + /** - * 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); + * 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(); }); }; - - 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); - }; + /** + * 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(); + }); + }; - 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; + /** + * 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 }; + }); + }); }; - - ScheduledItem.prototype.invokeCore = function () { - return this.action(this.scheduler, this.state); + + /** + * 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() }; + }); }; - /** Provides a set of static properties to access commonly used schedulers. */ - var Scheduler = Rx.Scheduler = (function () { + function sampleObservable(source, sampler) { + return new AnonymousObservable(function (o) { + var atEnd = false, value, hasValue = false; - function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { - this.now = now; - this._schedule = schedule; - this._scheduleRelative = scheduleRelative; - this._scheduleAbsolute = scheduleAbsolute; - } + function sampleSubscribe() { + if (hasValue) { + hasValue = false; + o.onNext(value); + } + atEnd && o.onCompleted(); + } - /** Determines whether the given object is a scheduler */ - Scheduler.isScheduler = function (s) { - return s instanceof Scheduler; - } + var sourceSubscription = new SingleAssignmentDisposable(); + sourceSubscription.setDisposable(source.subscribe( + function (newValue) { + hasValue = true; + value = newValue; + }, + function (e) { o.onError(e); }, + function () { + atEnd = true; + sourceSubscription.dispose(); + } + )); - function invokeAction(scheduler, action) { - action(); - return disposableEmpty; - } + return new CompositeDisposable( + sourceSubscription, + sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) + ); + }, source); + } - var schedulerProto = Scheduler.prototype; + /** + * 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); - /** - * 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); - }; + var source = this, schedulerMethod = dueTime instanceof Date ? + 'scheduleWithAbsolute' : + 'scheduleWithRelative'; - /** - * 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); - }; + return new AnonymousObservable(function (observer) { + var id = 0, + original = new SingleAssignmentDisposable(), + subscription = new SerialDisposable(), + switched = false, + timer = new SerialDisposable(); - /** - * 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); - }; + subscription.setDisposable(original); - /** - * 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); - }; + function createTimer() { + var myId = id; + timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { + if (id === myId) { + isPromise(other) && (other = observableFromPromise(other)); + subscription.setDisposable(other.subscribe(observer)); + } + })); + } - /** - * 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); - }; + createTimer(); - /** - * 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; - }; + 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); - return Scheduler; - }()); + 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); - var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; + 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(); + } + }); + }); + }; - (function (schedulerProto) { + /** + * 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(); - function invokeRecImmediate(scheduler, pair) { - var state = pair[0], action = pair[1], group = new CompositeDisposable(); + d.setDisposable(scheduler[scheduleMethod](dueTime, function() { + d.setDisposable(source.subscribe(o)); + })); - 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; + 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 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; + 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(); } - }); - }; - 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); - }; + function done () { + atEnd && delays.length === 0 && observer.onCompleted(); + } - /** - * 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); - }; + if (!subDelay) { + start(); + } else { + subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); + } + return new CompositeDisposable(subscription, delays); + }, this); + }; + /** - * 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). + * 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. */ - schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { - return this._scheduleRelative([state, action], dueTime, function (s, p) { - return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); - }); - }; + 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(); - /** - * 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); - }; + subscription.setDisposable(original); - /** - * 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) { + var id = 0, switched = false; - /** - * 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); - }; + function setTimer(timeout) { + var myId = id; - /** - * 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); }); - }; + function timerWins () { + return id === myId; + } - }(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; - } - } + 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)); + })); + }; - function SchedulePeriodicRecursive(scheduler, state, period, action) { - this._scheduler = scheduler; - this._state = state; - this._period = period; - this._action = action; - } + setTimer(firstTimeout); - SchedulePeriodicRecursive.prototype.start = function () { - var d = new SingleAssignmentDisposable(); - this._cancel = d; - d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); + function observerWins() { + var res = !switched; + if (res) { id++; } + return res; + } - return d; + 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); }; - - 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. + * 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. */ - var currentThreadScheduler = Scheduler.currentThread = (function () { - var queue; + 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; + } - function runTrampoline () { - while (queue.length > 0) { - var item = queue.dequeue(); - !item.isCancelled() && item.invoke(); - } - } + isPromise(throttle) && (throttle = observableFromPromise(throttle)); - function scheduleNow(state, action) { - var si = new ScheduledItem(this, state, action, this.now()); + 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); + }; - 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; - }()); + /** + * @deprecated use #debounceWithSelector instead. + */ + observableProto.throttleWithSelector = function (durationSelector) { + //deprecate('throttleWithSelector', 'debounceWithSelector'); + return this.debounceWithSelector(durationSelector); + }; - 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); } + /** + * 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); } - } - } - - 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)); + }, function (e) { o.onError(e); }, function () { + var now = scheduler.now(); + while (q.length > 0 && now - q[0].interval >= duration) { + o.onNext(q.shift().value); } - } - - 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; - }; - } - }()); - + o.onCompleted(); + }); + }, source); + }; + /** - * Gets a scheduler that schedules work via a timed callback based upon platform. + * 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. */ - 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)); + 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(); }); - 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); - })(); + }, source); + }; - 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; + /** + * 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(); } - }; - }; - - 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; + }, 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); } - })); - - return d; - }; - - return CatchScheduler; - }(Scheduler)); + o.onNext(res); + o.onCompleted(); + }); + }, source); + }; /** - * Represents a notification to an observer. + * 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. */ - 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; - })(); - + 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); + }; + /** - * 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. + * 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. */ - 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); - }; - }()); - + 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); + }; + /** - * 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. + * 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. */ - 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); - }; - }()); + 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); + }; + /** - * Creates an object that represents an OnCompleted notification to an observer. - * @returns {Notification} The OnCompleted notification. + * 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. */ - 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); - }; - }()); + 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); + }; /** - * 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. + * 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. */ - Observer.prototype.toNotifier = function () { - var observer = this; - return function (n) { return n.accept(observer); }; + 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); }; - + /** - * Hides the identity of an observer. - * @returns An observer that hides the identity of the specified observer. + * 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. */ - Observer.prototype.asObserver = function () { - return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); - }; + observableProto.transduce = function(transducer) { + var source = 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); }; + 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(); + } + }; + } - /** - * 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); + 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); }; - - /** - * 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. + + /* + * 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. */ - 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()); - }); - }; + observableProto.exclusive = function () { + var sources = this; + return new AnonymousObservable(function (observer) { + var hasCurrent = false, + isStopped = false, + m = new SingleAssignmentDisposable(), + g = new CompositeDisposable(); - /** - * 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); - }; + g.add(m); - Observer.prototype.makeSafe = function(disposable) { - return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); + 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); }; - /** - * Abstract base class for implementations of the Observer class. - * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. + /* + * 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. */ - var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { - inherits(AbstractObserver, __super__); + 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(); - /** - * Creates a new observer in a non-stopped state. - */ - function AbstractObserver() { - this.isStopped = false; - __super__.call(this); - } + g.add(m); - // Must be implemented by other observers - AbstractObserver.prototype.next = notImplemented; - AbstractObserver.prototype.error = notImplemented; - AbstractObserver.prototype.completed = notImplemented; + m.setDisposable(sources.subscribe( + function (innerSource) { - /** - * 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); } - }; + if (!hasCurrent) { + hasCurrent = true; - /** - * 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); - } - }; + innerSubscription = new SingleAssignmentDisposable(); + g.add(innerSubscription); - /** - * Notifies the observer of the end of the sequence. - */ - AbstractObserver.prototype.onCompleted = function () { - if (!this.isStopped) { - this.isStopped = true; - this.completed(); - } - }; + isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); - /** - * Disposes the observer, causing it to transition to the stopped state. - */ - AbstractObserver.prototype.dispose = function () { - this.isStopped = true; - }; + innerSubscription.setDisposable(innerSource.subscribe( + function (x) { + var result; + try { + result = selectorFunc(x, index++, innerSource); + } catch (e) { + observer.onError(e); + return; + } - AbstractObserver.prototype.fail = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.error(e); - return true; - } - - return false; - }; + observer.onNext(result); + }, + function (e) { observer.onError(e); }, + function () { + g.remove(innerSubscription); + hasCurrent = false; - return AbstractObserver; - }(Observer)); + 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); + }; - /** - * Class to create an Observer instance from delegate-based implementations of the on* methods. - */ - var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { - inherits(AnonymousObserver, __super__); + /** 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 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. + * 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 AnonymousObserver(onNext, onError, onCompleted) { - __super__.call(this); - this._onNext = onNext; - this._onError = onError; - this._onCompleted = onCompleted; + 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; + /** - * Calls the onNext action. - * @param {Any} value Next element in the sequence. + * 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. */ - AnonymousObserver.prototype.next = function (value) { - this._onNext(value); - }; + VirtualTimeSchedulerPrototype.add = notImplemented; /** - * Calls the onError action. - * @param {Any} error The error that has occurred. + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms */ - AnonymousObserver.prototype.error = function (error) { - this._onError(error); - }; + VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** - * Calls the onCompleted action. + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. */ - 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 - } + VirtualTimeSchedulerPrototype.toRelative = notImplemented; - var CheckedObserverPrototype = CheckedObserver.prototype; + /** + * 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(); + }; - CheckedObserverPrototype.onNext = function (value) { - this.checkAccess(); - var res = tryCatch(this._observer.onNext).call(this._observer, value); - this._state = 0; - res === errorObj && thrower(res.e); + /** + * 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); }; - CheckedObserverPrototype.onError = function (err) { - this.checkAccess(); - var res = tryCatch(this._observer.onError).call(this._observer, err); - this._state = 2; - res === errorObj && thrower(res.e); + /** + * 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); }; - CheckedObserverPrototype.onCompleted = function () { - this.checkAccess(); - var res = tryCatch(this._observer.onCompleted).call(this._observer); - this._state = 2; - res === errorObj && thrower(res.e); + /** + * 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); + } }; - 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; } + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; }; - return CheckedObserver; - }(Observer)); - - var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { - inherits(ScheduledObserver, __super__); + /** + * 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; + } + }; - 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(); - } + /** + * 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; } - ScheduledObserver.prototype.next = function (value) { - var self = this; - this.queue.push(function () { self.observer.onNext(value); }); + this.advanceTo(dt); }; - ScheduledObserver.prototype.error = function (e) { - var self = this; - this.queue.push(function () { self.observer.onError(e); }); + /** + * 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; }; - 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(); - })); + /** + * 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; }; - ScheduledObserver.prototype.dispose = function () { - __super__.prototype.dispose.call(this); - this.disposable.dispose(); + /** + * 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); }; - 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(); - }; + /** + * 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; - ObserveOnObserver.prototype.error = function (e) { - __super__.prototype.error.call(this, e); - this.ensureActive(); - }; + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } - ObserveOnObserver.prototype.completed = function () { - __super__.prototype.completed.call(this); - this.ensureActive(); - }; + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); - ObserveOnObserver.prototype.dispose = function () { - __super__.prototype.dispose.call(this); - this._cancel && this._cancel.dispose(); - this._cancel = null; + return si.disposable; }; - return ObserveOnObserver; - })(ScheduledObserver); + return VirtualTimeScheduler; + }(Scheduler)); - 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; + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); /** - * 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. + * 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. */ - observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { - return this._subscribe(typeof observerOrOnNext === 'object' ? - observerOrOnNext : - observerCreate(observerOrOnNext, onError, onCompleted)); - }; + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + + var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** - * 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. + * 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. */ - observableProto.subscribeOnNext = function (onNext, thisArg) { - return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; }; - /** - * 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)); + HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { + return new Date(absolute).getTime(); }; /** - * 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. + * 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. */ - observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { - return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); + HistoricalSchedulerProto.toRelative = function (timeSpan) { + return timeSpan; }; - return Observable; - })(); + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); - var ObservableBase = Rx.ObservableBase = (function (__super__) { - inherits(ObservableBase, __super__); + 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], self = state[1]; - var sub = tryCatch(self.subscribeCore).call(self, ado); + var ado = state[0], subscribe = state[1]; + var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } @@ -11590,9474 +12922,8175 @@ module.exports = function (string, locale) { ado.setDisposable(fixSubscriber(sub)); } - function subscribe(observer) { - var ado = new AutoDetachObserver(observer), state = [ado, this]; + function AnonymousObservable(subscribe, parent) { + this.source = parent; - if (currentThreadScheduler.scheduleRequired()) { - currentThreadScheduler.scheduleWithState(state, setDisposable); - } else { - setDisposable(null, state); + function s(observer) { + var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; + + if (currentThreadScheduler.scheduleRequired()) { + currentThreadScheduler.scheduleWithState(state, setDisposable); + } else { + setDisposable(null, state); + } + return ado; } - return ado; - } - function ObservableBase() { - __super__.call(this, subscribe); + __super__.call(this, s); } - ObservableBase.prototype.subscribeCore = notImplemented; + return AnonymousObservable; - return ObservableBase; }(Observable)); - var Enumerable = Rx.internals.Enumerable = function () { }; + var AutoDetachObserver = (function (__super__) { + inherits(AutoDetachObserver, __super__); - var ConcatEnumerableObservable = (function(__super__) { - inherits(ConcatEnumerableObservable, __super__); - function ConcatEnumerableObservable(sources) { - this.sources = sources; + function AutoDetachObserver(observer) { __super__.call(this); + this.observer = observer; + this.m = new SingleAssignmentDisposable(); } - - 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 AutoDetachObserverPrototype = AutoDetachObserver.prototype; - var d = new SingleAssignmentDisposable(); - subscription.setDisposable(d); - d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); - }); + AutoDetachObserverPrototype.next = function (value) { + var result = tryCatch(this.observer.onNext).call(this.observer, value); + if (result === errorObj) { + this.dispose(); + thrower(result.e); + } + }; - return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { - isDisposed = true; - })); + AutoDetachObserverPrototype.error = function (err) { + var result = tryCatch(this.observer.onError).call(this.observer, err); + this.dispose(); + result === errorObj && thrower(result.e); }; - - 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); - } + + AutoDetachObserverPrototype.completed = function () { + var result = tryCatch(this.observer.onCompleted).call(this.observer); + this.dispose(); + result === errorObj && thrower(result.e); }; - InnerObserver.prototype.onCompleted = function () { - if (!this.isStopped) { - this.isStopped = true; - this.s(this.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(); }; - InnerObserver.prototype.dispose = function () { this.isStopped = true; }; - InnerObserver.prototype.fail = function (err) { + + 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.isStopped = true; - this.o.onError(err); - return true; + this.observers.push(observer); + return new InnerSubscription(this, observer); } - return false; - }; - - return ConcatEnumerableObservable; - }(ObservableBase)); + if (this.hasError) { + observer.onError(this.error); + return disposableEmpty; + } + observer.onCompleted(); + return disposableEmpty; + } - Enumerable.prototype.concat = function () { - return new ConcatEnumerableObservable(this); - }; - - var CatchErrorObservable = (function(__super__) { - inherits(CatchErrorObservable, __super__); - function CatchErrorObservable(sources) { - this.sources = sources; - __super__.call(this); + inherits(Subject, __super__); + + /** + * Creates a subject. + */ + function Subject() { + __super__.call(this, subscribe); + this.isDisposed = false, + this.isStopped = false, + this.observers = []; + this.hasError = false; } - - 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); } + 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(); + } - if (currentItem.done) { - return lastException !== null ? o.onError(lastException) : o.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); + } - // Check if promise - var currentValue = currentItem.value; - isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + 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; + } + }); - 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; - })); + /** + * 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 CatchErrorObservable; - }(ObservableBase)); - Enumerable.prototype.catchError = function () { - return new CatchErrorObservable(this); - }; + 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__) { - 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); + function subscribe(observer) { + checkDisposed(this); - var e = sources[$iterator$](); + if (!this.isStopped) { + this.observers.push(observer); + return new InnerSubscription(this, observer); + } - 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 (this.hasError) { + observer.onError(this.error); + } else if (this.hasValue) { + observer.onNext(this.value); + observer.onCompleted(); + } else { + observer.onCompleted(); + } - if (currentItem.done) { - if (lastException) { - o.onError(lastException); - } else { - o.onCompleted(); - } - return; - } + return disposableEmpty; + } - // Check if promise - var currentValue = currentItem.value; - isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); + inherits(AsyncSubject, __super__); - 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() { + /** + * 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(); + } + } - exceptions.onNext(exn); - }, - function() { o.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; - return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { - isDisposed = true; - })); + 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; + } }); - }; - - 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; + + return AsyncSubject; + }(Observable)); + + var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { + inherits(AnonymousSubject, __super__); + + function subscribe(observer) { + return this.observable.subscribe(observer); } - 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; + function AnonymousSubject(observer, observable) { + this.observer = observer; + this.observable = observable; + __super__.call(this, subscribe); } - 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; + + 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); } - 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); - }; + /** + * 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)); - /** - * 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); - }; + 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; + } - /** - * 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. + // All code before this point will be filtered from stack traces. + var rEndingLine = captureLine(); + +}.call(this)); - * 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. +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":510}],72:[function(require,module,exports){ +'use strict'; - * @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); - } +var _core = require('@cycle/core'); - ToArrayObservable.prototype.subscribeCore = function(o) { - return this.source.subscribe(new InnerObserver(o)); - }; +var packageJson = require('package'); +var RxPackageJson = require('rx/package.json'); - 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; - }; +var DEFAULT_EXAMPLE = 'merge'; - return ToArrayObservable; - }(ObservableBase)); +module.exports = function appModel() { + var route$ = _core.Rx.Observable.fromEvent(window, 'hashchange').map(function (hashEvent) { + return hashEvent.target.location.hash.replace('#', ''); + }).startWith(window.location.hash.replace('#', '') || DEFAULT_EXAMPLE); + var appVersion$ = _core.Rx.Observable.just(packageJson.version); + var rxVersion$ = _core.Rx.Observable.just(RxPackageJson.version); + return _core.Rx.Observable.combineLatest(route$, appVersion$, rxVersion$, function (route, appVersion, rxVersion) { + return { route: route, appVersion: appVersion, rxVersion: rxVersion }; + }); +}; +},{"@cycle/core":80,"package":150,"rx/package.json":153}],73:[function(require,module,exports){ +'use strict'; - /** - * 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); - } +var _dom = require('@cycle/dom'); - EmptyObservable.prototype.subscribeCore = function (observer) { - var sink = new EmptySink(observer, this); - return sink.run(); - }; +var _colors = require('rxmarbles/styles/colors'); - function EmptySink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +var _colors2 = _interopRequireDefault(_colors); - function scheduleItem(s, state) { - state.onCompleted(); - } +var _dimens = require('rxmarbles/styles/dimens'); - EmptySink.prototype.run = function () { - return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); - }; +var _dimens2 = _interopRequireDefault(_dimens); - return EmptyObservable; - }(ObservableBase)); +var _fonts = require('rxmarbles/styles/fonts'); - /** - * 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); - } +var _fonts2 = _interopRequireDefault(_fonts); - FromObservable.prototype.subscribeCore = function (observer) { - var sink = new FromSink(observer, this); - return sink.run(); - }; +var _utils = require('rxmarbles/styles/utils'); - return FromObservable; - }(ObservableBase)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var FromSink = (function () { - function FromSink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +var rxmarblesGithubUrl = 'https://github.com/staltz/rxmarbles'; +var rxjsGithubUrl = 'https://github.com/Reactive-Extensions/RxJS'; - FromSink.prototype.run = function () { - var list = Object(this.parent.iterable), - it = getIterable(list), - observer = this.observer, - mapper = this.parent.mapper; +var pageRowWidth = '1060px'; +var sandboxWidth = '820px'; - function loopRecursive(i, recurse) { - try { - var next = it.next(); - } catch (e) { - return observer.onError(e); - } - if (next.done) { - return observer.onCompleted(); - } +var pageRowStyle = { + position: 'relative', + width: pageRowWidth, + margin: '0 auto' +}; - var result = next.value; +var pageRowChildStyle = { + display: 'inline-block' +}; - if (mapper) { - try { - result = mapper(result, i); - } catch (e) { - return observer.onError(e); - } - } +var pageRowFirstChildStyle = (0, _utils.mergeStyles)(pageRowChildStyle, { + width: 'calc(' + pageRowWidth + ' - ' + sandboxWidth + ' - ' + _dimens2.default.spaceMedium + ')' +}); - observer.onNext(result); - recurse(i + 1); - } - - return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); - }; +var pageRowLastChildStyle = (0, _utils.mergeStyles)(pageRowChildStyle, { + width: sandboxWidth +}); - return FromSink; - }()); +function renderHeader() { + return (0, _dom.h)('div', { style: pageRowStyle }, [(0, _dom.h)('h1', { style: (0, _utils.mergeStyles)({ + fontFamily: _fonts2.default.fontSpecial, + color: _colors2.default.greyDark }, pageRowFirstChildStyle) }, 'RxMarbles'), (0, _dom.h)('h3', { style: (0, _utils.mergeStyles)({ + color: _colors2.default.greyDark }, pageRowLastChildStyle) }, 'Interactive diagrams of Rx Observables')]); +} - var maxSafeInteger = Math.pow(2, 53) - 1; +function renderContent(route) { + var style = (0, _utils.mergeStyles)(pageRowStyle, { marginTop: _dimens2.default.spaceSmall }); + return (0, _dom.h)('div', { style: style }, [(0, _dom.h)('div', { style: pageRowFirstChildStyle }, (0, _dom.h)('x-operators-menu', { key: 'operatorsMenu' })), (0, _dom.h)('div', { style: (0, _utils.mergeStyles)({ + position: 'absolute', + top: '0' }, pageRowLastChildStyle) }, (0, _dom.h)('x-sandbox', { key: 'sandbox', route: route, width: '820px', showSubscriptions: true }))]); +} - function StringIterable(str) { - this._s = s; - } +function renderFooter(appVersion, rxVersion) { + var style = { + position: 'fixed', + bottom: '2px', + right: _dimens2.default.spaceMedium, + color: _colors2.default.greyDark + }; + return (0, _dom.h)('section', { style: style }, [(0, _dom.h)('a', { href: rxmarblesGithubUrl + '/releases/tag/v' + appVersion }, 'v' + appVersion), ' built on ', (0, _dom.h)('a', { href: rxjsGithubUrl + '/tree/v' + rxVersion }, 'RxJS v' + rxVersion), ' by ', (0, _dom.h)('a', { href: 'https://twitter.com/andrestaltz' }, '@andrestaltz')]); +} - StringIterable.prototype[$iterator$] = function () { - return new StringIterator(this._s); +module.exports = function appView(state$) { + var wrapperStyle = { + paddingLeft: _dimens2.default.spaceSmall, + paddingRight: 'calc(' + _dimens2.default.spaceHuge + ' + ' + _dimens2.default.spaceSmall + ')' }; + return state$.map(function (_ref) { + var route = _ref.route; + var appVersion = _ref.appVersion; + var rxVersion = _ref.rxVersion; + return (0, _dom.h)('div', { style: wrapperStyle }, [(0, _utils.renderSvgDropshadow)(), renderHeader(), renderContent(route), renderFooter(appVersion, rxVersion)]); + }); +}; +},{"@cycle/dom":83,"rxmarbles/styles/colors":410,"rxmarbles/styles/dimens":411,"rxmarbles/styles/fonts":412,"rxmarbles/styles/utils":413}],74:[function(require,module,exports){ +'use strict'; - function StringIterator(str) { - this._s = s; - this._l = s.length; - this._i = 0; - } +var _core = require('@cycle/core'); - StringIterator.prototype[$iterator$] = function () { - return this; - }; +var _dom = require('@cycle/dom'); - StringIterator.prototype.next = function () { - return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; +var _utils = 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 ArrayIterable(a) { - this._a = a; - } +function createInnerStyle(inputStyle) { + return { + width: inputStyle.thickness, + height: '50%', + marginLeft: 'calc(3.5 * ' + inputStyle.thickness + ')', + marginTop: 'calc(' + inputStyle.height + ' / 4.0)', + backgroundColor: inputStyle.color + }; +} - ArrayIterable.prototype[$iterator$] = function () { - return new ArrayIterator(this._a); +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, _dom.h)('div.completionRoot', { + style: (0, _utils.mergeStyles)({ + left: time + '%' }, containerStyle, isDraggable ? draggableContainerStyle : {}) + }, [(0, _dom.h)('div.completionInner', { + style: (0, _utils.mergeStyles)(innerStyle, isDraggable && isHighlighted ? _utils.elevation1Style : null, isTall ? innerTallStyle : null) + })]); +} - function ArrayIterator(a) { - this._a = a; - this._l = toLength(a); - this._i = 0; - } +function diagramCompletionComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; - ArrayIterator.prototype[$iterator$] = function () { - return this; - }; + 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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _core.Rx.Observable.combineLatest(time$, isDraggable$, isTall$, style$, isHighlighted$, render); - ArrayIterator.prototype.next = function () { - return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; + return { + DOM: vtree$ }; +} - function numberIsFinite(value) { - return typeof value === 'number' && root.isFinite(value); - } +module.exports = diagramCompletionComponent; +},{"@cycle/core":80,"@cycle/dom":83,"rxmarbles/styles/utils":413}],75:[function(require,module,exports){ +'use strict'; - function isNan(n) { - return n !== n; - } +var _diagramModel = require('rxmarbles/components/diagram/diagram-model'); - 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$](); - } +var _diagramModel2 = _interopRequireDefault(_diagramModel); - function sign(value) { - var number = +value; - if (number === 0) { return number; } - if (isNaN(number)) { return number; } - return number < 0 ? -1 : 1; - } +var _diagramView = require('rxmarbles/components/diagram/diagram-view'); - 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; - } +var _diagramView2 = _interopRequireDefault(_diagramView); - /** - * 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); - } +var _diagramIntent = require('rxmarbles/components/diagram/diagram-intent'); - FromArrayObservable.prototype.subscribeCore = function (observer) { - var sink = new FromArraySink(observer, this); - return sink.run(); - }; +var _diagramIntent2 = _interopRequireDefault(_diagramIntent); - return FromArrayObservable; - }(ObservableBase)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function FromArraySink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +function DiagramComponent(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; - 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(); - } - } + var intent = (0, _diagramIntent2.default)(DOM); + var model = (0, _diagramModel2.default)(props, intent); + var view = (0, _diagramView2.default)(model); - 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) + return { + DOM: view.vtree$, + events: { + newdata: model.newData$ + } }; - - /** - * 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); - }; +module.exports = DiagramComponent; +},{"rxmarbles/components/diagram/diagram-intent":154,"rxmarbles/components/diagram/diagram-model":155,"rxmarbles/components/diagram/diagram-view":156}],76:[function(require,module,exports){ +'use strict'; - /** - * 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); +var _core = require('@cycle/core'); - 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]); - } - } +var _dom = require('@cycle/dom'); - Object.observe(obj, observerFn); +var _colors = require('rxmarbles/styles/colors'); - return function () { - Object.unobserve(obj, observerFn); - }; - }); - }; - - var NeverObservable = (function(__super__) { - inherits(NeverObservable, __super__); - function NeverObservable() { - __super__.call(this); - } +var _colors2 = _interopRequireDefault(_colors); - NeverObservable.prototype.subscribeCore = function (observer) { - return disposableEmpty; - }; +var _utils = require('rxmarbles/styles/utils'); - return NeverObservable; - }(ObservableBase)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - /** - * 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(); +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' }; - - 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(); - }; +function renderSvg(data, isDraggable, inputStyle, isHighlighted, isGhost) { + var POSSIBLE_COLORS = [_colors2.default.blue, _colors2.default.green, _colors2.default.yellow, _colors2.default.red]; + var color = isGhost ? _colors2.default.almostWhite : POSSIBLE_COLORS[data.get('id') % POSSIBLE_COLORS.length]; + return (0, _dom.svg)('svg.marbleShape', { + style: { + overflow: 'visible', + width: inputStyle.size, + height: inputStyle.size + }, + attributes: { viewBox: '0 0 1 1' } }, [(0, _dom.svg)('circle', { + style: (0, _utils.mergeStyles)({ + stroke: isGhost ? _colors2.default.greyLight : _colors2.default.black, + fill: color + }, isDraggable && isHighlighted ? _utils.marbleElevation1Style : {}), + attributes: { + cx: 0.5, cy: 0.5, r: 0.47, + 'stroke-width': '0.06px' + } + })]); +} - return PairsObservable; - }(ObservableBase)); +function renderInnerContent(data, inputStyle, isGhost) { + var style = { + position: 'absolute', + width: '100%', + height: '100%', + top: '0', + margin: '0', + textAlign: 'center', + lineHeight: inputStyle.size + }; - function PairsSink(observer, parent) { - this.observer = observer; - this.parent = parent; + if (isGhost) { + style['color'] = _colors2.default.greyLight; } - 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 (0, _dom.h)('p.marbleContent', { + style: (0, _utils.mergeStyles)(style, _utils.textUnselectable) + }, '' + data.get('content')); +} - return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); +function render(data, isDraggable, inputStyle, isHighlighted, isGhost) { + var draggableContainerStyle = { + cursor: 'ew-resize' }; + return (0, _dom.h)('div.marbleRoot', { + style: (0, _utils.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, isGhost), renderInnerContent(data, inputStyle, isGhost)]); +} - /** - * 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); +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 isGhost$ = props.get('isGhost').startWith(false); + var style$ = props.get('style').startWith({}); + var isHighlighted$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var vtree$ = _core.Rx.Observable.combineLatest(data$, isDraggable$, style$, isHighlighted$, isGhost$, render); + + return { + DOM: vtree$ }; - - 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(); - }; +module.exports = marbleComponent; +},{"@cycle/core":80,"@cycle/dom":83,"rxmarbles/styles/colors":410,"rxmarbles/styles/utils":413}],77:[function(require,module,exports){ +'use strict'; - return RangeObservable; - }(ObservableBase)); +var _core = require('@cycle/core'); - var RangeSink = (function () { - function RangeSink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +var _dom = require('@cycle/dom'); - 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(); - } - } +var _colors = require('rxmarbles/styles/colors'); - return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); - }; +var _colors2 = _interopRequireDefault(_colors); - return RangeSink; - }()); +var _dimens = require('rxmarbles/styles/dimens'); - /** - * 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); - } +var _dimens2 = _interopRequireDefault(_dimens); - RepeatObservable.prototype.subscribeCore = function (observer) { - var sink = new RepeatSink(observer, this); - return sink.run(); - }; +var _utils = require('rxmarbles/styles/utils'); - return RepeatObservable; - }(ObservableBase)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function RepeatSink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +function operatorsMenuLink(_ref) { + var DOM = _ref.DOM; + var props = _ref.props; - 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); - } + 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$ = _core.Rx.Observable.merge(startHighlight$.map(function () { + return true; + }), stopHighlight$.map(function () { + return false; + })).startWith(false); + var highlightingArrow = (0, _dom.h)('span', { + style: { + display: 'inline-block', + position: 'absolute', + right: _dimens2.default.spaceTiny } + }, '❯'); + var vtree$ = _core.Rx.Observable.combineLatest(href$, content$, isHighlighted$, function (href, content, isHighlighted) { + return (0, _dom.h)('a.link', { + style: (0, _utils.mergeStyles)({ + position: 'relative', + display: 'block', + color: _colors2.default.greyDark }, isHighlighted ? { color: _colors2.default.black } : null), + href: href }, [content, isHighlighted ? highlightingArrow : null]); + }); - return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); - }; + return { DOM: vtree$ }; +} - /** - * 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); - } +module.exports = operatorsMenuLink; +},{"@cycle/core":80,"@cycle/dom":83,"rxmarbles/styles/colors":410,"rxmarbles/styles/dimens":411,"rxmarbles/styles/utils":413}],78:[function(require,module,exports){ +'use strict'; - JustObservable.prototype.subscribeCore = function (observer) { - var sink = new JustSink(observer, this); - return sink.run(); - }; +var _core = require('@cycle/core'); - function JustSink(observer, parent) { - this.observer = observer; - this.parent = parent; - } +var _dom = require('@cycle/dom'); - function scheduleItem(s, state) { - var value = state[0], observer = state[1]; - observer.onNext(value); - observer.onCompleted(); - } +var _colors = require('rxmarbles/styles/colors'); - JustSink.prototype.run = function () { - return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); - }; +var _colors2 = _interopRequireDefault(_colors); - return JustObservable; - }(ObservableBase)); +var _dimens = require('rxmarbles/styles/dimens'); - /** - * 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 = 45 ? 1.3 : label.length >= 30 ? 1.5 : 2; + if (small) { + fontSize *= 0.5; + } + var style = { + fontFamily: _fonts2.default.fontCode, + fontWeight: '400', + fontSize: fontSize + 'rem' }; - - /** - * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. - * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. - */ - observableProto.concat = function () { - for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } - args.unshift(this); - return observableConcat.apply(null, args); - }; - - var ConcatObservable = (function(__super__) { - inherits(ConcatObservable, __super__); - function ConcatObservable(sources) { - this.sources = sources; - __super__.call(this); - } - - ConcatObservable.prototype.subscribeCore = function(o) { - var sink = new ConcatSink(this.sources, o); - return sink.run(); - }; - - function ConcatSink(sources, o) { - this.sources = sources; - this.o = o; - } - ConcatSink.prototype.run = function () { - var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; - var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { - if (isDisposed) { return; } - if (i === length) { - return o.onCompleted(); - } - - // Check if promise - var currentValue = sources[i]; - isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); - - var d = new SingleAssignmentDisposable(); - subscription.setDisposable(d); - d.setDisposable(currentValue.subscribe( - function (x) { o.onNext(x); }, - function (e) { o.onError(e); }, - function () { self(i + 1); } - )); - }); - - return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { - isDisposed = true; - })); - }; - - - return ConcatObservable; - }(ObservableBase)); - - /** - * Concatenates all the observable sequences. - * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. - * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. - */ - var observableConcat = Observable.concat = function () { - var args; - if (Array.isArray(arguments[0])) { - args = arguments[0]; - } else { - args = new Array(arguments.length); - for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } - } - return new ConcatObservable(args); - }; - - /** - * Concatenates an observable sequence of observable sequences. - * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. - */ - observableProto.concatAll = observableProto.concatObservable = function () { - return this.merge(1); - }; - - var MergeObservable = (function (__super__) { - inherits(MergeObservable, __super__); + return (0, _dom.h)('span.operatorLabel', { style: style }, label); +} - function MergeObservable(source, maxConcurrent) { - this.source = source; - this.maxConcurrent = maxConcurrent; - __super__.call(this); - } +function renderOperator(label) { + var small = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; - MergeObservable.prototype.subscribeCore = function(observer) { - var g = new CompositeDisposable(); - g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); - return g; - }; + var style = (0, _utils.mergeStyles)({ + border: '1px solid rgba(0,0,0,0.06)', + padding: small ? _dimens2.default.spaceTiny : _dimens2.default.spaceMedium, + textAlign: 'center' }, _utils.elevation2Style); + return (0, _dom.h)('div.operatorBox', { style: style }, [_utils.elevation2Before, renderOperatorLabel(label, small), _utils.elevation2After]); +} - return MergeObservable; +function renderObservedInputs(inputs) { + return inputs.map(function (input, i) { + return (0, _dom.h)('x-diagram.sandboxObservedInput', { + key: "observedInput" + i, + data: input, + interactive: false, + compact: true + }); + }); +} - }(ObservableBase)); +function getSandboxStyle(width) { + return (0, _utils.mergeStyles)({ + background: _colors2.default.white, + width: width, + borderRadius: '2px' }, _utils.elevation1Style); +} - var MergeObserver = (function () { - function MergeObserver(o, max, g) { - this.o = o; - this.max = max; - this.g = g; - this.done = false; - this.q = []; - this.activeCount = 0; - this.isStopped = false; - } - MergeObserver.prototype.handleSubscribe = function (xs) { - var sad = new SingleAssignmentDisposable(); - this.g.add(sad); - isPromise(xs) && (xs = observableFromPromise(xs)); - sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); - }; - MergeObserver.prototype.onNext = function (innerSource) { - if (this.isStopped) { return; } - if(this.activeCount < this.max) { - this.activeCount++; - this.handleSubscribe(innerSource); - } else { - this.q.push(innerSource); - } - }; - MergeObserver.prototype.onError = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.o.onError(e); - } - }; - MergeObserver.prototype.onCompleted = function () { - if (!this.isStopped) { - this.isStopped = true; - this.done = true; - this.activeCount === 0 && this.o.onCompleted(); - } - }; - MergeObserver.prototype.dispose = function() { this.isStopped = true; }; - MergeObserver.prototype.fail = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.o.onError(e); - return true; - } +function renderSandbox(inputDiagrams, operatorLabel, outputDiagramData, width, showSubscriptions) { + var children = [inputDiagrams.get('diagrams').map(function (diagram, index) { + return (0, _dom.h)('x-diagram.sandboxInputDiagram', { + key: 'inputDiagram' + index, + data: diagram, + interactive: true + }); + }), renderOperator(operatorLabel), (0, _dom.h)('x-diagram.sandboxOutputDiagram', { + key: 'outputDiagram', + data: outputDiagramData.outputDiagram, + interactive: false + })]; - return false; - }; + if (showSubscriptions) { + children.push(renderOperator("subscription details", true), renderObservedInputs(outputDiagramData.observedInputDiagrams)); + } - function InnerObserver(parent, sad) { - this.parent = parent; - 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) { - this.isStopped = true; - var parent = this.parent; - parent.g.remove(this.sad); - if (parent.q.length > 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 (0, _dom.h)('div.sandboxRoot', { style: getSandboxStyle(width) }, children); +} - return false; - }; +function makeInputDiagrams(example) { + return _immutable2.default.Map({ + 'diagrams': example.get('inputs').map(_sandboxInput.prepareInputDiagram).map(function (diag) { + return (0, _sandboxInput.augmentWithExampleKey)(diag, example.get('key')); + }) + }); +} - return MergeObserver; - }()); +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 showSubscriptions$ = props.get('showSubscriptions').startWith(true); + var example$ = props.get('route').filter(isTruthy).map(function (key) { + return _immutable2.default.Map(_examples2.default[key]).set('key', key); + }).shareReplay(1); + var inputDiagrams$ = example$.map(makeInputDiagrams).map(markAllDiagramsAsFirst).shareReplay(1); + var newInputDiagrams$ = (0, _sandboxInput.makeNewInputDiagramsData$)(changeInputDiagram$, inputDiagrams$); + var operatorLabel$ = example$.map(function (example) { + return example.get('label'); + }); + var firstOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, inputDiagrams$).map(function (d) { + return { + outputDiagram: markAsFirstDiagram(d.outputDiagram), + observedInputDiagrams: d.observedInputDiagrams.map(markAsFirstDiagram) + }; + }); + var newOutputDiagram$ = (0, _sandboxOutput.getOutputDiagram$)(example$, newInputDiagrams$); + var outputDiagram$ = firstOutputDiagram$.merge(newOutputDiagram$); + var vtree$ = _core.Rx.Observable.combineLatest(inputDiagrams$, operatorLabel$, outputDiagram$, width$, showSubscriptions$, renderSandbox); - /** - * 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); + return { + DOM: vtree$ }; - - /** - * 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]; +} + +module.exports = sandboxComponent; +},{"@cycle/core":80,"@cycle/dom":83,"immutable":145,"rxmarbles/components/sandbox/sandbox-input":157,"rxmarbles/components/sandbox/sandbox-output":158,"rxmarbles/data/examples":159,"rxmarbles/styles/colors":410,"rxmarbles/styles/dimens":411,"rxmarbles/styles/fonts":412,"rxmarbles/styles/utils":413,"rxtween":422}],80:[function(require,module,exports){ +arguments[4][1][0].apply(exports,arguments) +},{"dup":1,"rx":152}],81:[function(require,module,exports){ +arguments[4][2][0].apply(exports,arguments) +},{"./render-dom":84,"@cycle/core":80,"dup":2}],82:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"./custom-element-widget":81,"dup":3,"es6-map":132}],83:[function(require,module,exports){ +arguments[4][4][0].apply(exports,arguments) +},{"./render-dom":84,"./render-html":85,"dup":4,"virtual-dom":437,"virtual-dom/virtual-hyperscript/svg":451}],84:[function(require,module,exports){ +arguments[4][5][0].apply(exports,arguments) +},{"./custom-elements":82,"@cycle/core":80,"dup":5,"vdom-parser":427,"virtual-dom":437,"virtual-dom/diff":435,"virtual-dom/patch":438}],85:[function(require,module,exports){ +arguments[4][6][0].apply(exports,arguments) +},{"./custom-element-widget":81,"./custom-elements":82,"@cycle/core":80,"dup":6,"vdom-to-html":431}],86:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],87:[function(require,module,exports){ +arguments[4][8][0].apply(exports,arguments) +},{"dup":8,"es5-ext/object/copy":100,"es5-ext/object/map":108,"es5-ext/object/valid-callable":114,"es5-ext/object/valid-value":115}],88:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"dup":9,"es5-ext/object/assign":97,"es5-ext/object/is-callable":103,"es5-ext/object/normalize-options":109,"es5-ext/string/#/contains":116}],89:[function(require,module,exports){ +arguments[4][10][0].apply(exports,arguments) +},{"../../object/valid-value":115,"dup":10}],90:[function(require,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"../../number/to-pos-integer":95,"../../object/valid-value":115,"dup":11}],91:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"./is-implemented":92,"./shim":93,"dup":12}],92:[function(require,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"dup":13}],93:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"dup":14}],94:[function(require,module,exports){ +arguments[4][15][0].apply(exports,arguments) +},{"../math/sign":91,"dup":15}],95:[function(require,module,exports){ +arguments[4][16][0].apply(exports,arguments) +},{"./to-integer":94,"dup":16}],96:[function(require,module,exports){ +arguments[4][17][0].apply(exports,arguments) +},{"./valid-callable":114,"./valid-value":115,"dup":17}],97:[function(require,module,exports){ +arguments[4][18][0].apply(exports,arguments) +},{"./is-implemented":98,"./shim":99,"dup":18}],98:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],99:[function(require,module,exports){ +arguments[4][20][0].apply(exports,arguments) +},{"../keys":105,"../valid-value":115,"dup":20}],100:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"./assign":97,"./valid-value":115,"dup":21}],101:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"./set-prototype-of/is-implemented":112,"./set-prototype-of/shim":113,"dup":22}],102:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"./_iterate":96,"dup":23}],103:[function(require,module,exports){ +arguments[4][24][0].apply(exports,arguments) +},{"dup":24}],104:[function(require,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"dup":25}],105:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"./is-implemented":106,"./shim":107,"dup":26}],106:[function(require,module,exports){ +arguments[4][27][0].apply(exports,arguments) +},{"dup":27}],107:[function(require,module,exports){ +arguments[4][28][0].apply(exports,arguments) +},{"dup":28}],108:[function(require,module,exports){ +arguments[4][29][0].apply(exports,arguments) +},{"./for-each":102,"./valid-callable":114,"dup":29}],109:[function(require,module,exports){ +arguments[4][30][0].apply(exports,arguments) +},{"dup":30}],110:[function(require,module,exports){ +arguments[4][31][0].apply(exports,arguments) +},{"dup":31}],111:[function(require,module,exports){ +arguments[4][32][0].apply(exports,arguments) +},{"./is-implemented":112,"./shim":113,"dup":32}],112:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],113:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"../create":101,"../is-object":104,"../valid-value":115,"dup":34}],114:[function(require,module,exports){ +arguments[4][35][0].apply(exports,arguments) +},{"dup":35}],115:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],116:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"./is-implemented":117,"./shim":118,"dup":37}],117:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"dup":38}],118:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"dup":39}],119:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"dup":40}],120:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"./":123,"d":88,"dup":41,"es5-ext/object/set-prototype-of":111,"es5-ext/string/#/contains":116}],121:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"./get":122,"dup":42,"es5-ext/object/valid-callable":114,"es5-ext/string/is-string":119}],122:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./array":120,"./string":130,"./valid-iterable":131,"dup":43,"es5-ext/string/is-string":119,"es6-symbol":125}],123:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"d":88,"d/auto-bind":87,"dup":44,"es5-ext/array/#/clear":89,"es5-ext/object/assign":97,"es5-ext/object/valid-callable":114,"es5-ext/object/valid-value":115,"es6-symbol":125}],124:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"dup":45,"es5-ext/string/is-string":119,"es6-symbol":125}],125:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":126,"./polyfill":128,"dup":46}],126:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"dup":47}],127:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"dup":48}],128:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"./validate-symbol":129,"d":88,"dup":49}],129:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./is-symbol":127,"dup":50}],130:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"./":123,"d":88,"dup":51,"es5-ext/object/set-prototype-of":111}],131:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"./is-iterable":124,"dup":52}],132:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"./is-implemented":133,"./polyfill":137,"dup":53}],133:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54}],134:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],135:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56,"es5-ext/object/primitive-set":110}],136:[function(require,module,exports){ +arguments[4][57][0].apply(exports,arguments) +},{"./iterator-kinds":135,"d":88,"dup":57,"es5-ext/object/set-prototype-of":111,"es6-iterator":123,"es6-symbol":138}],137:[function(require,module,exports){ +arguments[4][58][0].apply(exports,arguments) +},{"./is-native-implemented":134,"./lib/iterator":136,"d":88,"dup":58,"es5-ext/array/#/clear":89,"es5-ext/array/#/e-index-of":90,"es5-ext/object/set-prototype-of":111,"es5-ext/object/valid-callable":114,"es5-ext/object/valid-value":115,"es6-iterator/for-of":121,"es6-iterator/valid-iterable":131,"es6-symbol":138,"event-emitter":143}],138:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":139,"./polyfill":140,"dup":46}],139:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],140:[function(require,module,exports){ +arguments[4][61][0].apply(exports,arguments) +},{"d":88,"dup":61}],141:[function(require,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"dup":62}],142:[function(require,module,exports){ +arguments[4][63][0].apply(exports,arguments) +},{"dup":63,"individual/one-version":147}],143:[function(require,module,exports){ +arguments[4][64][0].apply(exports,arguments) +},{"d":88,"dup":64,"es5-ext/object/valid-callable":114}],144:[function(require,module,exports){ +arguments[4][65][0].apply(exports,arguments) +},{"dup":65,"min-document":509}],145:[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); } - return observableOf(scheduler, sources).mergeAll(); - }; - - var MergeAllObservable = (function (__super__) { - inherits(MergeAllObservable, __super__); + ctor.prototype.constructor = ctor; + } - function MergeAllObservable(source) { - this.source = source; - __super__.call(this); + function Iterable(value) { + return isIterable(value) ? value : Seq(value); } - 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; + + createClass(KeyedIterable, Iterable); + function KeyedIterable(value) { + return isKeyed(value) ? value : KeyedSeq(value); } - 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; - } + createClass(IndexedIterable, Iterable); + function IndexedIterable(value) { + return isIndexed(value) ? value : IndexedSeq(value); + } - return false; - }; - function InnerObserver(parent, g, sad) { - this.parent = parent; - this.g = g; - this.sad = sad; - this.isStopped = false; + createClass(SetIterable, Iterable); + function SetIterable(value) { + return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } - 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); + function isIterable(maybeIterable) { + return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } - 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); + function isKeyed(maybeKeyed) { + return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); + } - return new AnonymousObservable(function (o) { - var group = new CompositeDisposable(), - m = new SingleAssignmentDisposable(), - isStopped = false, - errors = []; + function isIndexed(maybeIndexed) { + return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); + } - function setCompletion() { - if (errors.length === 0) { - o.onCompleted(); - } else if (errors.length === 1) { - o.onError(errors[0]); - } else { - o.onError(new CompositeError(errors)); - } - } + function isAssociative(maybeAssociative) { + return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); + } - group.add(m); + function isOrdered(maybeOrdered) { + return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); + } - m.setDisposable(source.subscribe( - function (innerSource) { - var innerSubscription = new SingleAssignmentDisposable(); - group.add(innerSubscription); + Iterable.isIterable = isIterable; + Iterable.isKeyed = isKeyed; + Iterable.isIndexed = isIndexed; + Iterable.isAssociative = isAssociative; + Iterable.isOrdered = isOrdered; - // Check for promises support - isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + Iterable.Keyed = KeyedIterable; + Iterable.Indexed = IndexedIterable; + Iterable.Set = SetIterable; - 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 IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; - var rightSubscription = new SingleAssignmentDisposable(); - disposables.add(rightSubscription); - rightSubscription.setDisposable(other.subscribe(function () { - isOpen = true; - rightSubscription.dispose(); - }, function (e) { o.onError(e); }, function () { - rightSubscription.dispose(); - })); + // Used for setting prototype methods that IE8 chokes on. + var DELETE = 'delete'; - return disposables; - }, source); - }; - - var SwitchObservable = (function(__super__) { - inherits(SwitchObservable, __super__); - function SwitchObservable(source) { - this.source = source; - __super__.call(this); - } + // Constants describing the size of trie nodes. + var SHIFT = 5; // Resulted in best performance after ______? + var SIZE = 1 << SHIFT; + var MASK = SIZE - 1; - SwitchObservable.prototype.subscribeCore = function (o) { - var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); - return new CompositeDisposable(s, inner); - }; + // A consistent shared value representing "not set" which equals nothing other + // than itself, and nothing that could be provided externally. + var NOT_SET = {}; - 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; - }; + // Boolean references, Rough equivalent of `bool &`. + var CHANGE_LENGTH = { value: false }; + var DID_ALTER = { value: 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; - }; + function MakeRef(ref) { + ref.value = false; + return ref; + } - return SwitchObservable; - }(ObservableBase)); + function SetRef(ref) { + ref && (ref.value = true); + } - /** - * 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__); + // 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() {} - function TakeUntilObservable(source, other) { - this.source = source; - this.other = isPromise(other) ? observableFromPromise(other) : other; - __super__.call(this); + // 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; + } - 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; + function ensureSize(iter) { + if (iter.size === undefined) { + iter.size = iter.__iterate(returnTrue); } - 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 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; } - return false; - }; + index = uint32Index; + } + return index < 0 ? ensureSize(iter) + index : index; + } - return TakeUntilObservable; - }(ObservableBase)); + function returnTrue() { + return true; + } - /** - * 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; } + function wholeSlice(begin, end, size) { + return (begin === 0 || (size !== undefined && begin <= -size)) && + (end === undefined || (size !== undefined && end >= size)); + } - /** - * 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]); + function resolveBegin(begin, size) { + return resolveIndex(begin, size, 0); + } - return new AnonymousObservable(function (observer) { - var n = args.length, - hasValue = arrayInitialize(n, falseFactory), - hasValueAll = false, - values = new Array(n); + function resolveEnd(end, size) { + return resolveIndex(end, size, size); + } - 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)); - } + function resolveIndex(index, size, defaultIndex) { + return index === undefined ? + defaultIndex : + index < 0 ? + Math.max(0, size + index) : + size === undefined ? + index : + Math.min(size, index); + } - 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; + /* global Symbol */ - return new CompositeDisposable(subscriptions); - }, this); + 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 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 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 falseFactory() { return false; } - function emptyArrayFactory() { return []; } + function iteratorDone() { + return { value: undefined, done: true }; + } - /** - * 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]; } + function hasIterator(maybeIterable) { + return !!getIteratorFn(maybeIterable); + } - 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); + function isIterator(maybeIterator) { + return maybeIterator && typeof maybeIterator.next === 'function'; + } - 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); - } + function getIterator(iterable) { + var iteratorFn = getIteratorFn(iterable); + return iteratorFn && iteratorFn.call(iterable); + } - 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 []; } + function getIteratorFn(iterable) { + var iteratorFn = iterable && ( + (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || + iterable[FAUX_ITERATOR_SYMBOL] + ); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } - /** - * 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]; } + 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); } - 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); + 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; + }; - 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); - } + // abstract __iterateUncached(fn, reverse) - TapObservable.prototype.subscribeCore = function(o) { - return this.source.subscribe(new InnerObserver(o, this.t)); + Seq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, true); }; - 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; + // abstract __iteratorUncached(type, reverse) + + Seq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, true); }; - 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); - }; + createClass(KeyedSeq, Seq); + function KeyedSeq(value) { + return value === null || value === undefined ? + emptySequence().toKeyedSeq() : + isIterable(value) ? + (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : + keyedSeqFromValue(value); + } - /** - * 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); - }; + KeyedSeq.prototype.toKeyedSeq = function() { + return this; + }; - /** - * 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); + createClass(IndexedSeq, Seq); + function IndexedSeq(value) { + return value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } - IgnoreElementsObservable.prototype.subscribeCore = function (o) { - return this.source.subscribe(new InnerObserver(o)); + IndexedSeq.of = function(/*...values*/) { + return IndexedSeq(arguments); }; - 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); - } + IndexedSeq.prototype.toIndexedSeq = function() { + return this; }; - InnerObserver.prototype.onCompleted = function () { - if(!this.isStopped) { - this.isStopped = true; - this.o.onCompleted(); - } + + IndexedSeq.prototype.toString = function() { + return this.__toString('Seq [', ']'); }; - 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; + IndexedSeq.prototype.__iterate = function(fn, reverse) { + return seqIterate(this, fn, reverse, false); }; - return IgnoreElementsObservable; - }(ObservableBase)); + IndexedSeq.prototype.__iterator = function(type, reverse) { + return seqIterator(this, type, reverse, false); + }; - /** - * 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); + + + createClass(SetSeq, Seq); + function SetSeq(value) { + return ( + value === null || value === undefined ? emptySequence() : + !isIterable(value) ? indexedSeqFromValue(value) : + isKeyed(value) ? value.entrySeq() : value + ).toSetSeq(); } - ScanObservable.prototype.subscribeCore = function(observer) { - return this.source.subscribe(new ScanObserver(observer,this)); + SetSeq.of = function(/*...values*/) { + return SetSeq(arguments); }; - return ScanObservable; - }(ObservableBase)); + SetSeq.prototype.toSetSeq = function() { + return this; + }; - 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(); + + + 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; } - }; - ScanObserver.prototype.dispose = function() { this.isStopped = true; }; - ScanObserver.prototype.fail = function (e) { - if (!this.isStopped) { - this.isStopped = true; - this.observer.onError(e); - return true; + + 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; } - 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]; + 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; } - 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 = []; + 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; + }; - function createWindow () { - var s = new Subject(); - q.push(s); - observer.onNext(addRef(s, refCountDisposable)); + 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); + }); + }; - 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(); + + 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; } - )); - 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(); + } + 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]); } - /** - * 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)); + var EMPTY_SEQ; - 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; } + 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 -1; + return seq; } - function HashSet(comparer) { - this.comparer = comparer; - this.set = []; + function indexedSeqFromValue(value) { + var seq = maybeIndexedSeqFromValue(value); + if (!seq) { + throw new TypeError( + 'Expected Array or iterable object of values: ' + value + ); + } + return seq; } - 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; + 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; + } - if (keySelector) { - try { - key = keySelector(x); - } catch (e) { - o.onError(e); - return; - } + 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; } - 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); + } + return ii; + } + return seq.__iterateUncached(fn, reverse); + } - groupDisposable.add(source.subscribe(function (x) { - var key; - try { - key = keySelector(x); - } catch (e) { - map.getValues().forEach(handleError(e)); - observer.onError(e); - return; - } + 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); + } - var fireNewMapEntry = false, - writer = map.tryGetValue(key); - if (!writer) { - writer = new Subject(); - map.set(key, writer); - fireNewMapEntry = true; - } + function fromJS(json, converter) { + return converter ? + fromJSWith(converter, json, '', {'': json}) : + fromJSDefault(json); + } - 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; - } + 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; + } - observer.onNext(group); + function fromJSDefault(json) { + if (Array.isArray(json)) { + return IndexedSeq(json).map(fromJSDefault).toList(); + } + if (isPlainObj(json)) { + return KeyedSeq(json).map(fromJSDefault).toMap(); + } + return json; + } - var md = new SingleAssignmentDisposable(); - groupDisposable.add(md); + function isPlainObj(value) { + return value && (value.constructor === Object || value.constructor === undefined); + } - var expire = function () { - map.remove(key) && writer.onCompleted(); - groupDisposable.remove(md); - }; + /** + * 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; + } - md.setDisposable(duration.take(1).subscribe( - noop, - function (exn) { - map.getValues().forEach(handleError(exn)); - observer.onError(exn); - }, - expire) - ); - } + function deepEqual(a, b) { + if (a === b) { + return true; + } - var element; - try { - element = elementSelector(x); - } catch (e) { - map.getValues().forEach(handleError(e)); - observer.onError(e); - return; - } + 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; + } - writer.onNext(element); - }, function (ex) { - map.getValues().forEach(handleError(ex)); - observer.onError(ex); - }, function () { - map.getValues().forEach(function (item) { item.onCompleted(); }); - observer.onCompleted(); - })); + if (a.size === 0 && b.size === 0) { + return true; + } - return refCountDisposable; - }, source); - }; - - var MapObservable = (function (__super__) { - inherits(MapObservable, __super__); + var notAssociative = !isAssociative(a); - 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); } + 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; } - MapObservable.prototype.internalMap = function (selector, thisArg) { - return new MapObservable(this.source, innerMap(selector, this), thisArg); - }; + var flipped = false; - 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); + if (a.size === undefined) { + if (b.size === undefined) { + if (typeof a.cacheResult === 'function') { + a.cacheResult(); + } + } else { + flipped = true; + var _ = a; + a = b; + b = _; } - 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; + } + + 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 false; - }; + }); - return MapObservable; + return allEqual && a.size === bSize; + } - }(ObservableBase)); + createClass(Repeat, IndexedSeq); - /** - * 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; + 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; } - 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)); + Repeat.prototype.toString = function() { + if (this.size === 0) { + return 'Repeat []'; + } + return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; + }; - 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; + Repeat.prototype.get = function(index, notSetValue) { + return this.has(index) ? this._value : notSetValue; + }; - 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)); + Repeat.prototype.includes = function(searchValue) { + return is(this._value, searchValue); }; - - 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--; - } + + 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)); }; - InnerObserver.prototype.onError = function(e) { - if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } + + Repeat.prototype.reverse = function() { + return this; }; - InnerObserver.prototype.onCompleted = function() { - if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } + + Repeat.prototype.indexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return 0; + } + return -1; }; - InnerObserver.prototype.dispose = function() { this.isStopped = true; }; - InnerObserver.prototype.fail = function(e) { - if (!this.isStopped) { - this.isStopped = true; - this.o.onError(e); - return true; + + Repeat.prototype.lastIndexOf = function(searchValue) { + if (is(this._value, searchValue)) { + return this.size; } - return false; + return -1; }; - - 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; - } + + Repeat.prototype.__iterate = function(fn, reverse) { + for (var ii = 0; ii < this.size; ii++) { + if (fn(this._value, ii, this) === false) { + return ii + 1; } - 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 = n && comparer(x, searchElement)) { - o.onNext(true); - o.onCompleted(); - } - }, - function (e) { o.onError(e); }, - function () { - o.onNext(false); - o.onCompleted(); - }); - }, this); - }; - /** - * @deprecated use #includes instead. - */ - observableProto.contains = function (searchElement, fromIndex) { - //deprecate('contains', 'includes'); - observableProto.includes(searchElement, fromIndex); - }; - - /** - * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. - * @example - * res = source.count(); - * res = source.count(function (x) { return x > 3; }); - * @param {Function} [predicate]A function to test each element for a condition. - * @param {Any} [thisArg] Object to use as this when executing callback. - * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. - */ - observableProto.count = function (predicate, thisArg) { - return predicate ? - this.filter(predicate, thisArg).count() : - this.reduce(function (count) { return count + 1; }, 0); - }; - - /** - * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. - * @param {Any} searchElement Element to locate in the array. - * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. - * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. - */ - 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; + hash = getIENodeHash(obj); + if (hash !== undefined) { + return hash; } - 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); - }; - - /** - * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. - * @param {Function} [selector] A transform function to apply to each element. - * @param {Any} [thisArg] Object to use as this when executing callback. - * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. - */ - observableProto.sum = function (keySelector, thisArg) { - return keySelector && isFunction(keySelector) ? - this.map(keySelector, thisArg).sum() : - this.reduce(function (prev, curr) { return prev + curr; }, 0); - }; - - /** - * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. - * @example - * var res = source.minBy(function (x) { return x.value; }); - * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); - * @param {Function} keySelector Key selector function. - * @param {Function} [comparer] Comparer used to compare key values. - * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. - */ - observableProto.minBy = function (keySelector, comparer) { - comparer || (comparer = defaultSubComparer); - return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); - }; - - /** - * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. - * @example - * var res = source.min(); - * var res = source.min(function (x, y) { return x.value - y.value; }); - * @param {Function} [comparer] Comparer used to compare elements. - * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. - */ - observableProto.min = function (comparer) { - return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); - }; - - /** - * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. - * @example - * var res = source.maxBy(function (x) { return x.value; }); - * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); - * @param {Function} keySelector Key selector function. - * @param {Function} [comparer] Comparer used to compare key values. - * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. - */ - observableProto.maxBy = function (keySelector, comparer) { - comparer || (comparer = defaultSubComparer); - return extremaBy(this, keySelector, comparer); - }; - - /** - * Returns the maximum value in an observable sequence according to the specified comparer. - * @example - * var res = source.max(); - * var res = source.max(function (x, y) { return x.value - y.value; }); - * @param {Function} [comparer] Comparer used to compare elements. - * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. - */ - observableProto.max = function (comparer) { - return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); - }; - - /** - * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. - * @param {Function} [selector] A transform function to apply to each element. - * @param {Any} [thisArg] Object to use as this when executing callback. - * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. - */ - 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; - }); - }; - - /** - * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. - * - * @example - * var res = res = source.sequenceEqual([1,2,3]); - * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); - * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); - * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); - * @param {Observable} second Second observable sequence or array to compare. - * @param {Function} [comparer] Comparer used to compare elements of both sequences. - * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. - */ - 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(); - } + 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 }); - }, source); + } 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; } - - /** - * Returns the element at a specified index in a sequence. - * @example - * var res = source.elementAt(5); - * @param {Number} index The zero-based index of the element to retrieve. - * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. - */ - observableProto.elementAt = function (index) { - return elementAtOrDefault(this, index, false); - }; - - /** - * Returns the element at a specified index in a sequence or a default value if the index is out of range. - * @example - * var res = source.elementAtOrDefault(5); - * var res = source.elementAtOrDefault(5, 0); - * @param {Number} index The zero-based index of the element to retrieve. - * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. - * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. - */ - 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); + + // 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; + } + } } - - /** - * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. - */ - observableProto.single = function (predicate, thisArg) { - return predicate && isFunction(predicate) ? - this.where(predicate, thisArg).single() : - singleOrDefaultAsync(this, false); - }; - - /** - * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. - * @example - * var res = res = source.singleOrDefault(); - * var res = res = source.singleOrDefault(function (x) { return x === 42; }); - * res = source.singleOrDefault(function (x) { return x === 42; }, 0); - * res = source.singleOrDefault(null, 0); - * @memberOf Observable# - * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. - * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - 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); + + // If possible, use a WeakMap. + var usingWeakMap = typeof WeakMap === 'function'; + var weakMap; + if (usingWeakMap) { + weakMap = new WeakMap(); } - - /** - * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. - * @example - * var res = res = source.first(); - * var res = res = source.first(function (x) { return x > 3; }); - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. - */ - observableProto.first = function (predicate, thisArg) { - return predicate ? - this.where(predicate, thisArg).first() : - firstOrDefaultAsync(this, false); - }; - - /** - * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - 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); + + var objHashUID = 0; + + var UID_HASH_KEY = '__immutablehash__'; + if (typeof Symbol === 'function') { + UID_HASH_KEY = Symbol(UID_HASH_KEY); } - - /** - * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. - */ - observableProto.last = function (predicate, thisArg) { - return predicate ? - this.where(predicate, thisArg).last() : - lastOrDefaultAsync(this, false); - }; - - /** - * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. - * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. - */ - 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); + + 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.' + ); } - - /** - * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. - * @param {Function} predicate The predicate that defines the conditions of the element to search for. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. - */ - observableProto.find = function (predicate, thisArg) { - return findValue(this, predicate, thisArg, false); - }; - - /** - * Searches for an element that matches the conditions defined by the specified predicate, and returns - * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. - * @param {Function} predicate The predicate that defines the conditions of the element to search for. - * @param {Any} [thisArg] Object to use as `this` when executing the predicate. - * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. - */ - observableProto.findIndex = function (predicate, thisArg) { - return findValue(this, predicate, thisArg, true); - }; - - /** - * Converts the observable sequence to a Set if it exists. - * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. - */ - 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); - }; - - /** - * Converts the observable sequence to a Map if it exists. - * @param {Function} keySelector A function which produces the key for the Map. - * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. - * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. - */ - 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; - } - } + createClass(Map, KeyedCollection); - m.set(key, element); - }, - function (e) { o.onError(e); }, - function () { - o.onNext(m); - o.onCompleted(); + // @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)}); }); - }, 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); } + Map.of = function() {var keyValues = SLICE$0.call(arguments, 0); + return emptyMap().withMutations(function(map ) { + for (var i = 0; i < keyValues.length; i += 2) { + if (i + 1 >= keyValues.length) { + throw new Error('Missing value for key: ' + keyValues[i]); + } + map.set(keyValues[i], keyValues[i + 1]); + } + }); + }; - return obj; - } + Map.prototype.toString = function() { + return this.__toString('Map {', '}'); + }; - function objectToThunk(obj) { - var ctx = this; + // @pragma Access - return function (done) { - var keys = Object.keys(obj), - pending = keys.length, - results = new obj.constructor(), - finished; + Map.prototype.get = function(k, notSetValue) { + return this._root ? + this._root.get(0, undefined, k, notSetValue) : + notSetValue; + }; - if (!pending) { - timeoutScheduler.schedule(function () { done(null, results); }); - return; - } + // @pragma Modification - for (var i = 0, len = keys.length; i < len; i++) { - run(obj[keys[i]], keys[i]); - } + Map.prototype.set = function(k, v) { + return updateMap(this, k, v); + }; - function run(fn, key) { - if (finished) { return; } - try { - fn = toThunk(fn, ctx); + Map.prototype.setIn = function(keyPath, v) { + return this.updateIn(keyPath, NOT_SET, function() {return v}); + }; - if (typeof fn !== fnString) { - results[key] = fn; - return --pending || done(null, results); - } + Map.prototype.remove = function(k) { + return updateMap(this, k, NOT_SET); + }; - fn.call(ctx, function(err, res) { - if (finished) { return; } + Map.prototype.deleteIn = function(keyPath) { + return this.updateIn(keyPath, function() {return NOT_SET}); + }; - if (err) { - finished = true; - return done(err); - } + Map.prototype.update = function(k, notSetValue, updater) { + return arguments.length === 1 ? + k(this) : + this.updateIn([k], notSetValue, updater); + }; - results[key] = res; - --pending || done(null, results); - }); - } catch (e) { - finished = true; - done(e); - } + 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; + }; - function observableToThunk(observable) { - return function (fn) { - var value, hasValue = false; - observable.subscribe( - function (v) { - value = v; - hasValue = true; - }, - fn, - function () { - hasValue && fn(null, value); - }); - } - } + 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(); + }; - function promiseToThunk(promise) { - return function(fn) { - promise.then(function(res) { - fn(null, res); - }, fn); - } - } + // @pragma Composition - function isObservable(obj) { - return obj && typeof obj.subscribe === fnString; - } + Map.prototype.merge = function(/*...iters*/) { + return mergeIntoMapWith(this, undefined, arguments); + }; - function isGeneratorFunction(obj) { - return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; - } + Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, merger, iters); + }; - function isGenerator(obj) { - return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; - } + 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]} + ); + }; - /* - * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. - * @param {Function} The spawning function. - * @returns {Function} a function which has a done continuation. - */ - var observableSpawn = Rx.spawn = function (fn) { - var isGenFun = isGeneratorFunction(fn); + Map.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoMapWith(this, deepMerger, arguments); + }; - return function (done) { - var ctx = this, - gen = fn; + Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoMapWith(this, deepMergerWith(merger), iters); + }; - if (isGenFun) { - for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } - var len = args.length, - hasCallback = len && typeof args[len - 1] === fnString; + 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]} + ); + }; - done = hasCallback ? args.pop() : handleError; - gen = fn.apply(this, args); - } else { - done = done || handleError; - } + Map.prototype.sort = function(comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator)); + }; - next(); + Map.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedMap(sortFactory(this, comparator, mapper)); + }; - function exit(err, res) { - timeoutScheduler.schedule(done.bind(ctx, err, res)); + // @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 next(err, res) { - var ret; - // multiple args - if (arguments.length > 2) { - for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } - } + function isMap(maybeMap) { + return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); + } - if (err) { - try { - ret = gen[throwString](err); - } catch (e) { - return exit(e); - } - } + Map.isMap = isMap; - if (!err) { - try { - ret = gen.next(res); - } catch (e) { - return exit(e); - } + 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; + }; - if (ret.done) { - return exit(null, ret.value); + 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; - ret.value = toThunk(ret.value, ctx); + if (exists ? entries[idx][1] === value : removed) { + return this; + } - if (typeof ret.value === fnString) { - var called = false; - try { - ret.value.call(ctx, function() { - if (called) { - return; - } + SetRef(didAlter); + (removed || !exists) && SetRef(didChangeSize); - called = true; - next.apply(ctx, arguments); - }); - } catch (e) { - timeoutScheduler.schedule(function () { - if (called) { - return; - } + if (removed && entries.length === 1) { + return; // undefined + } - called = true; - next.call(ctx, e); - }); - } - return; + 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]); + } - // Not supported - next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); + if (isEditable) { + this.entries = newEntries; + return this; } - } - }; - function handleError(err) { - if (!err) { return; } - timeoutScheduler.schedule(function() { - throw err; - }); - } - - /** - * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. - * - * @example - * var res = Rx.Observable.start(function () { console.log('hello'); }); - * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); - * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); - * - * @param {Function} func Function to run asynchronously. - * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. - * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @returns {Observable} An observable sequence exposing the function's result value, or an exception. - * - * Remarks - * * The function is called immediately, not during the subscription of the resulting sequence. - * * Multiple subscriptions to the resulting sequence can observe the function's result. - */ - Observable.start = function (func, context, scheduler) { - return observableToAsync(func, context, scheduler)(); - }; - - /** - * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. - * @param {Function} function Function to convert to an asynchronous function. - * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. - * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @returns {Function} Asynchronous function. - */ - var observableToAsync = Observable.toAsync = function (func, context, scheduler) { - isScheduler(scheduler) || (scheduler = timeoutScheduler); - return function () { - var args = arguments, - subject = new AsyncSubject(); - - scheduler.schedule(function () { - var result; - try { - result = func.apply(context, args); - } catch (e) { - subject.onError(e); - return; - } - subject.onNext(result); - subject.onCompleted(); - }); - return subject.asObservable(); + return new ArrayMapNode(ownerID, newEntries); }; - }; - - /** - * Converts a callback function to an observable sequence. - * - * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. - * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. - * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. - */ - Observable.fromCallback = function (func, context, selector) { - return function () { - var len = arguments.length, args = new Array(len) - for(var i = 0; i < len; i++) { args[i] = arguments[i]; } - return new AnonymousObservable(function (observer) { - function handler() { - var len = arguments.length, results = new Array(len); - for(var i = 0; i < len; i++) { results[i] = arguments[i]; } - if (selector) { - try { - results = selector.apply(context, results); - } catch (e) { - return observer.onError(e); - } - observer.onNext(results); - } else { - if (results.length <= 1) { - observer.onNext.apply(observer, results); - } else { - observer.onNext(results); - } - } - observer.onCompleted(); - } + function BitmapIndexedNode(ownerID, bitmap, nodes) { + this.ownerID = ownerID; + this.bitmap = bitmap; + this.nodes = nodes; + } - args.push(handler); - func.apply(context, args); - }).publishLast().refCount(); + 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); }; - }; - - /** - * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. - * @param {Function} func The function to call - * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. - * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. - * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. - */ - Observable.fromNodeCallback = function (func, context, selector) { - return function () { - var len = arguments.length, args = new Array(len); - for(var i = 0; i < len; i++) { args[i] = arguments[i]; } - return new AnonymousObservable(function (observer) { - function handler(err) { - if (err) { - observer.onError(err); - return; - } + 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; - var len = arguments.length, results = []; - for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } + if (!exists && value === NOT_SET) { + return this; + } - if (selector) { - try { - results = selector.apply(context, results); - } catch (e) { - return observer.onError(e); - } - observer.onNext(results); - } else { - if (results.length <= 1) { - observer.onNext.apply(observer, results); - } else { - observer.onNext(results); - } - } + 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); - observer.onCompleted(); - } + if (newNode === node) { + return this; + } - args.push(handler); - func.apply(context, args); - }).publishLast().refCount(); - }; - }; - - function createListener (element, name, handler) { - if (element.addEventListener) { - element.addEventListener(name, handler, false); - return disposableCreate(function () { - element.removeEventListener(name, handler, false); - }); - } - throw new Error('No listener found'); - } + if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { + return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); + } - function createEventListener (el, eventName, handler) { - var disposables = new CompositeDisposable(); + if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { + return nodes[idx ^ 1]; + } - // Asume NodeList or HTMLCollection - var toStr = Object.prototype.toString; - if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') { - for (var i = 0, len = el.length; i < len; i++) { - disposables.add(createEventListener(el.item(i), eventName, handler)); + if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { + return newNode; } - } else if (el) { - disposables.add(createListener(el, eventName, handler)); - } - return disposables; - } + 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); - /** - * Configuration option to determine whether to use native events only - */ - Rx.config.useNativeEvents = false; + if (isEditable) { + this.bitmap = newBitmap; + this.nodes = newNodes; + return this; + } - /** - * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. - * - * @example - * var source = Rx.Observable.fromEvent(element, 'mouseup'); - * - * @param {Object} element The DOMElement or NodeList to attach a listener. - * @param {String} eventName The event name to attach the observable sequence. - * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. - * @returns {Observable} An observable sequence of events from the specified element and the specified event. - */ - Observable.fromEvent = function (element, eventName, selector) { - // Node.js specific - if (element.addListener) { - return fromEventPattern( - function (h) { element.addListener(eventName, h); }, - function (h) { element.removeListener(eventName, h); }, - selector); + return new BitmapIndexedNode(ownerID, newBitmap, newNodes); + }; + + + + + function HashArrayMapNode(ownerID, count, nodes) { + this.ownerID = ownerID; + this.count = count; + this.nodes = nodes; } - // Use only if non-native events are allowed - if (!Rx.config.useNativeEvents) { - // Handles jq, Angular.js, Zepto, Marionette, Ember.js - if (typeof element.on === 'function' && typeof element.off === 'function') { - return fromEventPattern( - function (h) { element.on(eventName, h); }, - function (h) { element.off(eventName, h); }, - selector); + HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { + if (keyHash === undefined) { + keyHash = hash(key); } - } - return new AnonymousObservable(function (observer) { - return createEventListener( - element, - eventName, - function handler (e) { - var results = e; + var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; + var node = this.nodes[idx]; + return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; + }; - if (selector) { - try { - results = selector(arguments); - } catch (err) { - return observer.onError(err); - } - } + 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]; - observer.onNext(results); - }); - }).publish().refCount(); - }; - - /** - * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. - * @param {Function} addHandler The function to add a handler to the emitter. - * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. - * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. - * @returns {Observable} An observable sequence which wraps an event from an event emitter - */ - var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { - return new AnonymousObservable(function (observer) { - function innerHandler (e) { - var result = e; - if (selector) { - try { - result = selector(arguments); - } catch (err) { - return observer.onError(err); - } - } - observer.onNext(result); + if (removed && !node) { + return this; } - var returnValue = addHandler(innerHandler); - return disposableCreate(function () { - if (removeHandler) { - removeHandler(innerHandler, returnValue); + 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); } - }); - }).publish().refCount(); - }; - - /** - * Invokes the asynchronous function, surfacing the result through an observable sequence. - * @param {Function} functionAsync Asynchronous function which returns a Promise to run. - * @returns {Observable} An observable sequence exposing the function's result value, or an exception. - */ - Observable.startAsync = function (functionAsync) { - var promise; - try { - promise = functionAsync(); - } catch (e) { - return observableThrow(e); - } - return observableFromPromise(promise); - } - - var PausableObservable = (function (__super__) { + } - inherits(PausableObservable, __super__); + var isEditable = ownerID && ownerID === this.ownerID; + var newNodes = setIn(nodes, idx, newNode, isEditable); - function subscribe(observer) { - var conn = this.source.publish(), - subscription = conn.subscribe(observer), - connection = disposableEmpty; + if (isEditable) { + this.count = newCount; + this.nodes = newNodes; + return this; + } - var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { - if (b) { - connection = conn.connect(); - } else { - connection.dispose(); - connection = disposableEmpty; - } - }); + return new HashArrayMapNode(ownerID, newCount, newNodes); + }; - return new CompositeDisposable(subscription, connection, pausable); - } - function PausableObservable(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); + function HashCollisionNode(ownerID, keyHash, entries) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entries = entries; } - PausableObservable.prototype.pause = function () { - this.controller.onNext(false); + 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; }; - PausableObservable.prototype.resume = function () { - this.controller.onNext(true); - }; + HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { + if (keyHash === undefined) { + keyHash = hash(key); + } - return PausableObservable; + var removed = value === NOT_SET; - }(Observable)); + if (keyHash !== this.keyHash) { + if (removed) { + return this; + } + SetRef(didAlter); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); + } - /** - * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. - * @example - * var pauser = new Rx.Subject(); - * var source = Rx.Observable.interval(100).pausable(pauser); - * @param {Observable} pauser The observable sequence used to pause the underlying sequence. - * @returns {Observable} The observable sequence which is paused based upon the pauser. - */ - observableProto.pausable = function (pauser) { - return new PausableObservable(this, pauser); - }; - - function combineLatestSource(source, subject, resultSelector) { - return new AnonymousObservable(function (o) { - var hasValue = [false, false], - hasValueAll = false, - isDone = false, - values = new Array(2), - err; + 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; - function next(x, i) { - values[i] = x - hasValue[i] = true; - if (hasValueAll || (hasValueAll = hasValue.every(identity))) { - if (err) { return o.onError(err); } - var res = tryCatch(resultSelector).apply(null, values); - if (res === errorObj) { return o.onError(res.e); } - o.onNext(res); + 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]; } - isDone && values[1] && o.onCompleted(); + } else { + newEntries.push([key, value]); } - return new CompositeDisposable( - source.subscribe( - function (x) { - next(x, 0); - }, - function (e) { - if (values[1]) { - o.onError(e); - } else { - err = e; - } - }, - function () { - isDone = true; - values[1] && o.onCompleted(); - }), - subject.subscribe( - function (x) { - next(x, 1); - }, - function (e) { o.onError(e); }, - function () { - isDone = true; - next(true, 1); - }) - ); - }, source); - } + if (isEditable) { + this.entries = newEntries; + return this; + } - var PausableBufferedObservable = (function (__super__) { + return new HashCollisionNode(ownerID, this.keyHash, newEntries); + }; - inherits(PausableBufferedObservable, __super__); - function subscribe(o) { - var q = [], previousShouldFire; - function drainQueue() { while (q.length > 0) { 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; - // change in shouldFire - if (results.shouldFire) { drainQueue(); } - } else { - previousShouldFire = results.shouldFire; - // new data - 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 ValueNode(ownerID, keyHash, entry) { + this.ownerID = ownerID; + this.keyHash = keyHash; + this.entry = entry; } - function PausableBufferedObservable(source, pauser) { - this.source = source; - this.controller = new Subject(); + ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { + return is(key, this.entry[0]) ? this.entry[1] : notSetValue; + }; - if (pauser && pauser.subscribe) { - this.pauser = this.controller.merge(pauser); - } else { - this.pauser = this.controller; + 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; } - __super__.call(this, subscribe, source); - } - - PausableBufferedObservable.prototype.pause = function () { - this.controller.onNext(false); - }; + SetRef(didAlter); - PausableBufferedObservable.prototype.resume = function () { - this.controller.onNext(true); - }; + if (removed) { + SetRef(didChangeSize); + return; // undefined + } - return PausableBufferedObservable; + if (keyMatch) { + if (ownerID && ownerID === this.ownerID) { + this.entry[1] = value; + return this; + } + return new ValueNode(ownerID, this.keyHash, [key, value]); + } - }(Observable)); + SetRef(didChangeSize); + return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); + }; - /** - * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, - * and yields the values that were buffered while paused. - * @example - * var pauser = new Rx.Subject(); - * var source = Rx.Observable.interval(100).pausableBuffered(pauser); - * @param {Observable} pauser The observable sequence used to pause the underlying sequence. - * @returns {Observable} The observable sequence which is paused based upon the pauser. - */ - observableProto.pausableBuffered = function (subject) { - return new PausableBufferedObservable(this, subject); - }; - - var ControlledObservable = (function (__super__) { - inherits(ControlledObservable, __super__); - function subscribe (observer) { - return this.source.subscribe(observer); - } + // #pragma Iterators - function ControlledObservable (source, enableQueue, scheduler) { - __super__.call(this, subscribe, source); - this.subject = new ControlledSubject(enableQueue, scheduler); - this.source = source.multicast(this.subject).refCount(); + 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; + } } + } - 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); + 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; + } } + } - inherits(ControlledSubject, __super__); + ValueNode.prototype.iterate = function (fn, reverse) { + return fn(this.entry); + } - function ControlledSubject(enableQueue, scheduler) { - enableQueue == null && (enableQueue = true); + createClass(MapIterator, Iterator); - __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; + function MapIterator(map, type, reverse) { + this._type = type; + this._reverse = reverse; + this._stack = map._root && mapIteratorFrame(map._root); } - 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)); + 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 { - (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 = []; + 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; } - - 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; + stack = this._stack = this._stack.__prev; } - }); - - return ControlledSubject; - }(Observable)); + return iteratorDone(); + }; - /** - * Attaches a controller to the observable sequence with the ability to queue. - * @example - * var source = Rx.Observable.interval(100).controlled(); - * source.request(3); // Reads 3 values - * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request - * @param {Scheduler} scheduler determines how the requests will be scheduled - * @returns {Observable} The observable sequence which only propagates values on request. - */ - observableProto.controlled = function (enableQueue, scheduler) { - if (enableQueue && isScheduler(enableQueue)) { - scheduler = enableQueue; - enableQueue = true; - } + function mapIteratorValue(type, entry) { + return iteratorValue(type, entry[0], entry[1]); + } - if (enableQueue == null) { enableQueue = true; } - return new ControlledObservable(this, enableQueue, scheduler); - }; - - var StopAndWaitObservable = (function (__super__) { + function mapIteratorFrame(node, prev) { + return { + node: node, + index: 0, + __prev: prev + }; + } - function subscribe (observer) { - this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); + 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 self = this; - timeoutScheduler.schedule(function () { self.source.request(1); }); + var EMPTY_MAP; + function emptyMap() { + return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); + } - return this.subscription; + 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); } - - inherits(StopAndWaitObservable, __super__); - - function StopAndWaitObservable (source) { - __super__.call(this, subscribe, source); - this.source = source; + if (map.__ownerID) { + map.size = newSize; + map._root = newRoot; + map.__hash = undefined; + map.__altered = true; + return map; } + return newRoot ? makeMap(newSize, newRoot) : emptyMap(); + } - var StopAndWaitObserver = (function (__sub__) { - - inherits(StopAndWaitObserver, __sub__); - - function StopAndWaitObserver (observer, observable, cancel) { - __sub__.call(this); - this.observer = observer; - this.observable = observable; - this.cancel = cancel; + 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); + } - var stopAndWaitObserverProto = StopAndWaitObserver.prototype; - - stopAndWaitObserverProto.completed = function () { - this.observer.onCompleted(); - this.dispose(); - }; + function isLeafNode(node) { + return node.constructor === ValueNode || node.constructor === HashCollisionNode; + } - stopAndWaitObserverProto.error = function (error) { - this.observer.onError(error); - this.dispose(); - } + function mergeIntoNode(node, ownerID, shift, keyHash, entry) { + if (node.keyHash === keyHash) { + return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); + } - stopAndWaitObserverProto.next = function (value) { - this.observer.onNext(value); + var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; + var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var self = this; - timeoutScheduler.schedule(function () { - self.observable.source.request(1); - }); - }; + 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]); - stopAndWaitObserverProto.dispose = function () { - this.observer = null; - if (this.cancel) { - this.cancel.dispose(); - this.cancel = null; - } - __sub__.prototype.dispose.call(this); - }; + return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); + } - return StopAndWaitObserver; - }(AbstractObserver)); + 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; + } - return StopAndWaitObservable; - }(Observable)); + 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); + } - /** - * Attaches a stop and wait observable to the current observable. - * @returns {Observable} A stop and wait observable. - */ - ControlledObservable.prototype.stopAndWait = function () { - return new StopAndWaitObservable(this); - }; - - var WindowedObservable = (function (__super__) { + 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 subscribe (observer) { - this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); + function deepMerger(existing, value, key) { + return existing && existing.mergeDeep && isIterable(value) ? + existing.mergeDeep(value) : + is(existing, value) ? existing : value; + } - var self = this; - timeoutScheduler.schedule(function () { - self.source.request(self.windowSize); - }); + 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; + }; + } - return this.subscription; + 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); + } + }); + } - inherits(WindowedObservable, __super__); - - function WindowedObservable(source, windowSize) { - __super__.call(this, subscribe, source); - this.source = source; - this.windowSize = windowSize; + 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); + } - var WindowedObserver = (function (__sub__) { + 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; + } - inherits(WindowedObserver, __sub__); + function setIn(array, idx, val, canEdit) { + var newArray = canEdit ? array : arrCopy(array); + newArray[idx] = val; + return newArray; + } - function WindowedObserver(observer, observable, cancel) { - this.observer = observer; - this.observable = observable; - this.cancel = cancel; - this.received = 0; + 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; + } - var windowedObserverPrototype = WindowedObserver.prototype; + 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; + } - windowedObserverPrototype.completed = function () { - this.observer.onCompleted(); - this.dispose(); - }; + var MAX_ARRAY_MAP_SIZE = SIZE / 4; + var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; + var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; - windowedObserverPrototype.error = function (error) { - this.observer.onError(error); - this.dispose(); - }; + createClass(List, IndexedCollection); - windowedObserverPrototype.next = function (value) { - this.observer.onNext(value); + // @pragma Construction - this.received = ++this.received % this.observable.windowSize; - if (this.received === 0) { - var self = this; - timeoutScheduler.schedule(function () { - self.observable.source.request(self.observable.windowSize); - }); + 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]); } - }; + }); + }; - windowedObserverPrototype.dispose = function () { - this.observer = null; - if (this.cancel) { - this.cancel.dispose(); - this.cancel = null; + 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]); } - __sub__.prototype.dispose.call(this); - }; + }); + }; - return WindowedObserver; - }(AbstractObserver)); + List.prototype.shift = function() { + return setListBounds(this, 1); + }; - return WindowedObservable; - }(Observable)); + // @pragma Composition - /** - * Creates a sliding windowed observable based upon the window size. - * @param {Number} windowSize The number of items in the window - * @returns {Observable} A windowed observable based upon the window size. - */ - ControlledObservable.prototype.windowed = function (windowSize) { - return new WindowedObservable(this, windowSize); - }; - - /** - * Pipes the existing Observable sequence into a Node.js Stream. - * @param {Stream} dest The destination Node.js stream. - * @returns {Stream} The destination stream. - */ - observableProto.pipe = function (dest) { - var source = this.pausableBuffered(); + List.prototype.merge = function(/*...iters*/) { + return mergeIntoListWith(this, undefined, arguments); + }; - function onDrain() { - source.resume(); - } + List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return mergeIntoListWith(this, merger, iters); + }; - dest.addListener('drain', onDrain); + List.prototype.mergeDeep = function(/*...iters*/) { + return mergeIntoListWith(this, deepMerger, arguments); + }; - source.subscribe( - function (x) { - !dest.write(String(x)) && source.pause(); - }, - function (err) { - dest.emit('error', err); - }, - function () { - // Hack check because STDIO is not closable - !dest._isStdio && dest.end(); - dest.removeListener('drain', onDrain); + 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); }); + }; - source.resume(); + 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; + }; - return dest; - }; - - /** - * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each - * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's - * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. - * - * @example - * 1 - res = source.multicast(observable); - * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); - * - * @param {Function|Subject} subjectOrSubjectSelector - * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. - * Or: - * Subject to push source elements into. - * - * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if 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(); - } + List.isList = isList; - 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; + var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - os[i].onError(error); - } + 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; - 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 VNode(array, ownerID) { + this.array = array; + this.ownerID = ownerID; } - 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); + // TODO: seems like these methods are very similar - for (var i = 0, len = this.q.length; i < len; i++) { - so.onNext(this.q[i].value); + 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; + }; - if (this.hasError) { - so.onError(this.error); - } else if (this.isStopped) { - so.onCompleted(); + 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; } - so.ensureActive(); - return subscription; - } + 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; + } + } - inherits(ReplaySubject, __super__); + var editable = editableVNode(this, ownerID); + editable.array.splice(sizeIndex + 1); + if (newChild) { + editable.array[sizeIndex] = newChild; + } + return editable; + }; - /** - * 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; - } - }); + var DONE = {}; - return ReplaySubject; - }(Observable)); - - var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { - inherits(ConnectableObservable, __super__); + function iterateList(list, reverse) { + var left = list._origin; + var right = list._capacity; + var tailPos = getTailOffset(right); + var tail = list._tail; - function ConnectableObservable(source, subject) { - var hasSubscription = false, - subscription, - sourceObservable = source.asObservable(); + return iterateNodeOrLeaf(list._root, list._level, 0); - this.connect = function () { - if (!hasSubscription) { - hasSubscription = true; - subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { - hasSubscription = false; - })); + 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; } - return subscription; + var idx = reverse ? --to : from++; + return array && array[idx]; }; - - __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(); + 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 observable; - }; + 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); + }; + } + } - return new AnonymousObservable(function(o) { - return getObservable().subscribe(o); - }); - }; - - var Dictionary = (function () { + 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 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"; + var EMPTY_LIST; + function emptyList() { + return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); + } - 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 updateList(list, index, value) { + index = wrapIndex(list, index); + + if (index !== index) { + return list; } - 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; + 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) + }); } - 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; + 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); } - 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; + if (!didAlter.value) { + return list; } - var getHashCode = (function () { - var uniqueIdCounter = 0; + 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); + } - return function (obj) { - if (obj == null) { throw new Error(noSuchkey); } + 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; + } - // 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 newNode; - var id = 17 * uniqueIdCounter++; - obj.hashCode = function () { return id; }; - return id; - }; - }()); + 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; + } - function newEntry() { - return { key: null, value: null, next: 0, hashCode: 0 }; + if (nodeHas && node.array[idx] === value) { + return node; } - function Dictionary(capacity, comparer) { - if (capacity < 0) { throw new ArgumentOutOfRangeError(); } - if (capacity > 0) { this._initialize(capacity); } + SetRef(didAlter); - this.comparer = comparer || defaultComparer; - this.freeCount = 0; - this.size = 0; - this.freeList = -1; + newNode = editableVNode(node, ownerID); + if (value === undefined && idx === newNode.array.length - 1) { + newNode.array.pop(); + } else { + newNode.array[idx] = value; } + return newNode; + } - var dictionaryProto = Dictionary.prototype; + function editableVNode(node, ownerID) { + if (ownerID && node && ownerID === node.ownerID) { + return node; + } + return new VNode(node ? node.array.slice() : [], ownerID); + } - 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(); + 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; } - this.freeList = -1; - }; + return node; + } + } - dictionaryProto.add = function (key, value) { - this._insert(key, value, true); - }; + 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; + } - 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; - }; + // If it's going to end after it starts, it's empty. + if (newOrigin >= newCapacity) { + return list.clear(); + } - 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; + 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); } - this.buckets = numArray; - this.entries = entryArray; - }; + node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; + } - 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; - } + // 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]; } - 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; + // Trim the new sides of the new root. + if (newRoot && newOrigin > oldOrigin) { + newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } - for (index = 0; index < this.size; ++index) { - this.entries[index] = newEntry(); + if (newRoot && newTailOffset < oldTailOffset) { + newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } - this.freeList = -1; - this.size = 0; - }; + if (offsetShift) { + newOrigin -= offsetShift; + newCapacity -= offsetShift; + } + } - 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; - } - } + 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; } - return -1; + 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); }; - dictionaryProto.count = function () { - return this.size - this.freeCount; + OrderedMap.prototype.toString = function() { + return this.__toString('OrderedMap {', '}'); }; - dictionaryProto.tryGetValue = function (key) { - var entry = this._findEntry(key); - return entry >= 0 ? - this.entries[entry].value : - undefined; + // @pragma Access + + OrderedMap.prototype.get = function(k, notSetValue) { + var index = this._map.get(k); + return index !== undefined ? this._list.get(index)[1] : notSetValue; }; - 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; - } - } + // @pragma Modification + + OrderedMap.prototype.clear = function() { + if (this.size === 0) { + return this; } - return results; + if (this.__ownerID) { + this.size = 0; + this._map.clear(); + this._list.clear(); + return this; + } + return emptyOrderedMap(); }; - dictionaryProto.get = function (key) { - var entry = this._findEntry(key); - if (entry >= 0) { return this.entries[entry].value; } - throw new Error(noSuchkey); + OrderedMap.prototype.set = function(k, v) { + return updateOrderedMap(this, k, v); }; - dictionaryProto.set = function (key, value) { - this._insert(key, value, false); + OrderedMap.prototype.remove = function(k) { + return updateOrderedMap(this, k, NOT_SET); }; - dictionaryProto.containskey = function (key) { - return this._findEntry(key) >= 0; + OrderedMap.prototype.wasAltered = function() { + return this._map.wasAltered() || this._list.wasAltered(); }; - 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(); + 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 + ); + }; - group.add(left.subscribe( - function (value) { - var id = leftId++; - var md = new SingleAssignmentDisposable(); + OrderedMap.prototype.__iterator = function(type, reverse) { + return this._list.fromEntrySeq().__iterator(type, reverse); + }; - leftMap.add(id, value); - group.add(md); + 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); + }; - 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; - } + function isOrderedMap(maybeOrderedMap) { + return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); + } - md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + OrderedMap.isOrderedMap = isOrderedMap; - rightMap.getValues().forEach(function (v) { - var result; - try { - result = resultSelector(value, v); - } catch (exn) { - observer.onError(exn); - return; - } + OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; + OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; - 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); + 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 expire = function () { - rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); - group.remove(md); - }; + var EMPTY_ORDERED_MAP; + function emptyOrderedMap() { + return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); + } - var duration; - try { - duration = rightDurationSelector(value); - } catch (e) { - observer.onError(e); - return; - } + 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); + } - md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); + createClass(ToKeyedSequence, KeyedSeq); + function ToKeyedSequence(indexed, useKeys) { + this._iter = indexed; + this._useKeys = useKeys; + this.size = indexed.size; + } - leftMap.getValues().forEach(function (v) { - var result; - try { - result = resultSelector(v, value); - } catch (exn) { - observer.onError(exn); - return; - } + ToKeyedSequence.prototype.get = function(key, notSetValue) { + return this._iter.get(key, notSetValue); + }; - 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; + ToKeyedSequence.prototype.has = function(key) { + return this._iter.has(key); + }; - function handleError(e) { return function (v) { v.onError(e); }; }; + ToKeyedSequence.prototype.valueSeq = function() { + return this._iter.valueSeq(); + }; - group.add(left.subscribe( - function (value) { - var s = new Subject(); - var id = leftId++; - leftMap.add(id, s); + 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; + }; - var result; - try { - result = resultSelector(value, addRef(s, r)); - } catch (e) { - leftMap.getValues().forEach(handleError(e)); - observer.onError(e); - return; - } - observer.onNext(result); + 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; + }; - rightMap.getValues().forEach(function (v) { s.onNext(v); }); + 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 + ); + }; - var md = new SingleAssignmentDisposable(); - group.add(md); + 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); + }); + }; - var expire = function () { - leftMap.remove(id) && s.onCompleted(); - group.remove(md); - }; + ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; - 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)) - ); + createClass(ToIndexedSequence, IndexedSeq); + function ToIndexedSequence(iter) { + this._iter = iter; + this.size = iter.size; + } - group.add(right.subscribe( - function (value) { - var id = rightId++; - rightMap.add(id, value); + ToIndexedSequence.prototype.includes = function(value) { + return this._iter.includes(value); + }; - var md = new SingleAssignmentDisposable(); - group.add(md); + 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); + }; - var expire = function () { - rightMap.remove(id); - group.remove(md); - }; + 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) + }); + }; - 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); + createClass(ToSetSequence, SetSeq); + function ToSetSequence(iter) { + this._iter = iter; + this.size = iter.size; } - 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; - }); - } + ToSetSequence.prototype.has = function(key) { + return this._iter.includes(key); + }; - function observableWindowWithBoundaries(windowBoundaries) { - var source = this; - return new AnonymousObservable(function (observer) { - var win = new Subject(), - d = new CompositeDisposable(), - r = new RefCountDisposable(d); + ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); + }; - observer.onNext(addRef(win, r)); + 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); + }); + }; - 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(); - })); + createClass(FromEntriesSequence, KeyedSeq); + function FromEntriesSequence(entries) { + this._iter = entries; + this.size = entries.size; + } - return r; - }, source); - } + FromEntriesSequence.prototype.entrySeq = function() { + return this._iter.toSeq(); + }; - 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(); - })); + 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); + }; - function createWindowClose () { - var windowClose; - try { - windowClose = windowClosingSelector(); - } catch (e) { - observer.onError(e); - return; + 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 + ); + } } + }); + }; - 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(); - })); - } + ToIndexedSequence.prototype.cacheResult = + ToKeyedSequence.prototype.cacheResult = + ToSetSequence.prototype.cacheResult = + FromEntriesSequence.prototype.cacheResult = + cacheResultThrough; - 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; + + 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; } - 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; + return step; + }); + } + return iterable.__iterator( + type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, + reverse + ); } - WhileEnumerable.prototype[$iterator$] = function () { - var self = this; - return { - next: function () { - return self.c() ? - { done: false, value: self.s } : - { done: true, value: void 0 }; + 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); }; - 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]); } + 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; } - return new AnonymousObservable(function (subscriber) { - var count = allSources.length; - if (count === 0) { - subscriber.onCompleted(); - return disposableEmpty; + if (end !== undefined) { + if (end === Infinity) { + end = originalSize; + } else { + end = end | 0; } - 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); - } + if (wholeSlice(begin, end, originalSize)) { + return iterable; + } - 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(); + var resolvedBegin = resolveBegin(begin, originalSize); + var resolvedEnd = resolveEnd(end, originalSize); - isPromise(second) && (second = observableFromPromise(second)); + // 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); + } - 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; + // 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; } - inherits(ChainObservable, __super__); + var sliceSeq = makeSequence(iterable); - function ChainObservable(head) { - __super__.call(this, subscribe); - this.head = head; - this.tail = new AsyncSubject(); - } + // 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; - 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(); + 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; } - }); - - 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; + 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; }; - 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]); + 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 Map; - }()); - - /** - * @constructor - * Represents a join pattern over observable sequences. - */ - function Pattern(patterns) { - this.patterns = patterns; + return sliceSeq; } - /** - * 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; + 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); } - observer.onNext(result); - }, function () { - for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { - joinObservers[j].removeActivePlan(activePlan); + 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); } - 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; + 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 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); - } + + + 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; } - 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; + 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 (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); + + if (iters.length === 1) { + var singleton = iters[0]; + if (singleton === iterable || + isKeyedIterable && isKeyed(singleton) || + isIndexed(iterable) && isIndexed(singleton)) { + return singleton; } } - }; - - 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 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; + } - 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(); - } + 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; + } - JoinObserverPrototype.error = noop; - JoinObserverPrototype.completed = noop; - JoinObserverPrototype.addActivePlan = function (activePlan) { - this.activePlans.push(activePlan); - }; + 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); + } - 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(); + 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; }; - - JoinObserverPrototype.dispose = function () { - __super__.prototype.dispose.call(this); - if (!this.isDisposed) { - this.isDisposed = true; - this.subscription.dispose(); - } + 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; + } - 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]; + + 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 { - plans = new Array(len); - for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } + return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } - 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(); - })); + } + + 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; } - } catch (e) { - observableThrow(e).subscribe(o); } - var group = new CompositeDisposable(); - externalSubscriptions.forEach(function (joinObserver) { - joinObserver.subscribe(); - group.add(joinObserver); + 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 + } - return group; - }); - }; - - function observableTimerDate(dueTime, scheduler) { - return new AnonymousObservable(function (observer) { - return scheduler.scheduleWithAbsolute(dueTime, function () { - observer.onNext(0); - observer.onCompleted(); - }); - }); + + // #pragma Helper Functions + + function reify(iter, seq) { + return isSeq(iter) ? seq : iter.constructor(seq); } - - 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 validateEntry(entry) { + if (entry !== Object(entry)) { + throw new TypeError('Expected [K, V] tuple: ' + entry); + } } - - function observableTimerTimeSpan(dueTime, scheduler) { - return new AnonymousObservable(function (observer) { - return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { - observer.onNext(0); - observer.onCompleted(); - }); - }); + + function resolveSize(iter) { + assertNotInfinite(iter.size); + return ensureSize(iter); } - - 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); - }); + + function iterableClass(iterable) { + return isKeyed(iterable) ? KeyedIterable : + isIndexed(iterable) ? IndexedIterable : + SetIterable; } - - /** - * 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 makeSequence(iterable) { + return Object.create( + ( + isKeyed(iterable) ? KeyedSeq : + isIndexed(iterable) ? IndexedSeq : + SetSeq + ).prototype + ); } - function observableDelayDate(source, dueTime, scheduler) { - return observableDefer(function () { - return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); - }); + function cacheResultThrough() { + if (this._iter.cacheResult) { + this._iter.cacheResult(); + this.size = this._iter.size; + return this; + } else { + return Seq.prototype.cacheResult.call(this); + } } - /** - * 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); - }; + function defaultComparator(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + } - /** - * @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; + 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 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); + return iter; + } - 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; + createClass(Record, KeyedCollection); + + function Record(defaultValues, name) { + var hasInitialized; + + var RecordType = function Record(values) { + if (values instanceof RecordType) { + return values; } - var newTotalTime = isSpan ? nextSpan : nextShift, - ts = newTotalTime - totalTime; - totalTime = newTotalTime; - if (isSpan) { - nextSpan += timeShift; + if (!(this instanceof RecordType)) { + return new RecordType(values); } - if (isShift) { - nextShift += timeShift; + 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; } - 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(); - })); + this._map = Map(values); }; - 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); - })); - } + var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); + RecordTypePrototype.constructor = RecordType; - observer.onNext(addRef(s, refCountDisposable)); - createTimer(0); + return RecordType; + } - 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(); }); + Record.prototype.toString = function() { + return this.__toString(recordName(this) + ' {', '}'); }; - - /** - * 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(); - }); + + // @pragma Access + + Record.prototype.has = function(k) { + return this._defaultValues.hasOwnProperty(k); }; - - /** - * 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(); + 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; + }; - 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); - } + // @pragma Modification - /** - * 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); + 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())); + }; - var source = this, schedulerMethod = dueTime instanceof Date ? - 'scheduleWithAbsolute' : - 'scheduleWithRelative'; + Record.prototype.set = function(k, v) { + if (!this.has(k)) { + throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); + } + if (this._map && !this._map.has(k)) { + var defaultVal = this._defaultValues[k]; + if (v === defaultVal) { + return this; + } + } + var newMap = this._map && this._map.set(k, v); + if (this.__ownerID || newMap === this._map) { + return this; + } + return makeRecord(this, newMap); + }; - return new AnonymousObservable(function (observer) { - var id = 0, - original = new SingleAssignmentDisposable(), - subscription = new SerialDisposable(), - switched = false, - timer = new SerialDisposable(); + 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); + }; - subscription.setDisposable(original); + Record.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; - function createTimer() { - var myId = id; - timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { - if (id === myId) { - isPromise(other) && (other = observableFromPromise(other)); - subscription.setDisposable(other.subscribe(observer)); - } - })); + 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); + }; - 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); + 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; - 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(); + function makeRecord(likeRecord, map, ownerID) { + var record = Object.create(Object.getPrototypeOf(likeRecord)); + record._map = map; + record.__ownerID = ownerID; + return record; + } - d.setDisposable(scheduler[scheduleMethod](dueTime, function() { - d.setDisposable(source.subscribe(o)); - })); + function recordName(record) { + return record._name || record.constructor.name || 'Record'; + } - 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; + function setProps(prototype, names) { + try { + names.forEach(setProp.bind(undefined, prototype)); + } catch (error) { + // Object.defineProperty failed. Probably IE8. } - 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 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); } + }); + } - function done () { - atEnd && delays.length === 0 && observer.onCompleted(); - } + createClass(Set, SetCollection); - if (!subDelay) { - start(); - } else { - subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); - } + // @pragma Construction - 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(); + 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)}); + }); + } - subscription.setDisposable(original); + Set.of = function(/*...values*/) { + return this(arguments); + }; - var id = 0, switched = false; + Set.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; - function setTimer(timeout) { - var myId = id; + Set.prototype.toString = function() { + return this.__toString('Set {', '}'); + }; - function timerWins () { - return id === myId; - } + // @pragma Access - 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)); - })); - }; + Set.prototype.has = function(value) { + return this._map.has(value); + }; - setTimer(firstTimeout); + // @pragma Modification - function observerWins() { - var res = !switched; - if (res) { id++; } - return res; - } + Set.prototype.add = function(value) { + return updateSet(this, this._map.set(value, true)); + }; - 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); + Set.prototype.remove = function(value) { + return updateSet(this, this._map.remove(value)); }; - - /** - * 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)); + Set.prototype.clear = function() { + return updateSet(this, this._map.clear()); + }; - 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); - }; + // @pragma Composition - /** - * @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); + 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)}); } - 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); + 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); } - },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); + 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); } - }, - 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); + Set.prototype.merge = function() { + return this.union.apply(this, arguments); + }; - m.setDisposable(sources.subscribe( - function (innerSource) { - if (!hasCurrent) { - hasCurrent = true; + Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); + return this.union.apply(this, iters); + }; - isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + Set.prototype.sort = function(comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator)); + }; - var innerSubscription = new SingleAssignmentDisposable(); - g.add(innerSubscription); + Set.prototype.sortBy = function(mapper, comparator) { + // Late binding + return OrderedSet(sortFactory(this, comparator, mapper)); + }; - 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(); - } - })); + Set.prototype.wasAltered = function() { + return this._map.wasAltered(); + }; - 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(); + Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; + return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); + }; - g.add(m); + Set.prototype.__iterator = function(type, reverse) { + return this._map.map(function(_, k) {return k}).__iterator(type, reverse); + }; - m.setDisposable(sources.subscribe( - function (innerSource) { + 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); + }; - if (!hasCurrent) { - hasCurrent = true; - innerSubscription = new SingleAssignmentDisposable(); - g.add(innerSubscription); + function isSet(maybeSet) { + return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); + } - isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); + Set.isSet = isSet; - innerSubscription.setDisposable(innerSource.subscribe( - function (x) { - var result; - try { - result = selectorFunc(x, index++, innerSource); - } catch (e) { - observer.onError(e); - return; - } + var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; - observer.onNext(result); - }, - function (e) { observer.onError(e); }, - function () { - g.remove(innerSubscription); - hasCurrent = false; + 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; - 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__) { + SetPrototype.__empty = emptySet; + SetPrototype.__make = makeSet; - function localNow() { - return this.toDateTimeOffset(this.clock); + 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 scheduleNow(state, action) { - return this.scheduleAbsoluteWithState(state, this.clock, action); - } + function makeSet(map, ownerID) { + var set = Object.create(SetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } - function scheduleRelative(state, dueTime, action) { - return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); - } + var EMPTY_SET; + function emptySet() { + return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); + } - function scheduleAbsolute(state, dueTime, action) { - return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); - } + createClass(OrderedSet, Set); - function invokeAction(scheduler, action) { - action(); - return disposableEmpty; + // @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)}); + }); } - inherits(VirtualTimeScheduler, __super__); + OrderedSet.of = function(/*...values*/) { + return this(arguments); + }; - /** - * 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); - } + OrderedSet.fromKeys = function(value) { + return this(KeyedIterable(value).keySeq()); + }; - var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + OrderedSet.prototype.toString = function() { + return this.__toString('OrderedSet {', '}'); + }; - /** - * 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; + function isOrderedSet(maybeOrderedSet) { + return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); + } - /** - * 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; + OrderedSet.isOrderedSet = isOrderedSet; - /** - * 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(); - }; + var OrderedSetPrototype = OrderedSet.prototype; + OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; - /** - * 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); - }; + OrderedSetPrototype.__empty = emptyOrderedSet; + OrderedSetPrototype.__make = makeOrderedSet; - /** - * 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); - }; + function makeOrderedSet(map, ownerID) { + var set = Object.create(OrderedSetPrototype); + set.size = map ? map.size : 0; + set._map = map; + set.__ownerID = ownerID; + return set; + } - /** - * 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); - } - }; + var EMPTY_ORDERED_SET; + function emptyOrderedSet() { + return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); + } - /** - * Stops the virtual time scheduler. - */ - VirtualTimeSchedulerPrototype.stop = function () { - this.isEnabled = false; - }; + createClass(Stack, IndexedCollection); - /** - * 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; - } - }; + // @pragma Construction - /** - * 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; } + function Stack(value) { + return value === null || value === undefined ? emptyStack() : + isStack(value) ? value : + emptyStack().unshiftAll(value); + } - this.advanceTo(dt); + Stack.of = function(/*...values*/) { + return this(arguments); }; - /** - * 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; + Stack.prototype.toString = function() { + return this.__toString('Stack [', ']'); }; - /** - * 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; - } + // @pragma Access + + Stack.prototype.get = function(index, notSetValue) { + var head = this._head; + index = wrapIndex(this, index); + while (head && index--) { + head = head.next; } - return null; + return head ? head.value : notSetValue; }; - /** - * 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); + Stack.prototype.peek = function() { + return this._head && this._head.value; }; - /** - * 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; + // @pragma Modification - function run(scheduler, state1) { - self.queue.remove(si); - return action(scheduler, state1); + Stack.prototype.push = function(/*...values*/) { + if (arguments.length === 0) { + return this; } - - var si = new ScheduledItem(this, state, run, dueTime, this.comparer); - this.queue.enqueue(si); - - return si.disposable; + 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); }; - 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; + 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); }; - HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { - return new Date(absolute).getTime(); + Stack.prototype.pop = function() { + return this.slice(1); }; - /** - * 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; + Stack.prototype.unshift = function(/*...values*/) { + return this.push.apply(this, arguments); }; - 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; - } + Stack.prototype.unshiftAll = function(iter) { + return this.pushAll(iter); + }; - function setDisposable(s, state) { - var ado = state[0], subscribe = state[1]; - var sub = tryCatch(subscribe)(ado); + Stack.prototype.shift = function() { + return this.pop.apply(this, arguments); + }; - if (sub === errorObj) { - if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } + Stack.prototype.clear = function() { + if (this.size === 0) { + return this; } - 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; + if (this.__ownerID) { + this.size = 0; + this._head = undefined; + this.__hash = undefined; + this.__altered = true; + return this; } + return emptyStack(); + }; - __super__.call(this, s); - } - - return AnonymousObservable; + 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); + }; - }(Observable)); - - var AutoDetachObserver = (function (__super__) { - inherits(AutoDetachObserver, __super__); + // @pragma Mutability - function AutoDetachObserver(observer) { - __super__.call(this); - this.observer = observer; - this.m = new SingleAssignmentDisposable(); - } + 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); + }; - var AutoDetachObserverPrototype = AutoDetachObserver.prototype; + // @pragma Iteration - AutoDetachObserverPrototype.next = function (value) { - var result = tryCatch(this.observer.onNext).call(this.observer, value); - if (result === errorObj) { - this.dispose(); - thrower(result.e); + 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; }; - AutoDetachObserverPrototype.error = function (err) { - var result = tryCatch(this.observer.onError).call(this.observer, err); - this.dispose(); - result === errorObj && thrower(result.e); + 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(); + }); }; - 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(); }; + function isStack(maybeStack) { + return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); + } - AutoDetachObserverPrototype.dispose = function () { - __super__.prototype.dispose.call(this); - this.m.dispose(); - }; + Stack.isStack = isStack; - return AutoDetachObserver; - }(AbstractObserver)); - - var GroupedObservable = (function (__super__) { - inherits(GroupedObservable, __super__); + var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; - function subscribe(observer) { - return this.underlyingObservable.subscribe(observer); - } + 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 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)); - + 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)); + } + /** - * Represents an object that is both an observable sequence as well as an observer. - * Each notification is broadcasted to all subscribed observers. + * Contributes additional methods to a constructor */ - 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 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; + } - /** - * Creates a subject. - */ - function Subject() { - __super__.call(this, subscribe); - this.isDisposed = false, - this.isStopped = false, - this.observers = []; - this.hasError = false; - } + Iterable.Iterator = Iterator; - 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(); - } + mixin(Iterable, { - 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); - } + // ### Conversion to other types - 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; - } - }); + toArray: function() { + assertNotInfinite(this.size); + var array = new Array(this.size || 0); + this.valueSeq().__iterate(function(v, i) { array[i] = v; }); + return array; + }, - /** - * 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); - }; + toIndexedSeq: function() { + return new ToIndexedSequence(this); + }, - 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); + toJS: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} + ).__toJS(); + }, - if (!this.isStopped) { - this.observers.push(observer); - return new InnerSubscription(this, observer); - } + toJSON: function() { + return this.toSeq().map( + function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} + ).__toJS(); + }, - if (this.hasError) { - observer.onError(this.error); - } else if (this.hasValue) { - observer.onNext(this.value); - observer.onCompleted(); - } else { - observer.onCompleted(); - } + toKeyedSeq: function() { + return new ToKeyedSequence(this, true); + }, - return disposableEmpty; - } + toMap: function() { + // Use Late Binding here to solve the circular dependency. + return Map(this.toKeyedSeq()); + }, - inherits(AsyncSubject, __super__); + toObject: function() { + assertNotInfinite(this.size); + var object = {}; + this.__iterate(function(v, k) { object[k] = v; }); + return object; + }, - /** - * 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); + toOrderedMap: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedMap(this.toKeyedSeq()); + }, - this.isDisposed = false; - this.isStopped = false; - this.hasValue = false; - this.observers = []; - this.hasError = false; - } + toOrderedSet: function() { + // Use Late Binding here to solve the circular dependency. + return OrderedSet(isKeyed(this) ? this.valueSeq() : this); + }, - 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; + toSet: function() { + // Use Late Binding here to solve the circular dependency. + return Set(isKeyed(this) ? this.valueSeq() : this); + }, - 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(); - } - } + toSetSeq: function() { + return new ToSetSequence(this); + }, - 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; + toSeq: function() { + return isIndexed(this) ? this.toIndexedSeq() : + isKeyed(this) ? this.toKeyedSeq() : + this.toSetSeq(); + }, - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - os[i].onError(error); - } + toStack: function() { + // Use Late Binding here to solve the circular dependency. + return Stack(isKeyed(this) ? this.valueSeq() : this); + }, - 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; - } - }); + toList: function() { + // Use Late Binding here to solve the circular dependency. + return List(isKeyed(this) ? this.valueSeq() : this); + }, - return AsyncSubject; - }(Observable)); - - var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { - inherits(AnonymousSubject, __super__); - function subscribe(observer) { - return this.observable.subscribe(observer); - } + // ### Common JavaScript methods and properties - function AnonymousSubject(observer, observable) { - this.observer = observer; - this.observable = observable; - __super__.call(this, subscribe); - } + toString: function() { + return '[Iterable]'; + }, - addProperties(AnonymousSubject.prototype, Observer.prototype, { - onCompleted: function () { - this.observer.onCompleted(); - }, - onError: function (error) { - this.observer.onError(error); - }, - onNext: function (value) { - this.observer.onNext(value); + __toString: function(head, tail) { + if (this.size === 0) { + return head + tail; } - }); + return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; + }, - return AnonymousSubject; - }(Observable)); - - /** - * Used to pause and resume streams. - */ - Rx.Pauser = (function (__super__) { - inherits(Pauser, __super__); - function Pauser() { - __super__.call(this); - } + // ### ES6 Collection methods (ES6 Array and Map) - /** - * Pauses the underlying sequence. - */ - Pauser.prototype.pause = function () { this.onNext(false); }; + concat: function() {var values = SLICE$0.call(arguments, 0); + return reify(this, concatFactory(this, values)); + }, - /** - * Resumes the underlying sequence. - */ - Pauser.prototype.resume = function () { this.onNext(true); }; + includes: function(searchValue) { + return this.some(function(value ) {return is(value, searchValue)}); + }, - return Pauser; - }(Subject)); - - if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { - root.Rx = Rx; + entries: function() { + return this.__iterator(ITERATE_ENTRIES); + }, - 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)); + 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; + }, -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":2}],101:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "rx@^2.5.3", - "scope": null, - "escapedName": "rx", - "name": "rx", - "rawSpec": "^2.5.3", - "spec": ">=2.5.3 <3.0.0", - "type": "range" - }, - "/Users/hba21580/Dropbox/Afstuderen/rxmarbles" - ] - ], - "_from": "rx@>=2.5.3 <3.0.0", - "_id": "rx@2.5.3", - "_inCache": true, - "_installable": true, - "_location": "/rx", - "_nodeVersion": "0.12.2", - "_npmUser": { - "name": "mattpodwysocki", - "email": "matthew.podwysocki@gmail.com" - }, - "_npmVersion": "2.7.4", - "_phantomChildren": {}, - "_requested": { - "raw": "rx@^2.5.3", - "scope": null, - "escapedName": "rx", - "name": "rx", - "rawSpec": "^2.5.3", - "spec": ">=2.5.3 <3.0.0", - "type": "range" - }, - "_requiredBy": [ - "/", - "/@cycle/core" - ], - "_resolved": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz", - "_shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", - "_shrinkwrap": null, - "_spec": "rx@^2.5.3", - "_where": "/Users/hba21580/Dropbox/Afstuderen/rxmarbles", - "author": { - "name": "Cloud Programmability Team", - "url": "https://github.com/Reactive-Extensions/RxJS/blob/master/authors.txt" - }, - "browser": { - "index.js": "dist/rx.all.js" - }, - "bugs": { - "url": "https://github.com/Reactive-Extensions/RxJS/issues" - }, - "dependencies": {}, - "description": "Library for composing asynchronous and event-based operations in JavaScript", - "devDependencies": { - "benchmark": "*", - "grunt": "*", - "grunt-cli": "*", - "grunt-contrib-concat": "*", - "grunt-contrib-connect": "*", - "grunt-contrib-copy": "*", - "grunt-contrib-jshint": "*", - "grunt-contrib-qunit": "*", - "grunt-contrib-uglify": "*", - "grunt-contrib-watch": "*", - "grunt-jscs": "*", - "grunt-saucelabs": "*", - "load-grunt-tasks": "*" - }, - "directories": {}, - "dist": { - "shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", - "tarball": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz" - }, - "gitHead": "6507118725e93498f7a52a603acf679e472f47b7", - "homepage": "https://github.com/Reactive-Extensions/RxJS", - "jam": { - "main": "dist/rx.all.js" - }, - "keywords": [ - "LINQ", - "FRP", - "Reactive", - "Events", - "Rx", - "RxJS" - ], - "license": "Apache-2.0", - "main": "index.js", - "maintainers": [ - { - "name": "vvilhonen", - "email": "vesa@vilhonen.com" + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, true)); }, - { - "name": "mattpodwysocki", - "email": "matthew.podwysocki@gmail.com" - } - ], - "name": "rx", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/Reactive-Extensions/RxJS.git" - }, - "scripts": { - "test": "grunt" - }, - "title": "Reactive Extensions for JavaScript (RxJS)", - "version": "2.5.3" -} -},{}],102:[function(require,module,exports){ -'use strict'; + find: function(predicate, context, notSetValue) { + var entry = this.findEntry(predicate, context); + return entry ? entry[1] : notSetValue; + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + forEach: function(sideEffect, context) { + assertNotInfinite(this.size); + return this.__iterate(context ? sideEffect.bind(context) : sideEffect); + }, -var _require = require('./ease-common'); + 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; + }, -var createEasing = _require.createEasing; + keys: function() { + return this.__iterator(ITERATE_KEYS); + }, -var OVERSHOOT = 1.70158; + map: function(mapper, context) { + return reify(this, mapFactory(this, mapper, context)); + }, -exports['default'] = { - EasingBack: createEasing(function (x) { - return x * x * ((OVERSHOOT + 1) * x - OVERSHOOT); - }) -}; -module.exports = exports['default']; -},{"./ease-common":105}],103:[function(require,module,exports){ -'use strict'; + 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; + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + reduceRight: function(reducer, initialReduction, context) { + var reversed = this.toKeyedSeq().reverse(); + return reversed.reduce.apply(reversed, arguments); + }, -var _require = require('./ease-common'); + reverse: function() { + return reify(this, reverseFactory(this, true)); + }, -var createEasing = _require.createEasing; + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, true)); + }, -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; - } -} + some: function(predicate, context) { + return !this.every(not(predicate), context); + }, -exports['default'] = { - EasingBounce: createEasing(function (x) { - return 1 - easeOutFn(1 - x); - }) -}; -module.exports = exports['default']; -},{"./ease-common":105}],104:[function(require,module,exports){ -'use strict'; + sort: function(comparator) { + return reify(this, sortFactory(this, comparator)); + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + values: function() { + return this.__iterator(ITERATE_VALUES); + }, -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":105}],105:[function(require,module,exports){ -'use strict'; + // ### More sequential methods -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + butLast: function() { + return this.slice(0, -1); + }, -function interpolate(y, from, to) { - return from * (1 - y) + to * y; -} + isEmpty: function() { + return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); + }, -function flip(fn) { - return function (x) { - return 1 - fn(1 - x); - }; -} + count: function(predicate, context) { + return ensureSize( + predicate ? this.toSeq().filter(predicate, context) : this + ); + }, -exports['default'] = { - interpolate: interpolate, + countBy: function(grouper, context) { + return countByFactory(this, grouper, context); + }, - flip: flip, + equals: function(other) { + return deepEqual(this, other); + }, - 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); + 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); } - }; - } -}; -module.exports = exports['default']; -},{}],106:[function(require,module,exports){ -'use strict'; + var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); + entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; + return entriesSequence; + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + filterNot: function(predicate, context) { + return this.filter(not(predicate), context); + }, -var _require = require('./ease-common'); + findEntry: function(predicate, context, notSetValue) { + var found = notSetValue; + this.__iterate(function(v, k, c) { + if (predicate.call(context, v, k, c)) { + found = [k, v]; + return false; + } + }); + return found; + }, -var createEasing = _require.createEasing; + findKey: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry && entry[0]; + }, -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); - } -} + findLast: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); + }, -exports['default'] = { - EasingElastic: createEasing(elasticIn) -}; -module.exports = exports['default']; -},{"./ease-common":105}],107:[function(require,module,exports){ -'use strict'; + findLastEntry: function(predicate, context, notSetValue) { + return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + findLastKey: function(predicate, context) { + return this.toKeyedSeq().reverse().findKey(predicate, context); + }, -var _require = require('./ease-common'); + first: function() { + return this.find(returnTrue); + }, -var createEasing = _require.createEasing; + flatMap: function(mapper, context) { + return reify(this, flatMapFactory(this, mapper, context)); + }, -var EXP_WEIGHT = 6; -var EXP_MAX = Math.exp(EXP_WEIGHT) - 1; -function expFn(x) { - return (Math.exp(x * EXP_WEIGHT) - 1) / EXP_MAX; -} + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, true)); + }, -var EasingExponential = createEasing(expFn); + fromEntrySeq: function() { + return new FromEntriesSequence(this); + }, -exports['default'] = { - EasingExponential: EasingExponential -}; -module.exports = exports['default']; -},{"./ease-common":105}],108:[function(require,module,exports){ -'use strict'; + get: function(searchKey, notSetValue) { + return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + 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; + }, -var _require = require('./ease-common'); + groupBy: function(grouper, context) { + return groupByFactory(this, grouper, context); + }, -var createEasing = _require.createEasing; + has: function(searchKey) { + return this.get(searchKey, NOT_SET) !== NOT_SET; + }, -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; -}); + hasIn: function(searchKeyPath) { + return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; + }, -exports['default'] = { - EasingPower2: EasingPower2, - EasingPower3: EasingPower3, - EasingPower4: EasingPower4 -}; -module.exports = exports['default']; -},{"./ease-common":105}],109:[function(require,module,exports){ -'use strict'; + isSubset: function(iter) { + iter = typeof iter.includes === 'function' ? iter : Iterable(iter); + return this.every(function(value ) {return iter.includes(value)}); + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; + isSuperset: function(iter) { + iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); + return iter.isSubset(this); + }, -var _require = require('./ease-common'); + keyOf: function(searchValue) { + return this.findKey(function(value ) {return is(value, searchValue)}); + }, -var createEasing = _require.createEasing; + keySeq: function() { + return this.toSeq().map(keyMapper).toIndexedSeq(); + }, -var HALF_PI = Math.PI * 0.5; + last: function() { + return this.toSeq().reverse().first(); + }, -exports['default'] = { - EasingSine: createEasing(function (x) { - return 1 - Math.cos(x * HALF_PI); - }) -}; -module.exports = exports['default']; -},{"./ease-common":105}],110:[function(require,module,exports){ -'use strict'; + lastKeyOf: function(searchValue) { + return this.toKeyedSeq().reverse().keyOf(searchValue); + }, -Object.defineProperty(exports, '__esModule', { - value: true -}); -'use strict'; -var Rx = require('rx'); + max: function(comparator) { + return maxFactory(this, comparator); + }, -var _require = require('./ease-common'); + maxBy: function(mapper, comparator) { + return maxFactory(this, comparator, mapper); + }, -var interpolate = _require.interpolate; + min: function(comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); + }, -var _require2 = require('./ease-powers'); + minBy: function(mapper, comparator) { + return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); + }, -var EasingPower2 = _require2.EasingPower2; -var EasingPower3 = _require2.EasingPower3; -var EasingPower4 = _require2.EasingPower4; + rest: function() { + return this.slice(1); + }, -var _require3 = require('./ease-exponential'); + skip: function(amount) { + return this.slice(Math.max(0, amount)); + }, -var EasingExponential = _require3.EasingExponential; + skipLast: function(amount) { + return reify(this, this.toSeq().reverse().skip(amount).reverse()); + }, -var _require4 = require('./ease-back'); + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, true)); + }, -var EasingBack = _require4.EasingBack; + skipUntil: function(predicate, context) { + return this.skipWhile(not(predicate), context); + }, -var _require5 = require('./ease-bounce'); + sortBy: function(mapper, comparator) { + return reify(this, sortFactory(this, comparator, mapper)); + }, -var EasingBounce = _require5.EasingBounce; + take: function(amount) { + return this.slice(0, Math.max(0, amount)); + }, -var _require6 = require('./ease-circ'); + takeLast: function(amount) { + return reify(this, this.toSeq().reverse().take(amount).reverse()); + }, -var EasingCirc = _require6.EasingCirc; + takeWhile: function(predicate, context) { + return reify(this, takeWhileFactory(this, predicate, context)); + }, -var _require7 = require('./ease-elastic'); + takeUntil: function(predicate, context) { + return this.takeWhile(not(predicate), context); + }, -var EasingElastic = _require7.EasingElastic; + valueSeq: function() { + return this.toIndexedSeq(); + }, -var _require8 = require('./ease-sine'); -var EasingSine = _require8.EasingSine; + // ### Hashable Object -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; -} + hashCode: function() { + return this.__hash || (this.__hash = hashIterable(this)); + } -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)); -} + // ### Internal -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; + // abstract __iterate(fn, reverse) -exports['default'] = RxTween; -module.exports = exports['default']; -},{"./ease-back":102,"./ease-bounce":103,"./ease-circ":104,"./ease-common":105,"./ease-elastic":106,"./ease-exponential":107,"./ease-powers":108,"./ease-sine":109,"rx":100}],111:[function(require,module,exports){ -var lowerCase = require('lower-case') + // abstract __iterator(type, reverse) + }); -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') + // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; + // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; + // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; + // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; -/** - * 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 '' - } + 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; - replacement = replacement || ' ' + mixin(KeyedIterable, { - function replace (match, index, string) { - if (index === 0 || index === (string.length - match.length)) { - return '' - } + // ### More sequential methods - return replacement - } + flip: function() { + return reify(this, flipFactory(this)); + }, - 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) + 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() + ); + }, - // Lower case the entire string. - return lowerCase(str, locale) -} + 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() + ); + } -},{"./vendor/camel-case-regexp":112,"./vendor/non-word-regexp":113,"./vendor/trailing-digit-regexp":114,"lower-case":98}],112:[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 + }); -},{}],113:[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 + 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)}; -},{}],114:[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 -},{}],115:[function(require,module,exports){ -/** - * index.js - * - * A client-side DOM to vdom parser based on DOMParser API - */ + mixin(IndexedIterable, { -'use strict'; + // ### Conversion to other types -var VNode = require('virtual-dom/vnode/vnode'); -var VText = require('virtual-dom/vnode/vtext'); -var domParser; + toKeyedSeq: function() { + return new ToKeyedSequence(this, false); + }, -var propertyMap = require('./property-map'); -var namespaceMap = require('./namespace-map'); -var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; + // ### ES6 Collection methods (ES6 Array and Map) -module.exports = parser; + filter: function(predicate, context) { + return reify(this, filterFactory(this, predicate, context, false)); + }, -/** - * 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('')); - } + findIndex: function(predicate, context) { + var entry = this.findEntry(predicate, context); + return entry ? entry[0] : -1; + }, - 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'); + indexOf: function(searchValue) { + var key = this.keyOf(searchValue); + return key === undefined ? -1 : key; + }, - // most tags default to body - if (doc.body.firstChild) { - el = doc.getElementsByTagName('body')[0].firstChild; + lastIndexOf: function(searchValue) { + var key = this.lastKeyOf(searchValue); + return key === undefined ? -1 : key; + }, - // 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; + reverse: function() { + return reify(this, reverseFactory(this, false)); + }, - // special case for html comment, cdata, doctype - } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { - el = doc.firstChild; + slice: function(begin, end) { + return reify(this, sliceFactory(this, begin, end, false)); + }, - // other element, such as whitespace, or html/body/head tag, fallback to empty text node - } else { - el = document.createTextNode(''); - } - } + 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)) + ); + }, - if (typeof el !== 'object' || !el || !el.nodeType) { - throw new Error('invalid dom node', el); - } - return createNode(el, attr); -} + // ### More collection methods -/** - * 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); + findLastIndex: function(predicate, context) { + var entry = this.findLastEntry(predicate, context); + return entry ? entry[0] : -1; + }, - // cdata or doctype is not currently supported by virtual-dom - } else if (el.nodeType === 1 || el.nodeType === 9) { - return createVirtualDomNode(el, attr); - } + first: function() { + return this.get(0); + }, - // default to empty text node - return new VText(''); -} + flatten: function(depth) { + return reify(this, flattenFactory(this, depth, false)); + }, -/** - * Create vtext from dom node - * - * @param Object el Text node - * @return Object VText - */ -function createVirtualTextNode(el) { - return new VText(el.nodeValue); -} + 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); + }, -/** - * 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; + has: function(index) { + index = wrapIndex(this, index); + return index >= 0 && (this.size !== undefined ? + this.size === Infinity || index < this.size : + this.indexOf(index) !== -1 + ); + }, - return new VNode( - el.tagName - , createProperties(el) - , createChildren(el, attr) - , key - , ns - ); -} + interpose: function(separator) { + return reify(this, interposeFactory(this, separator)); + }, -/** - * 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)); - }; + 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); + }, - return children; -} + keySeq: function() { + return Range(0, this.size); + }, -/** - * Create properties from dom node - * - * @param Object el DOM element - * @return Object Node properties and attributes - */ -function createProperties(el) { - var properties = {}; + last: function() { + return this.get(-1); + }, - if (!el.hasAttributes()) { - return properties; - } + skipWhile: function(predicate, context) { + return reify(this, skipWhileFactory(this, predicate, context, false)); + }, - var ns; - if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) { - ns = el.namespaceURI; - } + zip: function(/*, ...iterables */) { + var iterables = [this].concat(arrCopy(arguments)); + return reify(this, zipWithFactory(this, defaultZipper, iterables)); + }, - var attr; - for (var i = 0; i < el.attributes.length; i++) { - // use built in css style parsing - if(el.attributes[i].name == 'style'){ - attr = createStyleProperty(el); - } - else if (ns) { - attr = createPropertyNS(el.attributes[i]); - } else { - attr = createProperty(el.attributes[i]); - } + zipWith: function(zipper/*, ...iterables */) { + var iterables = arrCopy(arguments); + iterables[0] = this; + return reify(this, zipWithFactory(this, zipper, iterables)); + } - // 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; + IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; + IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; - // 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; + mixin(SetIterable, { - // 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 || name.indexOf('aria-') === 0) { - value = attr.value; - isAttr = true; - } else { - value = attr.value; - } + // ### ES6 Collection methods (ES6 Array and Map) - return { - name: name - , value: value - , isAttr: isAttr || false - }; -} + get: function(value, notSetValue) { + return this.has(value) ? value : notSetValue; + }, -/** - * Create namespaced property from dom attribute - * - * @param Object attr DOM attribute - * @return Object Normalized attribute - */ -function createPropertyNS(attr) { - var name, value; + includes: function(value) { + return this.has(value); + }, - return { - name: attr.name - , value: attr.value - , ns: namespaceMap[attr.name] || '' - }; -} -/** - * Create style property from dom node - * - * @param Object el DOM node - * @return Object Normalized attribute - */ -function createStyleProperty(el) { - 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, '') - } - } - return { name: 'style', value: output }; -} + // ### More sequential methods -},{"./namespace-map":116,"./property-map":117,"virtual-dom/vnode/vnode":147,"virtual-dom/vnode/vtext":149}],116:[function(require,module,exports){ + keySeq: function() { + return this.valueSeq(); + } -/** - * namespace-map.js - * - * Necessary to map svg attributes back to their namespace - */ + }); -'use strict'; + SetIterable.prototype.has = IterablePrototype.includes; + SetIterable.prototype.contains = SetIterable.prototype.includes; -// 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 + // 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) : String(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; + +})); +},{}],146:[function(require,module,exports){ +arguments[4][66][0].apply(exports,arguments) +},{"dup":66}],147:[function(require,module,exports){ +arguments[4][67][0].apply(exports,arguments) +},{"./index.js":146,"dup":67}],148:[function(require,module,exports){ +arguments[4][68][0].apply(exports,arguments) +},{"dup":68}],149:[function(require,module,exports){ +arguments[4][69][0].apply(exports,arguments) +},{"dup":69}],150:[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", + "rx": "^2.5.3", + "rxtween": "^0.3.3" + }, + "devDependencies": { + "babel": "^5.2.7", + "babel-cli": "^6.14.0", + "babel-preset-es2015": "^6.14.0", + "browserify": "10.1.3", + "less": "^2.5.0", + "uglify-js": "~2.4.21", + "watchify": "~3.2.1" + }, + "scripts": { + "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src && rm -f node_modules/rxmarbles node_modules/package.json ignore/es5src/node_modules", + "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json && ln -s ../../node_modules ignore/es5src/node_modules", + "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" + } +} + +},{}],151:[function(require,module,exports){ +arguments[4][70][0].apply(exports,arguments) +},{"dup":70,"sentence-case":423}],152:[function(require,module,exports){ +arguments[4][71][0].apply(exports,arguments) +},{"_process":510,"dup":71}],153:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "rx@^2.5.3", + "scope": null, + "escapedName": "rx", + "name": "rx", + "rawSpec": "^2.5.3", + "spec": ">=2.5.3 <3.0.0", + "type": "range" + }, + "/Users/hba21580/Dropbox/Afstuderen/rxmarbles" + ] + ], + "_from": "rx@>=2.5.3 <3.0.0", + "_id": "rx@2.5.3", + "_inCache": true, + "_installable": true, + "_location": "/rx", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + }, + "_npmVersion": "2.7.4", + "_phantomChildren": {}, + "_requested": { + "raw": "rx@^2.5.3", + "scope": null, + "escapedName": "rx", + "name": "rx", + "rawSpec": "^2.5.3", + "spec": ">=2.5.3 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/", + "/@cycle/core" + ], + "_resolved": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz", + "_shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", + "_shrinkwrap": null, + "_spec": "rx@^2.5.3", + "_where": "/Users/hba21580/Dropbox/Afstuderen/rxmarbles", + "author": { + "name": "Cloud Programmability Team", + "url": "https://github.com/Reactive-Extensions/RxJS/blob/master/authors.txt" + }, + "browser": { + "index.js": "dist/rx.all.js" + }, + "bugs": { + "url": "https://github.com/Reactive-Extensions/RxJS/issues" + }, + "dependencies": {}, + "description": "Library for composing asynchronous and event-based operations in JavaScript", + "devDependencies": { + "benchmark": "*", + "grunt": "*", + "grunt-cli": "*", + "grunt-contrib-concat": "*", + "grunt-contrib-connect": "*", + "grunt-contrib-copy": "*", + "grunt-contrib-jshint": "*", + "grunt-contrib-qunit": "*", + "grunt-contrib-uglify": "*", + "grunt-contrib-watch": "*", + "grunt-jscs": "*", + "grunt-saucelabs": "*", + "load-grunt-tasks": "*" + }, + "directories": {}, + "dist": { + "shasum": "21adc7d80f02002af50dae97fd9dbf248755f566", + "tarball": "https://registry.npmjs.org/rx/-/rx-2.5.3.tgz" + }, + "gitHead": "6507118725e93498f7a52a603acf679e472f47b7", + "homepage": "https://github.com/Reactive-Extensions/RxJS", + "jam": { + "main": "dist/rx.all.js" + }, + "keywords": [ + "LINQ", + "FRP", + "Reactive", + "Events", + "Rx", + "RxJS" + ], + "license": "Apache-2.0", + "main": "index.js", + "maintainers": [ + { + "name": "vvilhonen", + "email": "vesa@vilhonen.com" + }, + { + "name": "mattpodwysocki", + "email": "matthew.podwysocki@gmail.com" + } + ], + "name": "rx", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/Reactive-Extensions/RxJS.git" + }, + "scripts": { + "test": "grunt" + }, + "title": "Reactive Extensions for JavaScript (RxJS)", + "version": "2.5.3" +} + +},{}],154:[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 _core = require('@cycle/core'); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var mouseMove$ = _core.Rx.Observable.fromEvent(document, 'mousemove'); +var mouseUp$ = _core.Rx.Observable.fromEvent(document, 'mouseup'); + +function getPxToPercentageRatio(element) { + var pxToPercentage = void 0; + 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":160,"immutable":225}],155:[function(require,module,exports){ +'use strict'; + +var _core = 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) { + var newEnd = diagramData.get('end') + endDelta; + return diagramData.set('end', newEnd).set('eventualEnd', newEnd); +} + +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).set('eventualEnd', 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$ = _core.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), + isCompact$: props.get('compact').startWith(false) + }; +} + +module.exports = diagramModel; +},{"@cycle/core":160}],156:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +var _core = require('@cycle/core'); + +var _dom = require('@cycle/dom'); + +var _colors = require('rxmarbles/styles/colors'); + +var _colors2 = _interopRequireDefault(_colors); + +var _dimens = require('rxmarbles/styles/dimens'); + +var _dimens2 = _interopRequireDefault(_dimens); + +var _fonts = require('rxmarbles/styles/fonts'); + +var _fonts2 = _interopRequireDefault(_fonts); + +var _rxtween = require('rxtween'); + +var _rxtween2 = _interopRequireDefault(_rxtween); + +var _utils = require('rxmarbles/styles/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MARBLE_WIDTH = 5; // estimate of a marble width, in percentages +var diagramSidePadding = _dimens2.default.spaceMedium; +var diagramArrowThickness = '2px'; +var diagramArrowSidePadding = _dimens2.default.spaceLarge; +var diagramArrowHeadSize = '8px'; +var diagramArrowColor = _colors2.default.black; +var diagramArrowColorGhost = _colors2.default.almostWhite; +var diagramMarbleSize = _dimens2.default.spaceLarge; +var diagramCompletionHeight = '44px'; + +function diagramVerticalMargin(isCompact) { + return isCompact ? _dimens2.default.spaceSmall : _dimens2.default.spaceLarge; +} + +function diagramStyle(isCompact) { + return (0, _utils.mergeStyles)({ + position: 'relative', + display: 'block', + width: '100%', + height: 'calc(' + diagramMarbleSize + ' + 2 * ' + diagramVerticalMargin(isCompact) + ')', + overflow: 'visible', + cursor: 'default' + }, _utils.textUnselectable); +} + +var paddingToTimeline = '(' + diagramArrowSidePadding + ' + ' + diagramSidePadding + ' + (' + diagramMarbleSize + ' / 2))'; +var timelineSize = '(100% - (2 * ' + paddingToTimeline + '))'; +function timeLeftPosition(time) { + return '(' + paddingToTimeline + ' + (' + timelineSize + ' * ' + time / 100 + '))'; +} +function timeRightPosition(time) { + return '(' + paddingToTimeline + ' + (' + timelineSize + ' * ' + (100 - time) / 100 + '))'; +} + +function diagramBodyStyle(isCompact) { + return { + position: 'absolute', + left: 'calc(' + paddingToTimeline + ')', + right: 'calc(' + paddingToTimeline + ')', + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2))', + height: diagramCompletionHeight, + marginTop: 'calc(0px - (' + diagramCompletionHeight + ' / 2))' + }; +} + +function renderMarble(marbleData) { + var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + var isGhost = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + + return (0, _dom.h)('x-marble.diagramMarble', { + key: 'marble' + marbleData.get('id'), + data: marbleData, + isDraggable: isDraggable, + style: { size: diagramMarbleSize }, + isGhost: isGhost + }); +} + +function renderEndpoints(diagramData) { + var isDraggable = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var endpoints = [renderEndpoint(diagramData, 'start', 'diagramStart', false, false), renderEndpoint(diagramData, 'end', 'diagramCompletion', isDraggable, false)]; + + // add the eventualEndpoint if it is past the actyal end + if (diagramData.get('eventualEnd') > diagramData.get('end')) { + endpoints.push(renderEndpoint(diagramData, 'eventualEnd', 'diagramEventualEnd', false, true)); + } + + return endpoints; +} + +function renderEndpoint(diagramData, timeName, endpointType, isDraggable, isGhost) { + var endTime = diagramData.get(timeName); + // do not render if the time is not defined, or it was at the end of our simulation + if (endTime === undefined || endTime >= 100) { + return undefined; + } + + var color = isGhost ? diagramArrowColorGhost : diagramArrowColor; + + var isTall = diagramData.get('notifications').some(function (marbleData) { + return Math.abs(marbleData.get('time') - endTime) <= MARBLE_WIDTH * 0.5; + }); + return (0, _dom.h)('x-diagram-completion.' + endpointType, { + key: endpointType, + time: endTime, + isDraggable: isDraggable, + isTall: isTall, + style: { + thickness: diagramArrowThickness, + color: color, + height: diagramCompletionHeight + } + }); +} + +function renderDiagramArrow(data, isCompact) { + /* render the line in 3 segments: + * - to the left of 'start' render ghosted + * - render between start & end normal + * - to the right of 'end' render ghosted + */ + var arrowStyle = { + height: diagramArrowThickness, + position: 'absolute', + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2))' + }; + var sections = []; + var start = data.get('start'); + var end = data.get('end'); + var middleStart = diagramSidePadding; + var middleEnd = diagramSidePadding; + + sections.push((0, _dom.h)('div.diagramArrow', { + style: (0, _utils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: middleStart, + right: 'calc(' + timeRightPosition(start) + ')' + }) + })); + middleStart = 'calc(' + timeLeftPosition(start) + ')'; + + if (end < 100) { + sections.push((0, _dom.h)('div.diagramArrow', { + style: (0, _utils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColorGhost, + left: 'calc(' + timeLeftPosition(end) + ')', + right: middleEnd + }) + })); + middleEnd = 'calc(' + timeRightPosition(end) + ')'; + } + + if (start < end) { + sections.push((0, _dom.h)('div.diagramArrow', { + style: (0, _utils.mergeStyles)(arrowStyle, { + backgroundColor: diagramArrowColor, + left: middleStart, + right: middleEnd + }) + })); + } + + return sections; +} + +function renderDiagramArrowHead(data, isCompact) { + var end = data.get('end'); + var isGhost = end < 100; + var color = isGhost ? diagramArrowColorGhost : diagramArrowColor; + return (0, _dom.h)('div.diagramArrowHead', { style: { + width: 0, + height: 0, + borderTop: diagramArrowHeadSize + ' solid transparent', + borderBottom: diagramArrowHeadSize + ' solid transparent', + borderLeft: 'calc(2 * ' + diagramArrowHeadSize + ') solid ' + color, + display: 'inline-block', + right: 'calc(' + diagramSidePadding + ' - 1px)', + position: 'absolute', + top: 'calc(' + diagramVerticalMargin(isCompact) + ' + (' + diagramMarbleSize + ' / 2)\n - ' + diagramArrowHeadSize + ' + (' + diagramArrowThickness + ' / 2))' + } }); +} + +function renderDiagram(data, isInteractive, isCompact) { + var marblesVTree = data.get('notifications').map(function (notification) { + return renderMarble(notification, isInteractive, notification.get('time') > data.get('end') + 0.01); + }).toArray(); // from Immutable.List + return (0, _dom.h)('div', { style: diagramStyle(isCompact) }, [renderDiagramArrow(data, isCompact), renderDiagramArrowHead(data, isCompact), (0, _dom.h)('div', { style: diagramBodyStyle(isCompact) }, renderEndpoints(data, isInteractive).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 _core.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 === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }); +} + +function diagramView(model) { + return { + vtree$: _core.Rx.Observable.combineLatest(animateData$(model.data$).merge(model.newData$), model.isInteractive$, model.isCompact$, renderDiagram) + }; +} + +module.exports = diagramView; +},{"@cycle/core":160,"@cycle/dom":163,"rxmarbles/styles/colors":354,"rxmarbles/styles/dimens":355,"rxmarbles/styles/fonts":356,"rxmarbles/styles/utils":357,"rxtween":366}],157:[function(require,module,exports){ +'use strict'; + +var _core = require('@cycle/core'); + +var _utils = require('rxmarbles/components/sandbox/utils'); + +var _utils2 = _interopRequireDefault(_utils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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); + } +} /* + * Functions to handle data of input diagrams in the example shown in the + * sandbox. + */ + + +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', _utils2.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]; + var end = typeof last === 'number' ? last : 100; + return _immutable2.default.Map({ start: 0 }).set('notifications', getNotifications(diagram).map(function (notification) { + return prepareNotification(notification, indexInDiagramArray); + })).set('end', end).set('eventualEnd', end).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":160,"immutable":225,"rxmarbles/components/sandbox/utils":232}],158:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /* + * Functions to handle data of the output diagram in the example shown in the + * sandbox. + */ + + +var _core = require('@cycle/core'); + +var _utils = require('rxmarbles/components/sandbox/utils'); + +var _utils2 = _interopRequireDefault(_utils); + +var _immutable = require('immutable'); + +var _immutable2 = _interopRequireDefault(_immutable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var MAX_VT_TIME = 100; // Time of completion + +function makeScheduler() { + var scheduler = new _core.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; +} + +/** + * Creates an (virtual time) Rx.Observable from diagram + * data (array of data items). + */ +function toVTStream(diagramData, scheduler) { + return _core.Rx.Observable.create(function (observer) { + var notifications = diagramData.get('notifications').map(function (item) { + return scheduler.scheduleWithRelative(item.get('time'), function () { + return observer.onNext(item); + }); + }).toArray(); + var completion = scheduler.scheduleWithRelative(diagramData.get('end') + 0.01, function () { + return observer.onCompleted(); + }); + var s = new _core.Rx.CompositeDisposable(notifications); + s.add(completion); + return s; + }); +} + +/** + * Wraps the observable and collects usage information + * Each time the observable is subscribed, produces a notification stream that shows + * - when the subscription started + * - each notification produced + * - when the subscription ended + * - any remaining notifications that would have occurred had the subscription continued + * @param stream + * @param scheduler + * @param correctedMaxTime + */ +function observeUsage(stream, scheduler, correctedMaxTime) { + var subject = new _core.Rx.Subject(); + var diagrams = subject.takeUntilWithTime(new Date(correctedMaxTime), scheduler); + var newStream = _core.Rx.Observable.create(function (observer) { + var subscribeEnd = new _core.Rx.AsyncSubject(); + var onUnsubscribe = _core.Rx.Disposable.create(function () { + subscribeEnd.onNext(scheduler.now()); + subscribeEnd.onCompleted(); + }); + var p = stream.publish(); + var diagram = diagramStream(p, scheduler, correctedMaxTime); + var finalDiagram = diagram.combineLatest(subscribeEnd, function (diagram, e) { + // eventualEnd is when the stream would have finished had we not unsubscribed + diagram.eventualEnd = diagram.end; + + // end is when the observer unsubscribed (or the stream ended naturally) + diagram.end = e; + return diagram; + }); + + // Give the observer his information + p.subscribe(observer); + + // watch final diagram ourselves + subject.onNext(finalDiagram); + + // start the flow + p.connect(); + + return onUnsubscribe; + }); + + return { + diagrams: diagrams, + stream: newStream + }; +} + +function getObservedStreams(diagrams, scheduler, correctedMaxTime) { + var observedStreams = diagrams.get('diagrams').map(function (diagram) { + return toVTStream(diagram, scheduler); + }).map(function (s) { + return observeUsage(s, scheduler, correctedMaxTime); + }); + var inputStreams = observedStreams.map(function (s) { + return s.stream; + }); + // merge all the diagram streams such that we can keep a FIFO order on the final diagrams + var observedInputDiagramStream = _core.Rx.Observable.merge(observedStreams.map(function (s) { + return s.diagrams; + })).flatMap(function (d$, i) { + return d$.map(function (diag) { + return { diag: diag, i: i }; + }); + }).toArray().map(function (results) { + return results.sort(function (a, b) { + return a.i - b.i; + }).map(function (r) { + return r.diag; + }); + }).publishLast(); + observedInputDiagramStream.connect(); + var observedInputDiagrams = observedInputDiagramStream.startWith([]); + + return { inputStreams: inputStreams, observedInputDiagrams: observedInputDiagrams }; +} + +function diagramStream(stream, scheduler, correctedMaxTime) { + return _core.Rx.Observable.defer(function () { + var diagram = { start: scheduler.now() }; + return stream.observeOn(scheduler).timestamp(scheduler).takeUntilWithTime(new Date(correctedMaxTime), scheduler).map(function (x) { + if (_typeof(x.value) !== 'object') { + x.value = _immutable2.default.Map({ + content: x.value, + id: _utils2.default.calculateNotificationContentHash(x.value) + }); + } + // converts timestamp to % of MAX_VT_TIME + return x.value.set('time', x.timestamp / MAX_VT_TIME * 100); + }).catch(function (e) { + console.warn('Error in the diagram promise stream: ' + e); + return _core.Rx.Observable.empty(); + }).toArray().map(function (notifications) { + diagram.end = scheduler.now(); + diagram.notifications = notifications; + return diagram; + }); + }); +} + +function getDiagramPromise(stream, scheduler, correctedMaxTime) { + var s = diagramStream(stream, scheduler, correctedMaxTime).publishLast(); + s.connect(); + return s.startWith([]); +} + +function toImmutableDiagramData(diagramData) { + return _immutable2.default.Map({}).set('notifications', _immutable2.default.List(diagramData.notifications).map(_immutable2.default.Map)).set('end', diagramData.end).set('start', diagramData.start).set('eventualEnd', diagramData.eventualEnd || diagramData.end); +} + +function getOutputDiagram$(example$, inputDiagrams$) { + return inputDiagrams$.withLatestFrom(example$, function (diagrams, example) { + var vtscheduler = makeScheduler(); + // Necessary hack to include marbles at exactly 100.01 + var correctedMaxTime = MAX_VT_TIME + 0.02; + + var _getObservedStreams = getObservedStreams(diagrams, vtscheduler, correctedMaxTime); + + var inputStreams = _getObservedStreams.inputStreams; + var observedInputDiagrams = _getObservedStreams.observedInputDiagrams; + + var outputVTStream = example.get('apply')(inputStreams, vtscheduler); + var outputDiagram = getDiagramPromise(outputVTStream, vtscheduler, MAX_VT_TIME); + vtscheduler.start(); + + return outputDiagram.map(toImmutableDiagramData).zip(observedInputDiagrams.map(function (diagrams) { + return diagrams.map(toImmutableDiagramData); + }), function (od, ids) { + return { + outputDiagram: od, + observedInputDiagrams: ids + }; + }); + }).mergeAll(); +} + +module.exports = { + getOutputDiagram$: getOutputDiagram$ +}; +},{"@cycle/core":160,"immutable":225,"rxmarbles/components/sandbox/utils":232}],159:[function(require,module,exports){ +'use strict'; + +/* + * The database of all predefined examples in the app. + */ +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 < 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; +}; + +module.exports = 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")); +},{"rxmarbles/data/boolean-examples":233,"rxmarbles/data/combine-examples":234,"rxmarbles/data/conditional-examples":235,"rxmarbles/data/filter-examples":236,"rxmarbles/data/math-examples":237,"rxmarbles/data/transform-examples":238}],160:[function(require,module,exports){ +arguments[4][1][0].apply(exports,arguments) +},{"dup":1,"rx":231}],161:[function(require,module,exports){ +arguments[4][2][0].apply(exports,arguments) +},{"./render-dom":164,"@cycle/core":160,"dup":2}],162:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"./custom-element-widget":161,"dup":3,"es6-map":212}],163:[function(require,module,exports){ +arguments[4][4][0].apply(exports,arguments) +},{"./render-dom":164,"./render-html":165,"dup":4,"virtual-dom":381,"virtual-dom/virtual-hyperscript/svg":395}],164:[function(require,module,exports){ +arguments[4][5][0].apply(exports,arguments) +},{"./custom-elements":162,"@cycle/core":160,"dup":5,"vdom-parser":371,"virtual-dom":381,"virtual-dom/diff":379,"virtual-dom/patch":382}],165:[function(require,module,exports){ +arguments[4][6][0].apply(exports,arguments) +},{"./custom-element-widget":161,"./custom-elements":162,"@cycle/core":160,"dup":6,"vdom-to-html":375}],166:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],167:[function(require,module,exports){ +arguments[4][8][0].apply(exports,arguments) +},{"dup":8,"es5-ext/object/copy":180,"es5-ext/object/map":188,"es5-ext/object/valid-callable":194,"es5-ext/object/valid-value":195}],168:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"dup":9,"es5-ext/object/assign":177,"es5-ext/object/is-callable":183,"es5-ext/object/normalize-options":189,"es5-ext/string/#/contains":196}],169:[function(require,module,exports){ +arguments[4][10][0].apply(exports,arguments) +},{"../../object/valid-value":195,"dup":10}],170:[function(require,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"../../number/to-pos-integer":175,"../../object/valid-value":195,"dup":11}],171:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"./is-implemented":172,"./shim":173,"dup":12}],172:[function(require,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"dup":13}],173:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"dup":14}],174:[function(require,module,exports){ +arguments[4][15][0].apply(exports,arguments) +},{"../math/sign":171,"dup":15}],175:[function(require,module,exports){ +arguments[4][16][0].apply(exports,arguments) +},{"./to-integer":174,"dup":16}],176:[function(require,module,exports){ +arguments[4][17][0].apply(exports,arguments) +},{"./valid-callable":194,"./valid-value":195,"dup":17}],177:[function(require,module,exports){ +arguments[4][18][0].apply(exports,arguments) +},{"./is-implemented":178,"./shim":179,"dup":18}],178:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],179:[function(require,module,exports){ +arguments[4][20][0].apply(exports,arguments) +},{"../keys":185,"../valid-value":195,"dup":20}],180:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"./assign":177,"./valid-value":195,"dup":21}],181:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"./set-prototype-of/is-implemented":192,"./set-prototype-of/shim":193,"dup":22}],182:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"./_iterate":176,"dup":23}],183:[function(require,module,exports){ +arguments[4][24][0].apply(exports,arguments) +},{"dup":24}],184:[function(require,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"dup":25}],185:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"./is-implemented":186,"./shim":187,"dup":26}],186:[function(require,module,exports){ +arguments[4][27][0].apply(exports,arguments) +},{"dup":27}],187:[function(require,module,exports){ +arguments[4][28][0].apply(exports,arguments) +},{"dup":28}],188:[function(require,module,exports){ +arguments[4][29][0].apply(exports,arguments) +},{"./for-each":182,"./valid-callable":194,"dup":29}],189:[function(require,module,exports){ +arguments[4][30][0].apply(exports,arguments) +},{"dup":30}],190:[function(require,module,exports){ +arguments[4][31][0].apply(exports,arguments) +},{"dup":31}],191:[function(require,module,exports){ +arguments[4][32][0].apply(exports,arguments) +},{"./is-implemented":192,"./shim":193,"dup":32}],192:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],193:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"../create":181,"../is-object":184,"../valid-value":195,"dup":34}],194:[function(require,module,exports){ +arguments[4][35][0].apply(exports,arguments) +},{"dup":35}],195:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],196:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"./is-implemented":197,"./shim":198,"dup":37}],197:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"dup":38}],198:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"dup":39}],199:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"dup":40}],200:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"./":203,"d":168,"dup":41,"es5-ext/object/set-prototype-of":191,"es5-ext/string/#/contains":196}],201:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"./get":202,"dup":42,"es5-ext/object/valid-callable":194,"es5-ext/string/is-string":199}],202:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./array":200,"./string":210,"./valid-iterable":211,"dup":43,"es5-ext/string/is-string":199,"es6-symbol":205}],203:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"d":168,"d/auto-bind":167,"dup":44,"es5-ext/array/#/clear":169,"es5-ext/object/assign":177,"es5-ext/object/valid-callable":194,"es5-ext/object/valid-value":195,"es6-symbol":205}],204:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"dup":45,"es5-ext/string/is-string":199,"es6-symbol":205}],205:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":206,"./polyfill":208,"dup":46}],206:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"dup":47}],207:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"dup":48}],208:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"./validate-symbol":209,"d":168,"dup":49}],209:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./is-symbol":207,"dup":50}],210:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"./":203,"d":168,"dup":51,"es5-ext/object/set-prototype-of":191}],211:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"./is-iterable":204,"dup":52}],212:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"./is-implemented":213,"./polyfill":217,"dup":53}],213:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54}],214:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],215:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56,"es5-ext/object/primitive-set":190}],216:[function(require,module,exports){ +arguments[4][57][0].apply(exports,arguments) +},{"./iterator-kinds":215,"d":168,"dup":57,"es5-ext/object/set-prototype-of":191,"es6-iterator":203,"es6-symbol":218}],217:[function(require,module,exports){ +arguments[4][58][0].apply(exports,arguments) +},{"./is-native-implemented":214,"./lib/iterator":216,"d":168,"dup":58,"es5-ext/array/#/clear":169,"es5-ext/array/#/e-index-of":170,"es5-ext/object/set-prototype-of":191,"es5-ext/object/valid-callable":194,"es5-ext/object/valid-value":195,"es6-iterator/for-of":201,"es6-iterator/valid-iterable":211,"es6-symbol":218,"event-emitter":223}],218:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":219,"./polyfill":220,"dup":46}],219:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],220:[function(require,module,exports){ +arguments[4][61][0].apply(exports,arguments) +},{"d":168,"dup":61}],221:[function(require,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"dup":62}],222:[function(require,module,exports){ +arguments[4][63][0].apply(exports,arguments) +},{"dup":63,"individual/one-version":227}],223:[function(require,module,exports){ +arguments[4][64][0].apply(exports,arguments) +},{"d":168,"dup":64,"es5-ext/object/valid-callable":194}],224:[function(require,module,exports){ +arguments[4][65][0].apply(exports,arguments) +},{"dup":65,"min-document":509}],225:[function(require,module,exports){ +arguments[4][145][0].apply(exports,arguments) +},{"dup":145}],226:[function(require,module,exports){ +arguments[4][66][0].apply(exports,arguments) +},{"dup":66}],227:[function(require,module,exports){ +arguments[4][67][0].apply(exports,arguments) +},{"./index.js":226,"dup":67}],228:[function(require,module,exports){ +arguments[4][68][0].apply(exports,arguments) +},{"dup":68}],229:[function(require,module,exports){ +arguments[4][69][0].apply(exports,arguments) +},{"dup":69}],230:[function(require,module,exports){ +arguments[4][70][0].apply(exports,arguments) +},{"dup":70,"sentence-case":367}],231:[function(require,module,exports){ +arguments[4][71][0].apply(exports,arguments) +},{"_process":510,"dup":71}],232:[function(require,module,exports){ +"use strict"; + +/* + * Conversion from virtual time streams out to diagram data, and + * vice-versa, and related functions. + */ + +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 +}; +},{}],233:[function(require,module,exports){ +"use strict"; + +var _core = 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":239}],234:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.Rx.Observable.combineLatest(inputs[0], inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + }, + + "concat": { + "label": "concat(a, b)", + "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 _core.Rx.Observable.concat(inputs); + } + }, + + "merge": { + "label": "merge(a, b)", + "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 _core.Rx.Observable.merge(inputs); + } + }, + + "sample": { + "label": "a.sample(b)", + "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": "xs.withLatestFrom(ys, (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(xs, ys, (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" }, 70]], + "apply": function apply(inputs) { + return _core.Rx.Observable.zip(inputs[0], inputs[1], function (x, y) { + return "" + x.get('content') + y.get('content'); + }); + } + } +}; +},{"@cycle/core":239}],235:[function(require,module,exports){ +"use strict"; + +var _core = require("@cycle/core"); + +module.exports = { + "amb": { + "label": "amb(a, b, c)", + "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 _core.Rx.Observable.amb(inputs); + } + }, + + "repeat": { + "label": "a.repeat()", + "inputs": [[{ t: 5, d: 1 }, { t: 10, d: 2 }, { t: 20, d: 3 }, 35]], + "apply": function apply(inputs) { + return inputs[0].repeat(); + } + } +}; +},{"@cycle/core":239}],236:[function(require,module,exports){ +"use strict"; + +var _core = 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": "a.publish(p => p.pausable(signal))", + "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 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get('content'); + }); + return inputs[0].publish(function (p) { + return p.pausable(signal); + }); + } + }, + + "pausable(cold)": { + "label": "a.pausable(signal)", + "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 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get('content'); + }); + return inputs[0].pausable(signal); + } + }, + + "pausableBuffered": { + "label": "a.publish(p => p.pausableBuffered(signal))", + "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 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get('content'); + }); + return inputs[0].publish(function (p) { + return p.pausableBuffered(signal); + }); + } + }, + + "pausableBuffered(cold)": { + "label": "a.pausableBuffered(signal)", + "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 }, 85], [{ t: 15, d: true }, { t: 35, d: false }, { t: 55, d: true }, 70]], + "apply": function apply(inputs) { + var signal = inputs[1].map(function (x) { + return x.get('content'); + }); + return inputs[0].pausableBuffered(signal); + } + }, + + "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 }, 80]], + "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 }, 80]], + "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":239}],237:[function(require,module,exports){ +"use strict"; + +var _core = 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":239}],238:[function(require,module,exports){ +"use strict"; + +var _core = 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 _core.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 _core.Rx.Observable.timer(Number(x.get('content')) * 10, 1000, scheduler); + }); + } + } +}; +},{"@cycle/core":239}],239:[function(require,module,exports){ +arguments[4][1][0].apply(exports,arguments) +},{"dup":1,"rx":310}],240:[function(require,module,exports){ +arguments[4][2][0].apply(exports,arguments) +},{"./render-dom":243,"@cycle/core":239,"dup":2}],241:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"./custom-element-widget":240,"dup":3,"es6-map":291}],242:[function(require,module,exports){ +arguments[4][4][0].apply(exports,arguments) +},{"./render-dom":243,"./render-html":244,"dup":4,"virtual-dom":325,"virtual-dom/virtual-hyperscript/svg":339}],243:[function(require,module,exports){ +arguments[4][5][0].apply(exports,arguments) +},{"./custom-elements":241,"@cycle/core":239,"dup":5,"vdom-parser":315,"virtual-dom":325,"virtual-dom/diff":323,"virtual-dom/patch":326}],244:[function(require,module,exports){ +arguments[4][6][0].apply(exports,arguments) +},{"./custom-element-widget":240,"./custom-elements":241,"@cycle/core":239,"dup":6,"vdom-to-html":319}],245:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],246:[function(require,module,exports){ +arguments[4][8][0].apply(exports,arguments) +},{"dup":8,"es5-ext/object/copy":259,"es5-ext/object/map":267,"es5-ext/object/valid-callable":273,"es5-ext/object/valid-value":274}],247:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"dup":9,"es5-ext/object/assign":256,"es5-ext/object/is-callable":262,"es5-ext/object/normalize-options":268,"es5-ext/string/#/contains":275}],248:[function(require,module,exports){ +arguments[4][10][0].apply(exports,arguments) +},{"../../object/valid-value":274,"dup":10}],249:[function(require,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"../../number/to-pos-integer":254,"../../object/valid-value":274,"dup":11}],250:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"./is-implemented":251,"./shim":252,"dup":12}],251:[function(require,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"dup":13}],252:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"dup":14}],253:[function(require,module,exports){ +arguments[4][15][0].apply(exports,arguments) +},{"../math/sign":250,"dup":15}],254:[function(require,module,exports){ +arguments[4][16][0].apply(exports,arguments) +},{"./to-integer":253,"dup":16}],255:[function(require,module,exports){ +arguments[4][17][0].apply(exports,arguments) +},{"./valid-callable":273,"./valid-value":274,"dup":17}],256:[function(require,module,exports){ +arguments[4][18][0].apply(exports,arguments) +},{"./is-implemented":257,"./shim":258,"dup":18}],257:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],258:[function(require,module,exports){ +arguments[4][20][0].apply(exports,arguments) +},{"../keys":264,"../valid-value":274,"dup":20}],259:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"./assign":256,"./valid-value":274,"dup":21}],260:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"./set-prototype-of/is-implemented":271,"./set-prototype-of/shim":272,"dup":22}],261:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"./_iterate":255,"dup":23}],262:[function(require,module,exports){ +arguments[4][24][0].apply(exports,arguments) +},{"dup":24}],263:[function(require,module,exports){ +arguments[4][25][0].apply(exports,arguments) +},{"dup":25}],264:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"./is-implemented":265,"./shim":266,"dup":26}],265:[function(require,module,exports){ +arguments[4][27][0].apply(exports,arguments) +},{"dup":27}],266:[function(require,module,exports){ +arguments[4][28][0].apply(exports,arguments) +},{"dup":28}],267:[function(require,module,exports){ +arguments[4][29][0].apply(exports,arguments) +},{"./for-each":261,"./valid-callable":273,"dup":29}],268:[function(require,module,exports){ +arguments[4][30][0].apply(exports,arguments) +},{"dup":30}],269:[function(require,module,exports){ +arguments[4][31][0].apply(exports,arguments) +},{"dup":31}],270:[function(require,module,exports){ +arguments[4][32][0].apply(exports,arguments) +},{"./is-implemented":271,"./shim":272,"dup":32}],271:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],272:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"../create":260,"../is-object":263,"../valid-value":274,"dup":34}],273:[function(require,module,exports){ +arguments[4][35][0].apply(exports,arguments) +},{"dup":35}],274:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],275:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"./is-implemented":276,"./shim":277,"dup":37}],276:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"dup":38}],277:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"dup":39}],278:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"dup":40}],279:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"./":282,"d":247,"dup":41,"es5-ext/object/set-prototype-of":270,"es5-ext/string/#/contains":275}],280:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"./get":281,"dup":42,"es5-ext/object/valid-callable":273,"es5-ext/string/is-string":278}],281:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./array":279,"./string":289,"./valid-iterable":290,"dup":43,"es5-ext/string/is-string":278,"es6-symbol":284}],282:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"d":247,"d/auto-bind":246,"dup":44,"es5-ext/array/#/clear":248,"es5-ext/object/assign":256,"es5-ext/object/valid-callable":273,"es5-ext/object/valid-value":274,"es6-symbol":284}],283:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"dup":45,"es5-ext/string/is-string":278,"es6-symbol":284}],284:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":285,"./polyfill":287,"dup":46}],285:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"dup":47}],286:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"dup":48}],287:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"./validate-symbol":288,"d":247,"dup":49}],288:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./is-symbol":286,"dup":50}],289:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"./":282,"d":247,"dup":51,"es5-ext/object/set-prototype-of":270}],290:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"./is-iterable":283,"dup":52}],291:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"./is-implemented":292,"./polyfill":296,"dup":53}],292:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54}],293:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],294:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56,"es5-ext/object/primitive-set":269}],295:[function(require,module,exports){ +arguments[4][57][0].apply(exports,arguments) +},{"./iterator-kinds":294,"d":247,"dup":57,"es5-ext/object/set-prototype-of":270,"es6-iterator":282,"es6-symbol":297}],296:[function(require,module,exports){ +arguments[4][58][0].apply(exports,arguments) +},{"./is-native-implemented":293,"./lib/iterator":295,"d":247,"dup":58,"es5-ext/array/#/clear":248,"es5-ext/array/#/e-index-of":249,"es5-ext/object/set-prototype-of":270,"es5-ext/object/valid-callable":273,"es5-ext/object/valid-value":274,"es6-iterator/for-of":280,"es6-iterator/valid-iterable":290,"es6-symbol":297,"event-emitter":302}],297:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"./is-implemented":298,"./polyfill":299,"dup":46}],298:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],299:[function(require,module,exports){ +arguments[4][61][0].apply(exports,arguments) +},{"d":247,"dup":61}],300:[function(require,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"dup":62}],301:[function(require,module,exports){ +arguments[4][63][0].apply(exports,arguments) +},{"dup":63,"individual/one-version":306}],302:[function(require,module,exports){ +arguments[4][64][0].apply(exports,arguments) +},{"d":247,"dup":64,"es5-ext/object/valid-callable":273}],303:[function(require,module,exports){ +arguments[4][65][0].apply(exports,arguments) +},{"dup":65,"min-document":509}],304:[function(require,module,exports){ +arguments[4][145][0].apply(exports,arguments) +},{"dup":145}],305:[function(require,module,exports){ +arguments[4][66][0].apply(exports,arguments) +},{"dup":66}],306:[function(require,module,exports){ +arguments[4][67][0].apply(exports,arguments) +},{"./index.js":305,"dup":67}],307:[function(require,module,exports){ +arguments[4][68][0].apply(exports,arguments) +},{"dup":68}],308:[function(require,module,exports){ +arguments[4][69][0].apply(exports,arguments) +},{"dup":69}],309:[function(require,module,exports){ +arguments[4][70][0].apply(exports,arguments) +},{"dup":70,"sentence-case":311}],310:[function(require,module,exports){ +arguments[4][71][0].apply(exports,arguments) +},{"_process":510,"dup":71}],311:[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":312,"./vendor/non-word-regexp":313,"./vendor/trailing-digit-regexp":314,"lower-case":308}],312:[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 + +},{}],313:[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 + +},{}],314:[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 + +},{}],315:[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'){ + attr = createStyleProperty(el); + } + 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 || name.indexOf('aria-') === 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] || '' + }; +} + +/** + * Create style property from dom node + * + * @param Object el DOM node + * @return Object Normalized attribute + */ +function createStyleProperty(el) { + 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, '') + } + } + return { name: 'style', value: output }; +} + +},{"./namespace-map":316,"./property-map":317,"virtual-dom/vnode/vnode":347,"virtual-dom/vnode/vtext":349}],316:[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 @@ -21317,7 +21350,7 @@ var namespaces = { module.exports = namespaces; -},{}],117:[function(require,module,exports){ +},{}],317:[function(require,module,exports){ /** * property-map.js @@ -21455,7 +21488,7 @@ var properties = { module.exports = properties; -},{}],118:[function(require,module,exports){ +},{}],318:[function(require,module,exports){ var escape = require('escape-html'); var propConfig = require('./property-config'); var types = propConfig.attributeTypes; @@ -21525,7 +21558,7 @@ function memoizeString(callback) { } }; } -},{"./property-config":120,"escape-html":90}],119:[function(require,module,exports){ +},{"./property-config":320,"escape-html":300}],319:[function(require,module,exports){ var escape = require('escape-html'); var extend = require('xtend'); var isVNode = require('virtual-dom/vnode/is-vnode'); @@ -21626,7 +21659,7 @@ function closeTag(node) { return voidElements[tag] ? '' : ''; } -},{"./create-attribute":118,"./void-elements":121,"escape-html":90,"param-case":99,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":133,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":135,"virtual-dom/vnode/is-thunk":141,"virtual-dom/vnode/is-vnode":143,"virtual-dom/vnode/is-vtext":144,"virtual-dom/vnode/is-widget":145,"xtend":153}],120:[function(require,module,exports){ +},{"./create-attribute":318,"./void-elements":321,"escape-html":300,"param-case":309,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":333,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":335,"virtual-dom/vnode/is-thunk":341,"virtual-dom/vnode/is-vnode":343,"virtual-dom/vnode/is-vtext":344,"virtual-dom/vnode/is-widget":345,"xtend":353}],320:[function(require,module,exports){ /** * Attribute types. */ @@ -21788,7 +21821,7 @@ module.exports = { properties: properties, attributeNames: attributeNames }; -},{}],121:[function(require,module,exports){ +},{}],321:[function(require,module,exports){ /** * Void elements. @@ -21813,22 +21846,22 @@ module.exports = { 'track': true, 'wbr': true }; -},{}],122:[function(require,module,exports){ +},{}],322:[function(require,module,exports){ var createElement = require("./vdom/create-element.js") module.exports = createElement -},{"./vdom/create-element.js":128}],123:[function(require,module,exports){ +},{"./vdom/create-element.js":328}],323:[function(require,module,exports){ var diff = require("./vtree/diff.js") module.exports = diff -},{"./vtree/diff.js":151}],124:[function(require,module,exports){ +},{"./vtree/diff.js":351}],324:[function(require,module,exports){ var h = require("./virtual-hyperscript/index.js") module.exports = h -},{"./virtual-hyperscript/index.js":136}],125:[function(require,module,exports){ +},{"./virtual-hyperscript/index.js":336}],325:[function(require,module,exports){ var diff = require("./diff.js") var patch = require("./patch.js") var h = require("./h.js") @@ -21845,12 +21878,12 @@ module.exports = { VText: VText } -},{"./create-element.js":122,"./diff.js":123,"./h.js":124,"./patch.js":126,"./vnode/vnode.js":147,"./vnode/vtext.js":149}],126:[function(require,module,exports){ +},{"./create-element.js":322,"./diff.js":323,"./h.js":324,"./patch.js":326,"./vnode/vnode.js":347,"./vnode/vtext.js":349}],326:[function(require,module,exports){ var patch = require("./vdom/patch.js") module.exports = patch -},{"./vdom/patch.js":131}],127:[function(require,module,exports){ +},{"./vdom/patch.js":331}],327:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook.js") @@ -21949,7 +21982,7 @@ function getPrototype(value) { } } -},{"../vnode/is-vhook.js":142,"is-object":97}],128:[function(require,module,exports){ +},{"../vnode/is-vhook.js":342,"is-object":307}],328:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") @@ -21997,7 +22030,7 @@ function createElement(vnode, opts) { return node } -},{"../vnode/handle-thunk.js":140,"../vnode/is-vnode.js":143,"../vnode/is-vtext.js":144,"../vnode/is-widget.js":145,"./apply-properties":127,"global/document":93}],129:[function(require,module,exports){ +},{"../vnode/handle-thunk.js":340,"../vnode/is-vnode.js":343,"../vnode/is-vtext.js":344,"../vnode/is-widget.js":345,"./apply-properties":327,"global/document":303}],329:[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. @@ -22084,7 +22117,7 @@ function ascending(a, b) { return a > b ? 1 : -1 } -},{}],130:[function(require,module,exports){ +},{}],330:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("../vnode/is-widget.js") @@ -22237,7 +22270,7 @@ function replaceRoot(oldRoot, newRoot) { return newRoot; } -},{"../vnode/is-widget.js":145,"../vnode/vpatch.js":148,"./apply-properties":127,"./update-widget":132}],131:[function(require,module,exports){ +},{"../vnode/is-widget.js":345,"../vnode/vpatch.js":348,"./apply-properties":327,"./update-widget":332}],331:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") @@ -22317,7 +22350,7 @@ function patchIndices(patches) { return indices } -},{"./create-element":128,"./dom-index":129,"./patch-op":130,"global/document":93,"x-is-array":152}],132:[function(require,module,exports){ +},{"./create-element":328,"./dom-index":329,"./patch-op":330,"global/document":303,"x-is-array":352}],332:[function(require,module,exports){ var isWidget = require("../vnode/is-widget.js") module.exports = updateWidget @@ -22334,7 +22367,7 @@ function updateWidget(a, b) { return false } -},{"../vnode/is-widget.js":145}],133:[function(require,module,exports){ +},{"../vnode/is-widget.js":345}],333:[function(require,module,exports){ 'use strict'; module.exports = AttributeHook; @@ -22371,7 +22404,7 @@ AttributeHook.prototype.unhook = function (node, prop, next) { AttributeHook.prototype.type = 'AttributeHook'; -},{}],134:[function(require,module,exports){ +},{}],334:[function(require,module,exports){ 'use strict'; var EvStore = require('ev-store'); @@ -22400,7 +22433,7 @@ EvHook.prototype.unhook = function(node, propertyName) { es[propName] = undefined; }; -},{"ev-store":91}],135:[function(require,module,exports){ +},{"ev-store":301}],335:[function(require,module,exports){ 'use strict'; module.exports = SoftSetHook; @@ -22419,7 +22452,7 @@ SoftSetHook.prototype.hook = function (node, propertyName) { } }; -},{}],136:[function(require,module,exports){ +},{}],336:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); @@ -22558,7 +22591,7 @@ function errorString(obj) { } } -},{"../vnode/is-thunk":141,"../vnode/is-vhook":142,"../vnode/is-vnode":143,"../vnode/is-vtext":144,"../vnode/is-widget":145,"../vnode/vnode.js":147,"../vnode/vtext.js":149,"./hooks/ev-hook.js":134,"./hooks/soft-set-hook.js":135,"./parse-tag.js":137,"x-is-array":152}],137:[function(require,module,exports){ +},{"../vnode/is-thunk":341,"../vnode/is-vhook":342,"../vnode/is-vnode":343,"../vnode/is-vtext":344,"../vnode/is-widget":345,"../vnode/vnode.js":347,"../vnode/vtext.js":349,"./hooks/ev-hook.js":334,"./hooks/soft-set-hook.js":335,"./parse-tag.js":337,"x-is-array":352}],337:[function(require,module,exports){ 'use strict'; var split = require('browser-split'); @@ -22614,7 +22647,7 @@ function parseTag(tag, props) { return props.namespace ? tagName : tagName.toUpperCase(); } -},{"browser-split":35}],138:[function(require,module,exports){ +},{"browser-split":245}],338:[function(require,module,exports){ 'use strict'; var DEFAULT_NAMESPACE = null; @@ -22921,841 +22954,1758 @@ var SVG_PROPERTIES = { 'zoomAndPan': DEFAULT_NAMESPACE }; -module.exports = SVGAttributeNamespace; +module.exports = SVGAttributeNamespace; + +function SVGAttributeNamespace(value) { + if (SVG_PROPERTIES.hasOwnProperty(value)) { + return SVG_PROPERTIES[value]; + } +} + +},{}],339:[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":333,"./index.js":336,"./svg-attribute-namespace":338,"x-is-array":352}],340:[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":341,"./is-vnode":343,"./is-vtext":344,"./is-widget":345}],341:[function(require,module,exports){ +module.exports = isThunk + +function isThunk(t) { + return t && t.type === "Thunk" +} + +},{}],342:[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")) +} + +},{}],343:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualNode + +function isVirtualNode(x) { + return x && x.type === "VirtualNode" && x.version === version +} + +},{"./version":346}],344:[function(require,module,exports){ +var version = require("./version") + +module.exports = isVirtualText + +function isVirtualText(x) { + return x && x.type === "VirtualText" && x.version === version +} + +},{"./version":346}],345:[function(require,module,exports){ +module.exports = isWidget + +function isWidget(w) { + return w && w.type === "Widget" +} + +},{}],346:[function(require,module,exports){ +module.exports = "2" + +},{}],347:[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":341,"./is-vhook":342,"./is-vnode":343,"./is-widget":345,"./version":346}],348:[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":346}],349:[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":346}],350:[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":342,"is-object":307}],351:[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)) + } -function SVGAttributeNamespace(value) { - if (SVG_PROPERTIES.hasOwnProperty(value)) { - return SVG_PROPERTIES[value]; - } + if (apply) { + patch[index] = apply + } + + if (applyClear) { + clearState(a, patch, index) + } } -},{}],139:[function(require,module,exports){ -'use strict'; +function diffChildren(a, b, patch, apply, index) { + var aChildren = a.children + var orderedSet = reorder(aChildren, b.children) + var bChildren = orderedSet.children -var isArray = require('x-is-array'); + var aLen = aChildren.length + var bLen = bChildren.length + var len = aLen > bLen ? aLen : bLen -var h = require('./index.js'); + 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) + } -var SVGAttributeNamespace = require('./svg-attribute-namespace'); -var attributeHook = require('./hooks/attribute-hook'); + if (isVNode(leftNode) && leftNode.count) { + index += leftNode.count + } + } -var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; + if (orderedSet.moves) { + // Reorder nodes last + apply = appendPatch(apply, new VPatch( + VPatch.ORDER, + a, + orderedSet.moves + )) + } -module.exports = svg; + return apply +} -function svg(tagName, properties, children) { - if (!children && isChildren(properties)) { - children = properties; - properties = {}; +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) } +} - properties = properties || {}; +// 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) + } +} - // set namespace for svg - properties.namespace = SVG_NAMESPACE; +function hasPatches(patch) { + for (var index in patch) { + if (index !== "a") { + return true + } + } - var attributes = properties.attributes || (properties.attributes = {}); + return false +} - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; +// 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) + ) + ) } - var namespace = SVGAttributeNamespace(key); + 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 - if (namespace === undefined) { // not a svg attribute - continue; + 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 - var value = properties[key]; + for (var k = 0; k < bChildren.length;) { + var wantedItem = bChildren[k] + simulateItem = simulate[simulateIndex] - if (typeof value !== 'string' && - typeof value !== 'number' && - typeof value !== 'boolean' - ) { - continue; + // remove items + while (simulateItem === null && simulate.length) { + removes.push(remove(simulate, simulateIndex, null)) + simulateItem = simulate[simulateIndex] } - if (namespace !== null) { // namespaced attribute - properties[key] = attributeHook(namespace, value); - continue; + 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++ } + } - attributes[key] = value - properties[key] = undefined + // remove all the remaining nodes from simulate + while(simulateIndex < simulate.length) { + simulateItem = simulate[simulateIndex] + removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) } - return h(tagName, properties, children); -} + // 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 + } + } -function isChildren(x) { - return typeof x === 'string' || isArray(x); + return { + children: newChildren, + moves: { + removes: removes, + inserts: inserts + } + } } -},{"./hooks/attribute-hook":133,"./index.js":136,"./svg-attribute-namespace":138,"x-is-array":152}],140:[function(require,module,exports){ -var isVNode = require("./is-vnode") -var isVText = require("./is-vtext") -var isWidget = require("./is-widget") -var isThunk = require("./is-thunk") +function remove(arr, index, key) { + arr.splice(index, 1) -module.exports = handleThunk + return { + from: index, + key: key + } +} -function handleThunk(a, b) { - var renderedA = a - var renderedB = b +function keyIndex(children) { + var keys = {} + var free = [] + var length = children.length - if (isThunk(b)) { - renderedB = renderThunk(b, a) - } + for (var i = 0; i < length; i++) { + var child = children[i] - if (isThunk(a)) { - renderedA = renderThunk(a, null) + if (child.key) { + keys[child.key] = i + } else { + free.push(i) + } } return { - a: renderedA, - b: renderedB + keys: keys, // A hash of key name to index + free: free // An array of unkeyed item indices } } -function renderThunk(thunk, previous) { - var renderedThunk = thunk.vnode +function appendPatch(apply, patch) { + if (apply) { + if (isArray(apply)) { + apply.push(patch) + } else { + apply = [apply, patch] + } - if (!renderedThunk) { - renderedThunk = thunk.vnode = thunk.render(previous) + return apply + } else { + return patch } +} - if (!(isVNode(renderedThunk) || - isVText(renderedThunk) || - isWidget(renderedThunk))) { - throw new Error("thunk did not return a valid node"); - } +},{"../vnode/handle-thunk":340,"../vnode/is-thunk":341,"../vnode/is-vnode":343,"../vnode/is-vtext":344,"../vnode/is-widget":345,"../vnode/vpatch":348,"./diff-props":350,"x-is-array":352}],352:[function(require,module,exports){ +var nativeIsArray = Array.isArray +var toString = Object.prototype.toString - return renderedThunk +module.exports = nativeIsArray || isArray + +function isArray(obj) { + return toString.call(obj) === "[object Array]" } -},{"./is-thunk":141,"./is-vnode":143,"./is-vtext":144,"./is-widget":145}],141:[function(require,module,exports){ -module.exports = isThunk - -function isThunk(t) { - return t && t.type === "Thunk" -} +},{}],353:[function(require,module,exports){ +module.exports = extend -},{}],142:[function(require,module,exports){ -module.exports = isHook +var hasOwnProperty = Object.prototype.hasOwnProperty; -function isHook(hook) { - return hook && - (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") || - typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook")) -} +function extend() { + var target = {} -},{}],143:[function(require,module,exports){ -var version = require("./version") + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] -module.exports = isVirtualNode + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } -function isVirtualNode(x) { - return x && x.type === "VirtualNode" && x.version === version + return target } -},{"./version":146}],144:[function(require,module,exports){ -var version = require("./version") +},{}],354:[function(require,module,exports){ +'use strict'; -module.exports = isVirtualText +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' +}; +},{}],355:[function(require,module,exports){ +'use strict'; -function isVirtualText(x) { - return x && x.type === "VirtualText" && x.version === version -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = { + spaceTiny: '5px', + spaceSmall: '10px', + spaceMedium: '22px', + spaceLarge: '32px', + spaceHuge: '42px', -},{"./version":146}],145:[function(require,module,exports){ -module.exports = isWidget + animationDurationQuick: '100ms', + animationDurationNormal: '200ms', + animationDurationSlow: '400ms' +}; +},{}],356:[function(require,module,exports){ +"use strict"; -function isWidget(w) { - return w && w.type === "Widget" -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = { + fontBase: "'Source Sans Pro', sans-serif", + fontSpecial: "'Signika', Helvetica, serif", + fontCode: "'Source Code Pro', monospace" +}; +},{}],357:[function(require,module,exports){ +'use strict'; -},{}],146:[function(require,module,exports){ -module.exports = "2" +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.textUnselectable = exports.renderSvgDropshadow = exports.marbleElevation1Style = exports.elevation3After = exports.elevation3Before = exports.elevation2After = exports.elevation2Before = exports.elevation2Style = exports.elevation1Style = exports.mergeStyles = undefined; -},{}],147:[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") +var _immutable = require('immutable'); -module.exports = VirtualNode +var _immutable2 = _interopRequireDefault(_immutable); -var noProperties = {} -var noChildren = [] +var _dom = require('@cycle/dom'); -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 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var count = (children && children.length) || 0 - var descendants = 0 - var hasWidgets = false - var hasThunks = false - var descendantHooks = false - var hooks +var isTruthy = function isTruthy(x) { + return !!x; +}; - for (var propName in properties) { - if (properties.hasOwnProperty(propName)) { - var property = properties[propName] - if (isVHook(property) && property.unhook) { - if (!hooks) { - hooks = {} - } +function mergeStyles() { + for (var _len = arguments.length, styleObjects = Array(_len), _key = 0; _key < _len; _key++) { + styleObjects[_key] = arguments[_key]; + } - hooks[propName] = property - } - } - } + 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 + }, {}); +} - for (var i = 0; i < count; i++) { - var child = children[i] - if (isVNode(child)) { - descendants += child.count || 0 +var DROPSHADOW_FILTER_ID = 'dropshadow'; - if (!hasWidgets && child.hasWidgets) { - hasWidgets = true - } +// Cross-browser SVG filter for drop shadows +function renderSvgDropshadow() { + return (0, _dom.svg)('svg', { attributes: { height: '0' } }, [(0, _dom.svg)('filter#' + DROPSHADOW_FILTER_ID, { attributes: { height: '130%' } }, [ + // stdDeviation is blur: + (0, _dom.svg)('feGaussianBlur', { attributes: { in: 'SourceAlpha', stdDeviation: '0.05' } }), + // position relative to marble viewBox: + (0, _dom.svg)('feOffset', { attributes: { dx: '0', dy: '0.05', result: 'offsetblur' } }), (0, _dom.svg)('feFlood', { attributes: { 'flood-color': 'rgba(0,0,0,0.4)' } }), (0, _dom.svg)('feComposite', { attributes: { in2: 'offsetblur', operator: 'in' } }), (0, _dom.svg)('feMerge', [(0, _dom.svg)('feMergeNode'), (0, _dom.svg)('feMergeNode', { attributes: { in: 'SourceGraphic' } })])])]); +} - if (!hasThunks && child.hasThunks) { - hasThunks = true - } +var marbleElevation1Style = { + filter: 'url(#' + DROPSHADOW_FILTER_ID + ')' +}; - 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; - } - } +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)' +}; - this.count = count + descendants - this.hasWidgets = hasWidgets - this.hasThunks = hasThunks - this.hooks = hooks - this.descendantHooks = descendantHooks +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 + ')' + }; } -VirtualNode.prototype.version = version -VirtualNode.prototype.type = "VirtualNode" +var elevation2Before = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '10px', '0.17') +}, ''); +var elevation2After = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('2px', '5px', '0.26') +}, ''); -},{"./is-thunk":141,"./is-vhook":142,"./is-vnode":143,"./is-widget":145,"./version":146}],148:[function(require,module,exports){ -var version = require("./version") +var elevation3Before = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('6px', '20px', '0.19') +}, ''); +var elevation3After = (0, _dom.h)('div', { style: getElevationPseudoElementStyle('6px', '17px', '0.2') +}, ''); -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 +var textUnselectable = { + '-webkit-user-select': 'none', + '-khtml-user-select': 'none', + '-moz-user-select': 'none', + '-o-user-select': 'none', + 'user-select': 'none' +}; -module.exports = VirtualPatch +exports.mergeStyles = mergeStyles; +exports.elevation1Style = elevation1Style; +exports.elevation2Style = elevation2Style; +exports.elevation2Before = elevation2Before; +exports.elevation2After = elevation2After; +exports.elevation3Before = elevation3Before; +exports.elevation3After = elevation3After; +exports.marbleElevation1Style = marbleElevation1Style; +exports.renderSvgDropshadow = renderSvgDropshadow; +exports.textUnselectable = textUnselectable; +},{"@cycle/dom":242,"immutable":304}],358:[function(require,module,exports){ +'use strict'; -function VirtualPatch(type, vNode, patch) { - this.type = Number(type) - this.vNode = vNode - this.patch = patch -} +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; -VirtualPatch.prototype.version = version -VirtualPatch.prototype.type = "VirtualPatch" +var _require = require('./ease-common'); -},{"./version":146}],149:[function(require,module,exports){ -var version = require("./version") +var createEasing = _require.createEasing; -module.exports = VirtualText +var OVERSHOOT = 1.70158; -function VirtualText(text) { - this.text = String(text) -} +exports['default'] = { + EasingBack: createEasing(function (x) { + return x * x * ((OVERSHOOT + 1) * x - OVERSHOOT); + }) +}; +module.exports = exports['default']; +},{"./ease-common":361}],359:[function(require,module,exports){ +'use strict'; -VirtualText.prototype.version = version -VirtualText.prototype.type = "VirtualText" +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; -},{"./version":146}],150:[function(require,module,exports){ -var isObject = require("is-object") -var isHook = require("../vnode/is-vhook") +var _require = require('./ease-common'); -module.exports = diffProps +var createEasing = _require.createEasing; -function diffProps(a, b) { - var diff +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; + } +} - for (var aKey in a) { - if (!(aKey in b)) { - diff = diff || {} - diff[aKey] = undefined - } +exports['default'] = { + EasingBounce: createEasing(function (x) { + return 1 - easeOutFn(1 - x); + }) +}; +module.exports = exports['default']; +},{"./ease-common":361}],360:[function(require,module,exports){ +'use strict'; - var aValue = a[aKey] - var bValue = b[aKey] +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; - 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 - } - } +var _require = require('./ease-common'); - for (var bKey in b) { - if (!(bKey in a)) { - diff = diff || {} - diff[bKey] = b[bKey] - } - } +var createEasing = _require.createEasing; +exports['default'] = { + EasingCirc: createEasing(function (x) { + return -(Math.sqrt(1 - x * x) - 1); + }) +}; +module.exports = exports['default']; +},{"./ease-common":361}],361:[function(require,module,exports){ +'use strict'; - return diff +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; + +function interpolate(y, from, to) { + return from * (1 - y) + to * y; } -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 - } +function flip(fn) { + return function (x) { + return 1 - fn(1 - x); + }; } -},{"../vnode/is-vhook":142,"is-object":97}],151:[function(require,module,exports){ -var isArray = require("x-is-array") +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']; +},{}],362:[function(require,module,exports){ +'use strict'; -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") +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; -var diffProps = require("./diff-props") +var _require = require('./ease-common'); -module.exports = diff +var createEasing = _require.createEasing; -function diff(a, b) { - var patch = { a: a } - walk(a, b, patch, 0) - return patch +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); + } } -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] - } +exports['default'] = { + EasingElastic: createEasing(elasticIn) +}; +module.exports = exports['default']; +},{"./ease-common":361}],363:[function(require,module,exports){ +'use strict'; - 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 - } +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; - apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) - } +var _require = require('./ease-common'); - if (apply) { - patch[index] = apply - } +var createEasing = _require.createEasing; - if (applyClear) { - clearState(a, patch, index) - } +var EXP_WEIGHT = 6; +var EXP_MAX = Math.exp(EXP_WEIGHT) - 1; +function expFn(x) { + return (Math.exp(x * EXP_WEIGHT) - 1) / EXP_MAX; } -function diffChildren(a, b, patch, apply, index) { - var aChildren = a.children - var orderedSet = reorder(aChildren, b.children) - var bChildren = orderedSet.children +var EasingExponential = createEasing(expFn); - var aLen = aChildren.length - var bLen = bChildren.length - var len = aLen > bLen ? aLen : bLen +exports['default'] = { + EasingExponential: EasingExponential +}; +module.exports = exports['default']; +},{"./ease-common":361}],364:[function(require,module,exports){ +'use strict'; - for (var i = 0; i < len; i++) { - var leftNode = aChildren[i] - var rightNode = bChildren[i] - index += 1 +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; - 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) - } +var _require = require('./ease-common'); - if (isVNode(leftNode) && leftNode.count) { - index += leftNode.count - } - } +var createEasing = _require.createEasing; - if (orderedSet.moves) { - // Reorder nodes last - apply = appendPatch(apply, new VPatch( - VPatch.ORDER, - a, - orderedSet.moves - )) - } +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; +}); - return apply -} +exports['default'] = { + EasingPower2: EasingPower2, + EasingPower3: EasingPower3, + EasingPower4: EasingPower4 +}; +module.exports = exports['default']; +},{"./ease-common":361}],365:[function(require,module,exports){ +'use strict'; -function clearState(vNode, patch, index) { - // TODO: Make this a single walk, not two - unhook(vNode, patch, index) - destroyWidgets(vNode, patch, index) -} +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; -// 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 +var _require = require('./ease-common'); - destroyWidgets(child, patch, index) +var createEasing = _require.createEasing; - if (isVNode(child) && child.count) { - index += child.count - } - } - } else if (isThunk(vNode)) { - thunks(vNode, null, patch, index) - } -} +var HALF_PI = Math.PI * 0.5; -// 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) - } -} +exports['default'] = { + EasingSine: createEasing(function (x) { + return 1 - Math.cos(x * HALF_PI); + }) +}; +module.exports = exports['default']; +},{"./ease-common":361}],366:[function(require,module,exports){ +'use strict'; -function hasPatches(patch) { - for (var index in patch) { - if (index !== "a") { - return true - } - } +Object.defineProperty(exports, '__esModule', { + value: true +}); +'use strict'; +var Rx = require('rx'); - return false -} +var _require = require('./ease-common'); -// 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) - ) - ) - } +var interpolate = _require.interpolate; - 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 +var _require2 = require('./ease-powers'); - unhook(child, patch, index) +var EasingPower2 = _require2.EasingPower2; +var EasingPower3 = _require2.EasingPower3; +var EasingPower4 = _require2.EasingPower4; - if (isVNode(child) && child.count) { - index += child.count - } - } - } - } else if (isThunk(vNode)) { - thunks(vNode, null, patch, index) - } -} +var _require3 = require('./ease-exponential'); -function undefinedKeys(obj) { - var result = {} +var EasingExponential = _require3.EasingExponential; - for (var key in obj) { - result[key] = undefined - } +var _require4 = require('./ease-back'); - return result -} +var EasingBack = _require4.EasingBack; -// 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 +var _require5 = require('./ease-bounce'); - if (bFree.length === bChildren.length) { - return { - children: bChildren, - moves: null - } - } +var EasingBounce = _require5.EasingBounce; - // O(N) time, O(N) memory - var aChildIndex = keyIndex(aChildren) - var aKeys = aChildIndex.keys - var aFree = aChildIndex.free +var _require6 = require('./ease-circ'); - if (aFree.length === aChildren.length) { - return { - children: bChildren, - moves: null - } - } +var EasingCirc = _require6.EasingCirc; - // O(MAX(N, M)) memory - var newChildren = [] +var _require7 = require('./ease-elastic'); - var freeIndex = 0 - var freeCount = bFree.length - var deletedItems = 0 +var EasingElastic = _require7.EasingElastic; - // 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 +var _require8 = require('./ease-sine'); - if (aItem.key) { - if (bKeys.hasOwnProperty(aItem.key)) { - // Match up the old keys - itemIndex = bKeys[aItem.key] - newChildren.push(bChildren[itemIndex]) +var EasingSine = _require8.EasingSine; - } 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 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; +} - var lastFreeIndex = freeIndex >= bFree.length ? - bChildren.length : - bFree[freeIndex] +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; - // Iterate through b and append any new keys - // O(M) time - for (var j = 0; j < bChildren.length; j++) { - var newItem = bChildren[j] + 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)); +} - 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) - } - } +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; - var simulate = newChildren.slice() - var simulateIndex = 0 - var removes = [] - var inserts = [] - var simulateItem +exports['default'] = RxTween; +module.exports = exports['default']; +},{"./ease-back":358,"./ease-bounce":359,"./ease-circ":360,"./ease-common":361,"./ease-elastic":362,"./ease-exponential":363,"./ease-powers":364,"./ease-sine":365,"rx":231}],367:[function(require,module,exports){ +arguments[4][311][0].apply(exports,arguments) +},{"./vendor/camel-case-regexp":368,"./vendor/non-word-regexp":369,"./vendor/trailing-digit-regexp":370,"dup":311,"lower-case":229}],368:[function(require,module,exports){ +arguments[4][312][0].apply(exports,arguments) +},{"dup":312}],369:[function(require,module,exports){ +arguments[4][313][0].apply(exports,arguments) +},{"dup":313}],370:[function(require,module,exports){ +arguments[4][314][0].apply(exports,arguments) +},{"dup":314}],371:[function(require,module,exports){ +arguments[4][315][0].apply(exports,arguments) +},{"./namespace-map":372,"./property-map":373,"dup":315,"virtual-dom/vnode/vnode":403,"virtual-dom/vnode/vtext":405}],372:[function(require,module,exports){ +arguments[4][316][0].apply(exports,arguments) +},{"dup":316}],373:[function(require,module,exports){ +arguments[4][317][0].apply(exports,arguments) +},{"dup":317}],374:[function(require,module,exports){ +arguments[4][318][0].apply(exports,arguments) +},{"./property-config":376,"dup":318,"escape-html":221}],375:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./create-attribute":374,"./void-elements":377,"dup":319,"escape-html":221,"param-case":230,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":389,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":391,"virtual-dom/vnode/is-thunk":397,"virtual-dom/vnode/is-vnode":399,"virtual-dom/vnode/is-vtext":400,"virtual-dom/vnode/is-widget":401,"xtend":409}],376:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320}],377:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"dup":321}],378:[function(require,module,exports){ +arguments[4][322][0].apply(exports,arguments) +},{"./vdom/create-element.js":384,"dup":322}],379:[function(require,module,exports){ +arguments[4][323][0].apply(exports,arguments) +},{"./vtree/diff.js":407,"dup":323}],380:[function(require,module,exports){ +arguments[4][324][0].apply(exports,arguments) +},{"./virtual-hyperscript/index.js":392,"dup":324}],381:[function(require,module,exports){ +arguments[4][325][0].apply(exports,arguments) +},{"./create-element.js":378,"./diff.js":379,"./h.js":380,"./patch.js":382,"./vnode/vnode.js":403,"./vnode/vtext.js":405,"dup":325}],382:[function(require,module,exports){ +arguments[4][326][0].apply(exports,arguments) +},{"./vdom/patch.js":387,"dup":326}],383:[function(require,module,exports){ +arguments[4][327][0].apply(exports,arguments) +},{"../vnode/is-vhook.js":398,"dup":327,"is-object":228}],384:[function(require,module,exports){ +arguments[4][328][0].apply(exports,arguments) +},{"../vnode/handle-thunk.js":396,"../vnode/is-vnode.js":399,"../vnode/is-vtext.js":400,"../vnode/is-widget.js":401,"./apply-properties":383,"dup":328,"global/document":224}],385:[function(require,module,exports){ +arguments[4][329][0].apply(exports,arguments) +},{"dup":329}],386:[function(require,module,exports){ +arguments[4][330][0].apply(exports,arguments) +},{"../vnode/is-widget.js":401,"../vnode/vpatch.js":404,"./apply-properties":383,"./update-widget":388,"dup":330}],387:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./create-element":384,"./dom-index":385,"./patch-op":386,"dup":331,"global/document":224,"x-is-array":408}],388:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"../vnode/is-widget.js":401,"dup":332}],389:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"dup":333}],390:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"dup":334,"ev-store":222}],391:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"dup":335}],392:[function(require,module,exports){ +arguments[4][336][0].apply(exports,arguments) +},{"../vnode/is-thunk":397,"../vnode/is-vhook":398,"../vnode/is-vnode":399,"../vnode/is-vtext":400,"../vnode/is-widget":401,"../vnode/vnode.js":403,"../vnode/vtext.js":405,"./hooks/ev-hook.js":390,"./hooks/soft-set-hook.js":391,"./parse-tag.js":393,"dup":336,"x-is-array":408}],393:[function(require,module,exports){ +arguments[4][337][0].apply(exports,arguments) +},{"browser-split":166,"dup":337}],394:[function(require,module,exports){ +arguments[4][338][0].apply(exports,arguments) +},{"dup":338}],395:[function(require,module,exports){ +arguments[4][339][0].apply(exports,arguments) +},{"./hooks/attribute-hook":389,"./index.js":392,"./svg-attribute-namespace":394,"dup":339,"x-is-array":408}],396:[function(require,module,exports){ +arguments[4][340][0].apply(exports,arguments) +},{"./is-thunk":397,"./is-vnode":399,"./is-vtext":400,"./is-widget":401,"dup":340}],397:[function(require,module,exports){ +arguments[4][341][0].apply(exports,arguments) +},{"dup":341}],398:[function(require,module,exports){ +arguments[4][342][0].apply(exports,arguments) +},{"dup":342}],399:[function(require,module,exports){ +arguments[4][343][0].apply(exports,arguments) +},{"./version":402,"dup":343}],400:[function(require,module,exports){ +arguments[4][344][0].apply(exports,arguments) +},{"./version":402,"dup":344}],401:[function(require,module,exports){ +arguments[4][345][0].apply(exports,arguments) +},{"dup":345}],402:[function(require,module,exports){ +arguments[4][346][0].apply(exports,arguments) +},{"dup":346}],403:[function(require,module,exports){ +arguments[4][347][0].apply(exports,arguments) +},{"./is-thunk":397,"./is-vhook":398,"./is-vnode":399,"./is-widget":401,"./version":402,"dup":347}],404:[function(require,module,exports){ +arguments[4][348][0].apply(exports,arguments) +},{"./version":402,"dup":348}],405:[function(require,module,exports){ +arguments[4][349][0].apply(exports,arguments) +},{"./version":402,"dup":349}],406:[function(require,module,exports){ +arguments[4][350][0].apply(exports,arguments) +},{"../vnode/is-vhook":398,"dup":350,"is-object":228}],407:[function(require,module,exports){ +arguments[4][351][0].apply(exports,arguments) +},{"../vnode/handle-thunk":396,"../vnode/is-thunk":397,"../vnode/is-vnode":399,"../vnode/is-vtext":400,"../vnode/is-widget":401,"../vnode/vpatch":404,"./diff-props":406,"dup":351,"x-is-array":408}],408:[function(require,module,exports){ +arguments[4][352][0].apply(exports,arguments) +},{"dup":352}],409:[function(require,module,exports){ +arguments[4][353][0].apply(exports,arguments) +},{"dup":353}],410:[function(require,module,exports){ +arguments[4][354][0].apply(exports,arguments) +},{"dup":354}],411:[function(require,module,exports){ +arguments[4][355][0].apply(exports,arguments) +},{"dup":355}],412:[function(require,module,exports){ +arguments[4][356][0].apply(exports,arguments) +},{"dup":356}],413:[function(require,module,exports){ +arguments[4][357][0].apply(exports,arguments) +},{"@cycle/dom":163,"dup":357,"immutable":225}],414:[function(require,module,exports){ +arguments[4][358][0].apply(exports,arguments) +},{"./ease-common":417,"dup":358}],415:[function(require,module,exports){ +arguments[4][359][0].apply(exports,arguments) +},{"./ease-common":417,"dup":359}],416:[function(require,module,exports){ +arguments[4][360][0].apply(exports,arguments) +},{"./ease-common":417,"dup":360}],417:[function(require,module,exports){ +arguments[4][361][0].apply(exports,arguments) +},{"dup":361}],418:[function(require,module,exports){ +arguments[4][362][0].apply(exports,arguments) +},{"./ease-common":417,"dup":362}],419:[function(require,module,exports){ +arguments[4][363][0].apply(exports,arguments) +},{"./ease-common":417,"dup":363}],420:[function(require,module,exports){ +arguments[4][364][0].apply(exports,arguments) +},{"./ease-common":417,"dup":364}],421:[function(require,module,exports){ +arguments[4][365][0].apply(exports,arguments) +},{"./ease-common":417,"dup":365}],422:[function(require,module,exports){ +arguments[4][366][0].apply(exports,arguments) +},{"./ease-back":414,"./ease-bounce":415,"./ease-circ":416,"./ease-common":417,"./ease-elastic":418,"./ease-exponential":419,"./ease-powers":420,"./ease-sine":421,"dup":366,"rx":152}],423:[function(require,module,exports){ +arguments[4][311][0].apply(exports,arguments) +},{"./vendor/camel-case-regexp":424,"./vendor/non-word-regexp":425,"./vendor/trailing-digit-regexp":426,"dup":311,"lower-case":149}],424:[function(require,module,exports){ +arguments[4][312][0].apply(exports,arguments) +},{"dup":312}],425:[function(require,module,exports){ +arguments[4][313][0].apply(exports,arguments) +},{"dup":313}],426:[function(require,module,exports){ +arguments[4][314][0].apply(exports,arguments) +},{"dup":314}],427:[function(require,module,exports){ +arguments[4][315][0].apply(exports,arguments) +},{"./namespace-map":428,"./property-map":429,"dup":315,"virtual-dom/vnode/vnode":459,"virtual-dom/vnode/vtext":461}],428:[function(require,module,exports){ +arguments[4][316][0].apply(exports,arguments) +},{"dup":316}],429:[function(require,module,exports){ +arguments[4][317][0].apply(exports,arguments) +},{"dup":317}],430:[function(require,module,exports){ +arguments[4][318][0].apply(exports,arguments) +},{"./property-config":432,"dup":318,"escape-html":141}],431:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./create-attribute":430,"./void-elements":433,"dup":319,"escape-html":141,"param-case":151,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":445,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":447,"virtual-dom/vnode/is-thunk":453,"virtual-dom/vnode/is-vnode":455,"virtual-dom/vnode/is-vtext":456,"virtual-dom/vnode/is-widget":457,"xtend":465}],432:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320}],433:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"dup":321}],434:[function(require,module,exports){ +arguments[4][322][0].apply(exports,arguments) +},{"./vdom/create-element.js":440,"dup":322}],435:[function(require,module,exports){ +arguments[4][323][0].apply(exports,arguments) +},{"./vtree/diff.js":463,"dup":323}],436:[function(require,module,exports){ +arguments[4][324][0].apply(exports,arguments) +},{"./virtual-hyperscript/index.js":448,"dup":324}],437:[function(require,module,exports){ +arguments[4][325][0].apply(exports,arguments) +},{"./create-element.js":434,"./diff.js":435,"./h.js":436,"./patch.js":438,"./vnode/vnode.js":459,"./vnode/vtext.js":461,"dup":325}],438:[function(require,module,exports){ +arguments[4][326][0].apply(exports,arguments) +},{"./vdom/patch.js":443,"dup":326}],439:[function(require,module,exports){ +arguments[4][327][0].apply(exports,arguments) +},{"../vnode/is-vhook.js":454,"dup":327,"is-object":148}],440:[function(require,module,exports){ +arguments[4][328][0].apply(exports,arguments) +},{"../vnode/handle-thunk.js":452,"../vnode/is-vnode.js":455,"../vnode/is-vtext.js":456,"../vnode/is-widget.js":457,"./apply-properties":439,"dup":328,"global/document":144}],441:[function(require,module,exports){ +arguments[4][329][0].apply(exports,arguments) +},{"dup":329}],442:[function(require,module,exports){ +arguments[4][330][0].apply(exports,arguments) +},{"../vnode/is-widget.js":457,"../vnode/vpatch.js":460,"./apply-properties":439,"./update-widget":444,"dup":330}],443:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./create-element":440,"./dom-index":441,"./patch-op":442,"dup":331,"global/document":144,"x-is-array":464}],444:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"../vnode/is-widget.js":457,"dup":332}],445:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"dup":333}],446:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"dup":334,"ev-store":142}],447:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"dup":335}],448:[function(require,module,exports){ +arguments[4][336][0].apply(exports,arguments) +},{"../vnode/is-thunk":453,"../vnode/is-vhook":454,"../vnode/is-vnode":455,"../vnode/is-vtext":456,"../vnode/is-widget":457,"../vnode/vnode.js":459,"../vnode/vtext.js":461,"./hooks/ev-hook.js":446,"./hooks/soft-set-hook.js":447,"./parse-tag.js":449,"dup":336,"x-is-array":464}],449:[function(require,module,exports){ +arguments[4][337][0].apply(exports,arguments) +},{"browser-split":86,"dup":337}],450:[function(require,module,exports){ +arguments[4][338][0].apply(exports,arguments) +},{"dup":338}],451:[function(require,module,exports){ +arguments[4][339][0].apply(exports,arguments) +},{"./hooks/attribute-hook":445,"./index.js":448,"./svg-attribute-namespace":450,"dup":339,"x-is-array":464}],452:[function(require,module,exports){ +arguments[4][340][0].apply(exports,arguments) +},{"./is-thunk":453,"./is-vnode":455,"./is-vtext":456,"./is-widget":457,"dup":340}],453:[function(require,module,exports){ +arguments[4][341][0].apply(exports,arguments) +},{"dup":341}],454:[function(require,module,exports){ +arguments[4][342][0].apply(exports,arguments) +},{"dup":342}],455:[function(require,module,exports){ +arguments[4][343][0].apply(exports,arguments) +},{"./version":458,"dup":343}],456:[function(require,module,exports){ +arguments[4][344][0].apply(exports,arguments) +},{"./version":458,"dup":344}],457:[function(require,module,exports){ +arguments[4][345][0].apply(exports,arguments) +},{"dup":345}],458:[function(require,module,exports){ +arguments[4][346][0].apply(exports,arguments) +},{"dup":346}],459:[function(require,module,exports){ +arguments[4][347][0].apply(exports,arguments) +},{"./is-thunk":453,"./is-vhook":454,"./is-vnode":455,"./is-widget":457,"./version":458,"dup":347}],460:[function(require,module,exports){ +arguments[4][348][0].apply(exports,arguments) +},{"./version":458,"dup":348}],461:[function(require,module,exports){ +arguments[4][349][0].apply(exports,arguments) +},{"./version":458,"dup":349}],462:[function(require,module,exports){ +arguments[4][350][0].apply(exports,arguments) +},{"../vnode/is-vhook":454,"dup":350,"is-object":148}],463:[function(require,module,exports){ +arguments[4][351][0].apply(exports,arguments) +},{"../vnode/handle-thunk":452,"../vnode/is-thunk":453,"../vnode/is-vnode":455,"../vnode/is-vtext":456,"../vnode/is-widget":457,"../vnode/vpatch":460,"./diff-props":462,"dup":351,"x-is-array":464}],464:[function(require,module,exports){ +arguments[4][352][0].apply(exports,arguments) +},{"dup":352}],465:[function(require,module,exports){ +arguments[4][353][0].apply(exports,arguments) +},{"dup":353}],466:[function(require,module,exports){ +arguments[4][311][0].apply(exports,arguments) +},{"./vendor/camel-case-regexp":467,"./vendor/non-word-regexp":468,"./vendor/trailing-digit-regexp":469,"dup":311,"lower-case":69}],467:[function(require,module,exports){ +arguments[4][312][0].apply(exports,arguments) +},{"dup":312}],468:[function(require,module,exports){ +arguments[4][313][0].apply(exports,arguments) +},{"dup":313}],469:[function(require,module,exports){ +arguments[4][314][0].apply(exports,arguments) +},{"dup":314}],470:[function(require,module,exports){ +arguments[4][315][0].apply(exports,arguments) +},{"./namespace-map":471,"./property-map":472,"dup":315,"virtual-dom/vnode/vnode":502,"virtual-dom/vnode/vtext":504}],471:[function(require,module,exports){ +arguments[4][316][0].apply(exports,arguments) +},{"dup":316}],472:[function(require,module,exports){ +arguments[4][317][0].apply(exports,arguments) +},{"dup":317}],473:[function(require,module,exports){ +arguments[4][318][0].apply(exports,arguments) +},{"./property-config":475,"dup":318,"escape-html":62}],474:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./create-attribute":473,"./void-elements":476,"dup":319,"escape-html":62,"param-case":70,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":488,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":490,"virtual-dom/vnode/is-thunk":496,"virtual-dom/vnode/is-vnode":498,"virtual-dom/vnode/is-vtext":499,"virtual-dom/vnode/is-widget":500,"xtend":508}],475:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320}],476:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"dup":321}],477:[function(require,module,exports){ +arguments[4][322][0].apply(exports,arguments) +},{"./vdom/create-element.js":483,"dup":322}],478:[function(require,module,exports){ +arguments[4][323][0].apply(exports,arguments) +},{"./vtree/diff.js":506,"dup":323}],479:[function(require,module,exports){ +arguments[4][324][0].apply(exports,arguments) +},{"./virtual-hyperscript/index.js":491,"dup":324}],480:[function(require,module,exports){ +arguments[4][325][0].apply(exports,arguments) +},{"./create-element.js":477,"./diff.js":478,"./h.js":479,"./patch.js":481,"./vnode/vnode.js":502,"./vnode/vtext.js":504,"dup":325}],481:[function(require,module,exports){ +arguments[4][326][0].apply(exports,arguments) +},{"./vdom/patch.js":486,"dup":326}],482:[function(require,module,exports){ +arguments[4][327][0].apply(exports,arguments) +},{"../vnode/is-vhook.js":497,"dup":327,"is-object":68}],483:[function(require,module,exports){ +arguments[4][328][0].apply(exports,arguments) +},{"../vnode/handle-thunk.js":495,"../vnode/is-vnode.js":498,"../vnode/is-vtext.js":499,"../vnode/is-widget.js":500,"./apply-properties":482,"dup":328,"global/document":65}],484:[function(require,module,exports){ +arguments[4][329][0].apply(exports,arguments) +},{"dup":329}],485:[function(require,module,exports){ +arguments[4][330][0].apply(exports,arguments) +},{"../vnode/is-widget.js":500,"../vnode/vpatch.js":503,"./apply-properties":482,"./update-widget":487,"dup":330}],486:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./create-element":483,"./dom-index":484,"./patch-op":485,"dup":331,"global/document":65,"x-is-array":507}],487:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"../vnode/is-widget.js":500,"dup":332}],488:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"dup":333}],489:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"dup":334,"ev-store":63}],490:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"dup":335}],491:[function(require,module,exports){ +arguments[4][336][0].apply(exports,arguments) +},{"../vnode/is-thunk":496,"../vnode/is-vhook":497,"../vnode/is-vnode":498,"../vnode/is-vtext":499,"../vnode/is-widget":500,"../vnode/vnode.js":502,"../vnode/vtext.js":504,"./hooks/ev-hook.js":489,"./hooks/soft-set-hook.js":490,"./parse-tag.js":492,"dup":336,"x-is-array":507}],492:[function(require,module,exports){ +arguments[4][337][0].apply(exports,arguments) +},{"browser-split":7,"dup":337}],493:[function(require,module,exports){ +arguments[4][338][0].apply(exports,arguments) +},{"dup":338}],494:[function(require,module,exports){ +arguments[4][339][0].apply(exports,arguments) +},{"./hooks/attribute-hook":488,"./index.js":491,"./svg-attribute-namespace":493,"dup":339,"x-is-array":507}],495:[function(require,module,exports){ +arguments[4][340][0].apply(exports,arguments) +},{"./is-thunk":496,"./is-vnode":498,"./is-vtext":499,"./is-widget":500,"dup":340}],496:[function(require,module,exports){ +arguments[4][341][0].apply(exports,arguments) +},{"dup":341}],497:[function(require,module,exports){ +arguments[4][342][0].apply(exports,arguments) +},{"dup":342}],498:[function(require,module,exports){ +arguments[4][343][0].apply(exports,arguments) +},{"./version":501,"dup":343}],499:[function(require,module,exports){ +arguments[4][344][0].apply(exports,arguments) +},{"./version":501,"dup":344}],500:[function(require,module,exports){ +arguments[4][345][0].apply(exports,arguments) +},{"dup":345}],501:[function(require,module,exports){ +arguments[4][346][0].apply(exports,arguments) +},{"dup":346}],502:[function(require,module,exports){ +arguments[4][347][0].apply(exports,arguments) +},{"./is-thunk":496,"./is-vhook":497,"./is-vnode":498,"./is-widget":500,"./version":501,"dup":347}],503:[function(require,module,exports){ +arguments[4][348][0].apply(exports,arguments) +},{"./version":501,"dup":348}],504:[function(require,module,exports){ +arguments[4][349][0].apply(exports,arguments) +},{"./version":501,"dup":349}],505:[function(require,module,exports){ +arguments[4][350][0].apply(exports,arguments) +},{"../vnode/is-vhook":497,"dup":350,"is-object":68}],506:[function(require,module,exports){ +arguments[4][351][0].apply(exports,arguments) +},{"../vnode/handle-thunk":495,"../vnode/is-thunk":496,"../vnode/is-vnode":498,"../vnode/is-vtext":499,"../vnode/is-widget":500,"../vnode/vpatch":503,"./diff-props":505,"dup":351,"x-is-array":507}],507:[function(require,module,exports){ +arguments[4][352][0].apply(exports,arguments) +},{"dup":352}],508:[function(require,module,exports){ +arguments[4][353][0].apply(exports,arguments) +},{"dup":353}],509:[function(require,module,exports){ + +},{}],510:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; - for (var k = 0; k < bChildren.length;) { - var wantedItem = bChildren[k] - simulateItem = simulate[simulateIndex] +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - // remove items - while (simulateItem === null && simulate.length) { - removes.push(remove(simulate, simulateIndex, null)) - simulateItem = simulate[simulateIndex] - } +var cachedSetTimeout; +var cachedClearTimeout; - 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)) - } +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; } - else { - simulateIndex++ - k++ + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } } - // remove all the remaining nodes from simulate - while(simulateIndex < simulate.length) { - simulateItem = simulate[simulateIndex] - removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } +} - // 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 - } +function drainQueue() { + if (draining) { + return; } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - return { - children: newChildren, - moves: { - removes: removes, - inserts: inserts + 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; + runClearTimeout(timeout); } -function remove(arr, index, key) { - arr.splice(index, 1) - - return { - from: index, - key: key +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) { + runTimeout(drainQueue); + } +}; + +// 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 keyIndex(children) { - var keys = {} - var free = [] - var length = children.length +function noop() {} - for (var i = 0; i < length; i++) { - var child = children[i] +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; - if (child.key) { - keys[child.key] = i - } else { - free.push(i) - } - } +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - return { - keys: keys, // A hash of key name to index - free: free // An array of unkeyed item indices - } -} +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -function appendPatch(apply, patch) { - if (apply) { - if (isArray(apply)) { - apply.push(patch) - } else { - apply = [apply, patch] - } +},{}],511:[function(require,module,exports){ +'use strict'; - return apply - } else { - return patch - } -} +var _core = require('@cycle/core'); -},{"../vnode/handle-thunk":140,"../vnode/is-thunk":141,"../vnode/is-vnode":143,"../vnode/is-vtext":144,"../vnode/is-widget":145,"../vnode/vpatch":148,"./diff-props":150,"x-is-array":152}],152:[function(require,module,exports){ -var nativeIsArray = Array.isArray -var toString = Object.prototype.toString +var _core2 = _interopRequireDefault(_core); -module.exports = nativeIsArray || isArray +var _dom = require('@cycle/dom'); -function isArray(obj) { - return toString.call(obj) === "[object Array]" -} +var _appModel = require('rxmarbles/app-model'); -},{}],153:[function(require,module,exports){ -module.exports = extend +var _appModel2 = _interopRequireDefault(_appModel); -var hasOwnProperty = Object.prototype.hasOwnProperty; +var _appView = require('rxmarbles/app-view'); -function extend() { - var target = {} +var _appView2 = _interopRequireDefault(_appView); - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] +var _operatorsMenuLink = require('rxmarbles/components/operators-menu-link'); - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } +var _operatorsMenuLink2 = _interopRequireDefault(_operatorsMenuLink); - return target -} +var _operatorsMenu = require('rxmarbles/components/operators-menu'); -},{}],154:[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", - "rx": "^2.5.3", - "rxtween": "^0.3.3" - }, - "devDependencies": { - "babel": "^5.2.7", - "babel-cli": "^6.14.0", - "babel-preset-es2015": "^6.14.0", - "browserify": "10.1.3", - "less": "^2.5.0", - "uglify-js": "~2.4.21", - "watchify": "~3.2.1" - }, - "scripts": { - "preinstall": "rm -rf build && rm -rf node_modules && mkdir -p ignore/es5src && rm -f node_modules/rxmarbles node_modules/package.json ignore/es5src/node_modules", - "postinstall": "ln -s ../ignore/es5src node_modules/rxmarbles && ln -s ../package.json node_modules/package.json && ln -s ../../node_modules ignore/es5src/node_modules", - "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" - } +var _operatorsMenu2 = _interopRequireDefault(_operatorsMenu); + +var _sandbox = require('rxmarbles/components/sandbox/sandbox'); + +var _sandbox2 = _interopRequireDefault(_sandbox); + +var _diagram = require('rxmarbles/components/diagram/diagram'); + +var _diagram2 = _interopRequireDefault(_diagram); + +var _marble = require('rxmarbles/components/marble'); + +var _marble2 = _interopRequireDefault(_marble); + +var _diagramCompletion = require('rxmarbles/components/diagram-completion'); + +var _diagramCompletion2 = _interopRequireDefault(_diagramCompletion); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function main() { + return { + DOM: (0, _appView2.default)((0, _appModel2.default)()) + }; } -},{}]},{},[5]); +_core2.default.run(main, { + DOM: (0, _dom.makeDOMDriver)('.js-appContainer', { + 'x-operators-menu-link': _operatorsMenuLink2.default, + 'x-operators-menu': _operatorsMenu2.default, + 'x-sandbox': _sandbox2.default, + 'x-marble': _marble2.default, + 'x-diagram-completion': _diagramCompletion2.default, + 'x-diagram': _diagram2.default + }) +}); +},{"@cycle/core":1,"@cycle/dom":4,"rxmarbles/app-model":72,"rxmarbles/app-view":73,"rxmarbles/components/diagram-completion":74,"rxmarbles/components/diagram/diagram":75,"rxmarbles/components/marble":76,"rxmarbles/components/operators-menu":78,"rxmarbles/components/operators-menu-link":77,"rxmarbles/components/sandbox/sandbox":79}]},{},[511]);