export function stations(state:Map<string,any> = Map<string,any>(), action:any):Map<string, List<StationModel>> {

    function indexOfStation(businessId, stationId):any {
        return stations.findIndex((i:StationModel) => {
            return i.getKey('businessId') === businessId && i.getKey('id') == stationId;
        });
    }

    switch (action.type) {
        case StationsAction.RECEIVE_STATIONS:
            return state.update(action.source, (value) => action.stations);

        case StationsAction.RECEIVE_STATIONS_GEO:
            for (var i in action.payload) {
                var station = action.payload[i];
                var source = station.source;
                var stations:List<StationModel> = state.get(source);
                stations = stations.update(indexOfStation(station.businessId, station.id), (i_station:StationModel) => {
                    return i_station.setKey<StationModel>(StationModel, 'geoLocation', {
                        lat: station.lat,
                        lon: station.lon,
                        city: station.city,
                        country: station.country
                    })
                });
                state = state.setIn([source], stations);
            }
            return state;
        default:
            return state;
    }
}
Example #2
0
  static FromXML(el: Element): [GF, undefined] | [undefined, Error] {
    const table: typeof GFDefaults = Object.assign({}, GFDefaults);
    let err: Error | undefined;

    for (let i = 0; i < el.attributes.length; i++) {
      const attr = el.attributes.item(i);
      if (!attr) {
        continue;
      }
      switch (attr.name.toLowerCase()) {
        case 'type':
          const kind = attr.value.toLowerCase();
          if (kind === 'discrete' || kind === 'continuous' || kind === 'extrapolate') {
            table.type = kind;
          } else {
            return [undefined, new Error(`bad GF type: ${kind}`)];
          }
          break;
      }
    }

    for (let i = 0; i < el.childNodes.length; i++) {
      const child = el.childNodes.item(i) as Element;
      if (child.nodeType !== 1) {
        // Element
        continue;
      }
      switch (child.nodeName.toLowerCase()) {
        case 'xscale':
          [table.xScale, err] = Scale.FromXML(child);
          if (err) {
            return [undefined, new Error(`xscale: ${err}`)];
          }
          break;
        case 'yscale':
          [table.yScale, err] = Scale.FromXML(child);
          if (err) {
            return [undefined, new Error(`yscale: ${err}`)];
          }
          break;
        case 'xpts':
          table.xPoints = numberize(splitOnComma(content(child)));
          break;
        case 'ypts':
          table.yPoints = numberize(splitOnComma(content(child)));
          break;
      }
    }

    if (table.yPoints === undefined) {
      return [undefined, new Error('table missing ypts')];
    }

    // FIXME: handle
    if (table.type && table.type !== 'continuous') {
      console.log('WARN: unimplemented table type: ' + table.type);
    }

    return [new GF(table), undefined];
  }
Example #3
0
    const renderGroupDeployNodes = (groupDeploys: List<DeployRecord>, deployGroup: DeployGroupRecord) => {
        const shouldShowProjectNames = !groupDeploys.equals(currentDeploys);

        return h(
            'li',
            { className: `deploy deploy--${deployGroup.status.split(' ').join('-').toLowerCase()}` },
            [
                h('h2', [
                    h('a', { href: createBuildLink(deployGroup.build) }, `${deployGroup.build}`)
                ]),
                // Only show project names if we have multiple deployed groups
                exp(shouldShowProjectNames) && ih('ul', {}, groupDeploys
                    .sortBy(build => build.projectName)
                    .map(deploy => {
                        const previousBuild = previousDeploysMap.get(deploy);
                        return h('li', [
                            h('a', {
                                href: createRiffRaffDeployLink(deploy.uuid),
                                title: previousBuild ? `Previous build: ${previousBuild.build}` : ''
                            }, deploy.projectName)
                        ]);
                    })
                    .toList()
                )
            ]
        );
    };
Example #4
0
    updateActivityInMention(kind: TimelineActivityKind, status: Tweet, from: TwitterUser): [List<Item>, number] {
        const status_id = status.id;
        const index = this.mention.findIndex(item => {
            if (item instanceof TimelineActivity) {
                return item.kind === kind && item.status.id === status_id;
            } else {
                return false;
            }
        });

        const next_focus_index =
            this.kind === 'mention' && (index === -1 || index < this.focus_index) ?
                this.nextFocusIndex(this.mention.size + 1) : this.focus_index;

        if (index === -1) {
            return [this.mention.unshift(new TimelineActivity(kind, status, [from])), next_focus_index];
        } else {
            const will_updated = this.mention.get(index);
            if (will_updated instanceof TimelineActivity) {
                const updated = will_updated.update(status, from);
                return [this.mention.delete(index).unshift(updated), next_focus_index];
            } else {
                log.error('Invalid activity for update:', will_updated);
                return [this.mention, next_focus_index];
            }
        }
    }
