import { Provider , Injectable } from 'angular2/core' ; import { QUESTIONS } from '../../data/questions' ; import { Store } from '../store/store' ; export enum QUESTION { NEXT , PREVIOUS } export interface IChoice { id : string ; label : string ; correct : boolean ; checked ? : boolean ; toggle ( ) : void ; isCorrect ( ) : boolean ; } export interface IQuestion { id : string ; title : string ; description : string ; choices : IChoice [ ] ; toggle ( choice ) : void ; isCorrect ( ) : boolean ; } export interface IQuestionsStore { fetch ( filterId ? ) : Promise < IQuestion [ ] > ; computeResult ( questions ? ) : number ; } class Choice implements IChoice { id : string ; label : string ; correct : boolean ; checked : boolean ; constructor ( choice ? ) { if ( choice ) { this . id = choice . id ; this . label = choice . label ; this . correct = choice . correct ; this . checked = choice . checked || false ; } } toggle ( ) { this . checked = ! this . checked ; } isCorrect ( ) { return ( this . correct && this . checked ) || ( ! this . correct && ! this . checked ) ; } } export class Question implements IQuestion { id = '' ; title = '' ; description = '' ; choices : IChoice [ ] = [ ] ; constructor ( question ? ) { if ( question ) { this . id = question . id ; this . title = question . title ; this . description = question . description ; this . choices = question . choices . map ( ( choice ) => new Choice ( choice ) ) ; } } toggle ( choice ) { let index = this . find ( choice ) ; if ( index !== undefined ) { this . choices [ index ] . toggle ( ) ; } } isCorrect ( ) { return this . choices . filter ( ( choice ) => choice . isCorrect ( ) ) . length === this . choices . length ; } private find ( choice ) { return this . choices . findIndex ( ( _choice ) => _choice . id === choice . id ) ; } } @ Injectable ( ) export class QuestionsStore { private questions : IQuestion [ ] ; constructor ( questions = QUESTIONS ) { this . questions = questions . map ( ( question ) => new Question ( question ) ) ; } public save ( questions ) { Store . save ( questions ) ; } public fetch ( filterId ? ) { let data = this . questions ; if ( filterId ) { data = data . filter ( ( question ) => question . id === filterId ) ; } if ( data ) { return Promise . resolve ( data ) ; } else { return < any > ( Promise . reject ( [ ] ) ) ; } } public computeResult ( questions ? ) { return ( this . questions || questions ) . filter ( ( question ) => question . isCorrect ( ) ) . length ; } }