function todosReducer(state:List<ITask>, action:IAction):List<ITask> {
        console.log(`todosReducer: Action(${JSON.stringify(action)})`);
        switch(action.type) {
                case Keys.AddTodo:
                    var todos: List<ITask> = List<ITask>(state.concat([action.payload]));
                    console.log(`todosReducer: todos(${JSON.stringify(todos)})`);
                    return todos;
                case Keys.CompleteTodo:
                        return List<ITask>(state.map((task:ITask) => {
                                if (task.Id === action.payload.Id) {
                                        return new Task(
                                                task.Id,
                                                task.Title,
                                                task.Description,
                                                action.payload.Complete
                                        );
                                } else {
                                        return task;
                                }
                        }));
                case Keys.RemoveTodo:
                        return List<ITask>(state.filter((task:ITask) => {
                                return task.Id !== action.payload.Id;
                        }))
        }                                 
        return state || initialState.todos;
}
Example #6
0
    addRejectedIds(ids: number[]) {
        const will_added = ids.filter(id => !this.rejected_ids.contains(id));
        if (will_added.length === 0) {
            return this;
        }

        const predicate = (i: Item) => {
            if (i instanceof Tweet) {
                const id = i.getMainStatus().user.id;
                return will_added.indexOf(id) === -1;
            }
            return true;
        };

        const next_home = this.home.filter(predicate).toList();
        const next_mention = this.mention.filter(predicate).toList();
        const home_updated = next_home.size !== this.home.size;
        const mention_updated = next_mention.size !== this.mention.size;
        const next_rejected_ids = this.rejected_ids.merge(will_added);

        // XXX:
        // Next focus index calculation is too complicated.  I skipped it.

        return new TimelineState(
            this.kind,
            home_updated ? next_home : this.home,
            mention_updated ? next_mention : this.mention,
            this.user,
            this.notified,
            next_rejected_ids,
            this.no_retweet_ids,
            this.focus_index
        );
    }
Example #7
0
    addNoRetweetUserIds(ids: number[]) {
        const predicate = (i: Item) => {
            if (i instanceof Tweet) {
                return !i.isRetweet() || ids.indexOf(i.retweeted_status.user.id) === -1;
            } else {
                return true;
            }
        };

        const next_home = this.home.filter(predicate).toList();
        const next_mention = this.mention.filter(predicate).toList();
        const next_no_retweet_ids = this.no_retweet_ids.merge(ids);

        // XXX:
        // Next focus index calculation is too complicated.  I skipped it.

        return new TimelineState(
            this.kind,
            next_home,
            next_mention,
            this.user,
            this.notified,
            this.rejected_ids,
            next_no_retweet_ids,
            this.focus_index
        );
    }
Example #8
0
function updateStatusIn(items: List<Item>, status: Tweet) {
    'use strict';
    const status_id = status.id;
    const index = items.findIndex(item => {
        if (item instanceof Tweet) {
            return item.getMainStatus().id === status_id;
        } else {
            return false;
        }
    });

    if (index === -1) {
        return items;
    }

    return items.update(index, item => {
        if (item instanceof Tweet) {
            if (item.isRetweet()) {
                const cloned = item.clone();
                cloned.json.retweeted_status = status.json;
                return cloned;
            } else {
                return status;
            }
        } else {
            log.error('Never reaches here');
            return item;
        }
    });
}
function getStageNameList(stageList: List<StageConfig | RawStageConfig>) {
  if (stageList.isEmpty()) {
    return 'empty'
  } else {
    return stageList.map(s => s.name).join(',')
  }
}
Example #10
0
export function reducer(state: List<SettingItem> = List<SettingItem>(), action: ITodoAction) {

  function indexOf(uuid: string) {
    return state.findIndex((i: SettingItem) => i.uuid === action.itemId);
  }

  function createItemObj(text: string) {
    if (!text) {
      return new SettingItem();
    }
    if (text.indexOf('|') >= 0) {
      // parse the text for name|value format
      let tokens = text.split('|');
      if (tokens.length > 1) {
        return new SettingItem({name: tokens[0], value: tokens[1], completed: false, uuid: uuid.v4()});
      }
    }
    return new SettingItem({name: '[no name]', value: text, completed: false, uuid: uuid.v4()});
  }

  switch (action.type) {
    case 'ADD':
      return state.push(createItemObj(action.text));
    case 'REMOVE':
      return List<SettingItem>(state.filter((i: SettingItem) => i.uuid !== action.itemId));
    case 'UPDATE_ITEM_VALUE':
      return state.update(indexOf(action.itemId), (i: SettingItem) => i.setValue(action.text));
    case 'UPDATE_ITEM_COMPLETION':
      return state.update(indexOf(action.itemId), (i: SettingItem) => i.setCompleted(action.completed));
    default:
      return state;
  }

}
Example #11
0
const removeContact = (state: Contacts, username: string) => {
  const people: List<Contact> = state.get('people');

  return state.set('people',
    people.withMutations(p => {
      p.delete(p.findIndex(c => c.get('username') === username));
    }));
};
 it('adds the entries to the state', () => {
     const state: Map<{}, {}> = Map();
     const entries: List<string> = List.of('Trainspotting', '28 Days Later');
     const nextState: Map<{}, {}> = setEntries(state, entries);
     expect(nextState).to.equal(Map({
         entries: List.of('Trainspotting', '28 Days Later')
     }));
 });
  it('can compose Immutable::List initial states', () => {
    const state = compose(List.of('a', 'b'), List.of('c', 'd'), List.of());
    expect(List.isList(state)).to.be.true;

    const plain = state.toJS();
    expect(plain).not.to.be.null;
    expect(plain).to.deep.equal(['a', 'b', 'c', 'd']);
  });
 /**
  * Create a List or update a list if one exists, with the Map key provided and the value to push to the new/updated list
  * @param ClassName
  * @param i_key
  * @param i_value
  * @returns {T}
  */
 public listPush<T>(ClassName, i_key:string, i_value:string):any {
     var value = this.getKey(i_key);
     var model:StoreModel = this;
     if (!value)
         model = this.setKey<T>(ClassName, i_key, List<any>()) as any;
     var list:List<any> = model.getKey(i_key);
     list = list.push(i_value);
     return model.setKey<T>(ClassName, i_key, list) as T;
 }
Example #15
0
    private addChild(parent: any, child: any, index?: number) {
        var list: List<any> = this.children.get(parent.id);

        if (index === undefined) {
            index = list.size;
        }

        return this.children.set(parent.id, list.insert(index, child));
    }
const RepoReducer = (repos: List<Repository> = List.of<Repository>(), action: any): List<Repository> => {
  switch (action.type) {
    case Actions.ADD_REPO:
      const {username, repo} = action;
      return repos.push({username, repo});
    default:
      return repos;
  }
};
Example #17
0
 .flatMap(previousAuthorName => {
     if (previousAuthorName === currentCommit.authorName) {
         const currentCommitsByAuthor = previousGroup[1];
         const index = accumulator.indexOf(previousGroup);
         return new Some(accumulator.set(index, [ previousAuthorName, currentCommitsByAuthor.push(currentCommit) ]))
     } else {
         return None;
     }
 })
Example #18
0
  (state: Contacts, key: string, value) => {
    const people: List<Contact> = state.get('availablePeople');

    return state.set('availablePeople',
      people.withMutations(l => {
        for (let i = 0; i < l.count(); ++i) {
          l.update(i, v => v.set(key, value));
        }
      }));
  };
 /**
  * Create a List or update a list if one exists, with the Map key provided and the value to push to the new/updated list
  * @param ClassName
  * @param i_key
  * @param i_value
  * @returns {T}
  */
 public listPush<K>(i_key: string, i_value: K): T {
     const value = this.getKey(i_key);
     let model: StoreModel<T> = this;
     if (!value) {
         model = this.setKey(i_key, List<any>()) as any;
     }
     let list: List<any> = model.getKey(i_key);
     list = list.push(i_value);
     return model.setKey(i_key, list);
 }
Example #20
0
 public getCustomerName(appStore:AppStore) {
     let name:string = '';
     var businessId = this.getKey('businessId');
     var businessUsers:List<BusinessUser> = appStore.getState().business.get('businessUsers');
     businessUsers.forEach((businessUser:BusinessUser)=> {
         if (businessUser.getBusinessId() == businessId)
             name = businessUser.getName();
     })
     return name;
 }
Example #21
0
 public getSource(appStore:AppStore) {
     let source:string = '';
     var businessId = this.getKey('businessId');
     var businesses:List<BusinessModel> = appStore.getState().business.get('businesses');
     businesses.forEach((business:BusinessModel)=> {
         if (business.getBusinessId() == businessId)
             source = business.getKey('source');
     })
     return source;
 }
Example #22
0
 return updatedRedo.updateIn(['snapshots', 'undo'], (undoList: List<Record<ProjectSnapshot>>) => {
   // Ensure max snapshot stack size
   if(undoList.size < _SNAPSHOTS_MAX_STACKSIZE_) {
     // Insert first
     return undoList.unshift(action.payload)
   } elseĀ {
     // Remove last, insert first
     return undoList.pop().unshift(action.payload)
   }
 })
export function getAdjacencies(voucherBooks: List<EAPAVoucherBook>): List<VoucherBookAdjacency> {

    let prevIds = voucherBooks.insert(0, undefined);
    let nextIds = voucherBooks.push(undefined).skip(1);

    return voucherBooks.zipWith(
        (curr, prev, next) => getAdjacency(curr, prev, next),
        voucherBooks.insert(0, undefined),
        voucherBooks.push(undefined).skip(1)
    ).toList();
}
Example #24
0
export function moveInList<T>(list: List<T>, itemIndex: number, insertPoint: number): List<T> {
  var n = list.size;
  if (itemIndex < 0 || itemIndex >= n) throw new Error('itemIndex out of range');
  if (insertPoint < 0 || insertPoint > n) throw new Error('insertPoint out of range');
  var newArray: T[] = [];
  list.forEach((value, i) => {
    if (i === insertPoint) newArray.push(list.get(itemIndex));
    if (i !== itemIndex) newArray.push(value);
  });
  if (n === insertPoint) newArray.push(list.get(itemIndex));
  return List(newArray);
}
Example #25
0
function focusPreviousCellEditor(
  state: NotebookModel,
  action: actionTypes.FocusPreviousCellEditor
): RecordOf<DocumentRecordProps> {
  const cellOrder: List<CellId> = state.getIn(["notebook", "cellOrder"]);
  const curIndex = cellOrder.findIndex(
    (id: CellId) => id === action.payload.id
  );
  const nextIndex = Math.max(0, curIndex - 1);

  return state.set("editorFocused", cellOrder.get(nextIndex));
}
function removeCounter(state: List<number>, action: RemoveCounterAction): List<number> {
  if(state.isEmpty()) {
    throw "no counters"
  }
  if(action.index >= state.size) {
    throw "index out of bounds"
  }
  if(action.index < 0) {
    throw "index out of bounds"
  }
    return state.remove(action.index)
}
 onRated(event) {
   let key = this.talks.findIndex(e => e.id === event);
   this.talks = this.talks.update(key, talk => {
       return {
         id: talk.id,
         title: talk.title,
         speaker: talk.speaker,
         avgRating: 10,
         watched: talk.watched,
         rated: true
       };
   });
 }
Example #28
0
function createCellAppend(
  state: NotebookModel,
  action: actionTypes.CreateCellAppend
): RecordOf<DocumentRecordProps> {
  const { cellType } = action.payload;
  const notebook: ImmutableNotebook = state.get("notebook");
  const cellOrder: List<CellId> = notebook.get("cellOrder", List());
  const cell: ImmutableCell =
    cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
  const index = cellOrder.count();
  const cellId = uuid();
  return state.set("notebook", insertCellAt(notebook, cell, cellId, index));
}
Example #29
0
function searchAnnotations(search: string|null, annotations: List<Record<AnnotationColorMap>>) {
  if(search !== null) {
    const jsAnnotations = annotations.toJS()
    const fuse = new Fuse(jsAnnotations, _FUSE_OPTIONS_)
    const res: string[] = fuse.search(search)
    return annotations.filter(ann => {
      const aId = ann.getIn(['annotation', 'id'])
      return res.find(id => parseInt(id) === aId)
    })
  } else {
    return annotations
  }
}
 _.forEach(action.payload, (v, k)=> {
     var type = k.split('_')[0]
     var key = k.split('_')[1]
     var value = v;
     var accountModels:List<AccountModel> = state.getIn(['accounts']);
     var index = accountModels.findIndex((i:AccountModel) => i.getType().toLowerCase() === type.toLowerCase());
     if (index == -1)
         return state;
     accountModels = accountModels.update(index, (accountModel:AccountModel) => {
         return accountModel.setKey<AccountModel>(AccountModel, key, value);
     });
     state = state.setIn(['accounts'], accountModels);
 });