<commit_before>// ----------------------------
// import dependencies
// ----------------------------
import React, {Component} from 'react';
import helpers from "../utils/helpers";

class Dashboard extends Component {
    constructor(props) {
        super(props);
        this.state = { boards: [] };
    }

    componentWillMount() {
        console.log("COMPONENT MOUNTED");

        // As the page loads, grab the articles that already exist in the database
        helpers.getBoards()
            .then((response) => {
                this.setState({
                    boards: response.data
                });
                console.log("RESULTS", response);
                console.log("state", this.state.boards);
            })
    }

    getOneboard (e) {
        helpers.getOneboard({id: e.dataset.id}
        ).then((res) => {
            res.render(res)
        })
    }

    generateImage () {
        return this.state.boards.map((board) => {
            return (

{board.boardTitle}

{board.category}

                                {board.boardTitle}

            )
        })
    }

    render() {
        return (

                        { /* This is what actually generates the images */ }

My Uploaded Boards

                        { this.generateImage() }

        );
    }
};

export default Dashboard;<commit_msg>edited Dashboard<commit_after>// ----------------------------
// import dependencies
// ----------------------------
import React, {Component} from 'react';
import helpers from "../utils/helpers";

class Dashboard extends Component {
    constructor(props) {
        super(props);
        this.state = { boards: [] };
    }

    componentWillMount() {
        console.log("COMPONENT MOUNTED");

        // As the page loads, grab the articles that already exist in the database
        helpers.getBoards()
            .then((response) => {
                this.setState({
                    boards: response.data
                });
                console.log("RESULTS", response);
                console.log("state", this.state.boards);
            })
    }

    getOneboard (e) {
        helpers.getOneboard({id: e.dataset.id}
        ).then((res) => {
            res.render(res)
        })
    }

    generateImage () {
        return this.state.boards.map((board) => {
            return (

{board.boardTitle}

{board.category}

                                {board.boardTitle}

            )
        })
    }

    render() {
        return (

                        { /* This is what actually generates the images */ }

My Uploaded Boards

                        { this.generateImage() }

        );
    }
};

export default Dashboard;<|endoftext|>


<commit_before>/**
 *
 * App.react.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React, { PropTypes } from 'react';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import AppBar from 'material-ui//AppBar';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import { browserHistory } from 'react-router';

import { selectLoggedIn } from './selectors';
import { logout } from './actions';

export class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    children: PropTypes.node,
    loggedIn: PropTypes.bool.isRequired,
    loginRedirect: PropTypes.func.isRequired,
    tryLogout: PropTypes.func.isRequired,
  };

  componentWillMount() {
    if (!this.props.loggedIn) {
      browserHistory.push('/login');
    }
  }

  render() {
    const { loggedIn,
            tryLogout,
            loginRedirect } = this.props;
    return (

        <AppBar
          title="SBG Monkeys"
          iconElementLeft={<IconButton><NavigationClose /></IconButton>}
          iconElementRight={
            loggedIn ?
              <FlatButton label="logout" onTouchTap={tryLogout} /> :
                <FlatButton label="sign in" onTouchTap={loginRedirect} />}
        />
        {React.Children.toArray(this.props.children)}

    );
  }
}

const mapStateToProps = createStructuredSelector({
  loggedIn: selectLoggedIn(),
});

function mapDispatchToProps(dispatch) {
  return {
    tryLogout: () => dispatch(logout()),
    loginRedirect: () => dispatch(push('/login')),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
<commit_msg>redirect to homepage when logged in<commit_after>/**
 *
 * App.react.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React, { PropTypes } from 'react';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import AppBar from 'material-ui//AppBar';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import { browserHistory } from 'react-router';

import { selectLoggedIn } from './selectors';
import { logout } from './actions';

export class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    children: PropTypes.node,
    loggedIn: PropTypes.bool.isRequired,
    loginRedirect: PropTypes.func.isRequired,
    tryLogout: PropTypes.func.isRequired,
  };

  componentWillMount() {
    if (this.props.loggedIn) {
      browserHistory.push('/');
    } else {
      browserHistory.push('/login');
    }
  }

  render() {
    const { loggedIn,
            tryLogout,
            loginRedirect } = this.props;
    return (

        <AppBar
          title="SBG Monkeys"
          iconElementLeft={<IconButton><NavigationClose /></IconButton>}
          iconElementRight={
            loggedIn ?
              <FlatButton label="logout" onTouchTap={tryLogout} /> :
                <FlatButton label="sign in" onTouchTap={loginRedirect} />}
        />
        {React.Children.toArray(this.props.children)}

    );
  }
}

const mapStateToProps = createStructuredSelector({
  loggedIn: selectLoggedIn(),
});

function mapDispatchToProps(dispatch) {
  return {
    tryLogout: () => dispatch(logout()),
    loginRedirect: () => dispatch(push('/login')),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
<|endoftext|>


<commit_before>
var overlay = Titanium.UI.createView();
var bottomOverlay = Titanium.UI.createView({
	width: "100%",
	height: "150px",
	bottom: "0px",
	backgroundColor: 'white',
});
var button = Titanium.UI.createButton({
	height:"90%",
	borderRadius:"20px",
	width:"30%",
	backgroundColor:"red",
	title : 'Record',
});
button.addEventListener('click', function() {
	Ti.Media.startVideoCapture();
});
overlay.add(bottomOverlay);
bottomOverlay.add(button);

Titanium.Media.showCamera( {
	mediaTypes: 			Titanium.Media.MEDIA_TYPE_VIDEO,
	videoMaximumDuration: 	10000, //Keep it short for now.
	videoQuality: 			Titanium.Media.QUALITY_HIGH,
	saveToPhotoGallery: 	true,
	allowEditing: 			true,
	showControls : false,
	overlay : overlay,
	success:function(e) {
		Ti.Media.setCameraFlashMode(Ti.Media.CAMERA_FLASH_OFF);
		Ti.Media.saveToPhotoGallery(e.media, {
			success: function(event) {
				Ti.Media.hideCamera();

			},
			error: function(evt) {
				alert("Failed to save video to gallery");
			},
		});
	},
	error:function(error) {alert("Error: " + error);},
});

//HintText for the TextArea field.
if ($.videoDesc.value.length > 0) {
	$.textAreaHint.hide();
}

$.videoDesc.addEventListener('change', function(e){
	if (e.source.value.length > 0) {
		$.textAreaHint.hide();
	}
	else {
		$.textAreaHint.show();
	}
});

$.textAreaHint.addEventListener('click', function(e){
	$.videoDesc.focus();
});
<commit_msg>video recording<commit_after>var recording = 0;
var overlay = Titanium.UI.createView();
var bottomOverlay = Titanium.UI.createView({
	width: "100%",
	height: "150px",
	bottom: "0px",
	backgroundColor: 'white',
});
var button = Titanium.UI.createButton({
	height:"90%",
	borderRadius:"20px",
	width:"30%",
	backgroundColor:"red",
	title : 'Record',
});
var cancelBtn = Titanium.UI.createButton({
	right:"5%",
	height:"90%",
	borderRadius:"30px",
	width:"30%",
	backgroundColor:"gray",
	title:"Cancel"
});
bottomOverlay.add(cancelBtn);
overlay.add(bottomOverlay);
bottomOverlay.add(button);
button.addEventListener('click', function() {
	if (recording==0) {
		Titanium.Media.startVideoCapture();
		button.title = "Recording...";
		recording = 1;
	} else {
		Titanium.Media.stopVideoCapture();
		recording = 0;
	}
});

Titanium.Media.showCamera( {
	mediaTypes: 			Titanium.Media.MEDIA_TYPE_VIDEO,
	videoMaximumDuration: 	10000, //Keep it short for now.
	videoQuality: 			Titanium.Media.QUALITY_HIGH,
	saveToPhotoGallery: 	true,
	showControls : false,
	overlay : overlay,
	autohide:false,
	success:function(event) {
		Ti.Media.setCameraFlashMode(Ti.Media.CAMERA_FLASH_OFF);
		Ti.Media.saveToPhotoGallery(event.media, {
			success: function(event) {
				Ti.Media.hideCamera();

			},
			error: function(evt) {
				alert("Failed to save video to gallery");
			},
		});
	},
	error:function(error) {alert("Error: " + error);},
});

//HintText for the TextArea field.
if ($.videoDesc.value.length > 0) {
	$.textAreaHint.hide();
}

$.videoDesc.addEventListener('change', function(e){
	if (e.source.value.length > 0) {
		$.textAreaHint.hide();
	}
	else {
		$.textAreaHint.show();
	}
});

$.textAreaHint.addEventListener('click', function(e){
	$.videoDesc.focus();
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';

export default Ember.Controller.extend(Bindings, {
  logPusherEvents: true,
  PUSHER_SUBSCRIPTIONS: {
    proposals: ['push']
  },
  posList: ENV.posList,
  needs: ['application'],
  currentUser: Ember.computed.alias('controllers.application.currentUser'),
  justVoted: false,
  isOpen: function() {
    return (this.get("model.state") === "open");
  }.property("model.state"),
  isMine: function() {
    return (this.get("model.user") === this.get("currentUser"));
  }.property("model.user", "currentUser"),
  canChange: function() {
    return (this.get("isOpen") && this.get("isMine"));
  }.property("isOpen", "isMine"),
  partialName: function() {
    return "proposal/" + this.get("model.type").dasherize();
  }.property("model.type"),
  actions: {
    startEdit: function() {
      this.set("isEditing", true);
    },
    submitEdit: function() {
      var _this = this;
      this.send("log", "proposal", "edit");
      this.get("model").save().then(
        function() {
          _this.set("isEditing", false);
        },
        function() {
          // apparently, just defining this function
          // makes everything work. weird.
        }
      );
    },
    withdraw: function() {
      var _this = this;
      Ember.$.post(ENV.api + "/proposals/" + this.model.get("id") + "/withdraw",
      {}, function(data) {
        _this.store.pushPayload('proposal', data);
        _this.send("log", "proposal", "withdraw");
      });
    },
    cancelEdit: function() {
      this.get("model").rollback();
      this.set("isEditing", false);
    },
    push: function(data) {
      this.store.pushPayload('proposal', data);
    },
  }
});
<commit_msg>Compare user ids for the "isMine" function<commit_after>import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';

export default Ember.Controller.extend(Bindings, {
  logPusherEvents: true,
  PUSHER_SUBSCRIPTIONS: {
    proposals: ['push']
  },
  posList: ENV.posList,
  needs: ['application'],
  currentUser: Ember.computed.alias('controllers.application.currentUser'),
  justVoted: false,
  isOpen: function() {
    return (this.get("model.state") === "open");
  }.property("model.state"),
  isMine: function() {
    return (this.get("model.user.id") === this.get("currentUser.id"));
  }.property("model.user.id", "currentUser.id"),
  canChange: function() {
    return (this.get("isOpen") && this.get("isMine"));
  }.property("isOpen", "isMine"),
  partialName: function() {
    return "proposal/" + this.get("model.type").dasherize();
  }.property("model.type"),
  actions: {
    startEdit: function() {
      this.set("isEditing", true);
    },
    submitEdit: function() {
      var _this = this;
      this.send("log", "proposal", "edit");
      this.get("model").save().then(
        function() {
          _this.set("isEditing", false);
        },
        function() {
          // apparently, just defining this function
          // makes everything work. weird.
        }
      );
    },
    withdraw: function() {
      var _this = this;
      Ember.$.post(ENV.api + "/proposals/" + this.model.get("id") + "/withdraw",
      {}, function(data) {
        _this.store.pushPayload('proposal', data);
        _this.send("log", "proposal", "withdraw");
      });
    },
    cancelEdit: function() {
      this.get("model").rollback();
      this.set("isEditing", false);
    },
    push: function(data) {
      this.store.pushPayload('proposal', data);
    },
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.validate', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/validate/:id', {
    templateUrl: 'templates/validate.html',
    controller: 'ValidateCtrl'
  });
}])

.controller('ValidateCtrl', function($http, $location, $scope, $routeParams) {
    var url = '/api/comptes/' + $routeParams.id;

    function set(v) {
	$http.put(url, v).success(function (resp) {
	    if (resp && resp.success) {
		$scope.finished = true;
	    }
	}).error(function (err) {
	    alert(err);
	});
    }

    $http.get(url).success(function (sv) {
	if (sv.error) {
	    alert(sv);
	} else {
	    set(sv.v);

	}
    }).error(function (err) {
	alert(err);
    });
});
<commit_msg>client side: fix /validate/xxx url<commit_after>'use strict';

angular.module('myApp')

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/validate/:id', {
    templateUrl: 'templates/validate.html',
    controller: 'ValidateCtrl'
  });
}])

.controller('ValidateCtrl', function($http, $location, $scope, $routeParams) {
    var url = '/api/comptes/' + $routeParams.id;

    function set(v) {
	$http.put(url, v).success(function (resp) {
	    if (resp && resp.success) {
		$scope.finished = true;
	    }
	}).error(function (err) {
	    alert(err);
	});
    }

    $http.get(url).success(function (sv) {
	if (sv.error) {
	    alert(sv);
	} else {
	    set(sv.v);

	}
    }).error(function (err) {
	alert(err);
    });
});
<|endoftext|>


<commit_before>module.exports = {
  _id: '_design/views',
  views: {
    queue: {
      map: function(doc) {
        if (doc.type === 'donation') {
          emit(doc.email, doc.amount)
        }
      }
    }
  }
}
<commit_msg>Only include donations in queue<commit_after>module.exports = {
  _id: '_design/views',
  views: {
    queue: {
      map: function(doc) {
        if (doc.type === 'donation' && doc.state === 'in_queue') {
          emit(doc.email, doc.amount)
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

(function() {
  var facetFilter = angular.module('facetFilter', []);

  facetFilter.filter('facet', function(Facet) {
    return _.memoize(function(records) {
      return Facet.filter(records);
    });
  });
})();
<commit_msg>Facet filter: add custom hash function<commit_after>'use strict';

(function() {
  var facetFilter = angular.module('facetFilter', []);

  facetFilter.filter('facet', function() {
    var facet_filter_fn = function(Facet) {
      return Facet.filter(records);
    };

    // The default hash function may confuse two arrays of objects
    // of the same length as the same set of records.
    var hash_fn = function(records) {
      JSON.stringify(records);
    };

    return _.memoize(facet_filter_fn, hash_fn);
  });
})();
<|endoftext|>


<commit_before>const sass = require('gulp-sass');
const named = require('vinyl-named');
const rename = require('gulp-rename');
const path = require('path');
const fs = require('fs');
const merge = require('merge-stream');
const gulpIf = require('gulp-if');
const sourcemaps = require('gulp-sourcemaps');
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const header = require('gulp-header');

const browserSync = require('browser-sync').create();

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

module.exports = {
    assign: sassTask
};

function sassTask (gulp, options) {
    /*
    var series = options.sassFiles.map(function (sassFile) {
        return function (callback) {
            return gulp.src({cwd: 'shortcode/*'}, '')
                .pipe(sass().on('error', sass.logError))
                .pipe(gulp.dest('bundle'));
        };
    });
    */

    function getFolders(dir) {
        return fs.readdirSync(dir)
            .filter(function(file) {
                return fs.statSync(path.join(dir, file)).isDirectory();
            });
    }

    var series = options.sassFiles.map(function (entry) {
        if (entry.forEachFolderIn) {
            var folders = getFolders(entry.forEachFolderIn);

            var tasks = folders.map(function (folder) {
                return function () {
                    return sassProcess(
                        path.join(entry.forEachFolderIn, folder, entry.input),
                        path.join(entry.forEachFolderIn, folder, entry.output),
                        entry
                    );
                }
            });

            return gulp.series(tasks);
        }

        return function () {
            return sassProcess(entry.input, entry.output, entry);
        }
    });

    function sassProcess (input, output, entry) {
        return gulp.src(input)
            .pipe(plumber({
                errorHandler: notify.onError(err => ({
                    title:   'Styles',
                    message: err.message
                }))
            }))
            .pipe(gulpIf(isDevelopment, sourcemaps.init()))
            .pipe(autoprefixer('last 2 version', '> 1%', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
            .pipe(sass({
                outputStyle: isDevelopment ? 'nested' : 'compressed',
                includePaths: [
                    'bower_components',
                    'node_modules'
                ].concat(
                    options.sassIncludePaths
                )
            }).on('error', sass.logError))
            .pipe(gulpIf(isDevelopment, sourcemaps.write()))
            .pipe(gulpIf(entry.header, header(
                (entry.header || {}).template,
                (entry.header || {}).values
            )))
            .pipe(gulp.dest(output))
            .pipe(gulpIf(isDevelopment, browserSync.stream()));
    }

    gulp.task('sass', gulp.series(series));

    gulp.task('sass:watch', gulp.series(
        'sass',
        function () {
            var toWatch = options.sassFiles.map((sassFile) => {
                if (sassFile.forEachFolderIn) {
                    return path.join(
                        sassFile.forEachFolderIn,
                        '*',
                        sassFile.input
                    );
                }

                return sassFile.input;
            });

            // console.log(toWatch);

            browserSync.init({
                proxy: options.proxyServer
            });

            gulp.watch(options.watchFilesAndReload).on('change', browserSync.reload)

            gulp.watch(
                toWatch,
                gulp.series('sass')
            );
        }
    ))
}
<commit_msg>require autoprefixer<commit_after>const sass = require('gulp-sass');
const named = require('vinyl-named');
const rename = require('gulp-rename');
const path = require('path');
const fs = require('fs');
const merge = require('merge-stream');
const gulpIf = require('gulp-if');
const sourcemaps = require('gulp-sourcemaps');
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const header = require('gulp-header');
const autoprefixer = require('gulp-autoprefixer');

const browserSync = require('browser-sync').create();

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

module.exports = {
    assign: sassTask
};

function sassTask (gulp, options) {
    /*
    var series = options.sassFiles.map(function (sassFile) {
        return function (callback) {
            return gulp.src({cwd: 'shortcode/*'}, '')
                .pipe(sass().on('error', sass.logError))
                .pipe(gulp.dest('bundle'));
        };
    });
    */

    function getFolders(dir) {
        return fs.readdirSync(dir)
            .filter(function(file) {
                return fs.statSync(path.join(dir, file)).isDirectory();
            });
    }

    var series = options.sassFiles.map(function (entry) {
        if (entry.forEachFolderIn) {
            var folders = getFolders(entry.forEachFolderIn);

            var tasks = folders.map(function (folder) {
                return function () {
                    return sassProcess(
                        path.join(entry.forEachFolderIn, folder, entry.input),
                        path.join(entry.forEachFolderIn, folder, entry.output),
                        entry
                    );
                }
            });

            return gulp.series(tasks);
        }

        return function () {
            return sassProcess(entry.input, entry.output, entry);
        }
    });

    function sassProcess (input, output, entry) {
        return gulp.src(input)
            .pipe(plumber({
                errorHandler: notify.onError(err => ({
                    title:   'Styles',
                    message: err.message
                }))
            }))
            .pipe(gulpIf(isDevelopment, sourcemaps.init()))
            .pipe(autoprefixer('last 2 version', '> 1%', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
            .pipe(sass({
                outputStyle: isDevelopment ? 'nested' : 'compressed',
                includePaths: [
                    'bower_components',
                    'node_modules'
                ].concat(
                    options.sassIncludePaths
                )
            }).on('error', sass.logError))
            .pipe(gulpIf(isDevelopment, sourcemaps.write()))
            .pipe(gulpIf(entry.header, header(
                (entry.header || {}).template,
                (entry.header || {}).values
            )))
            .pipe(gulp.dest(output))
            .pipe(gulpIf(isDevelopment, browserSync.stream()));
    }

    gulp.task('sass', gulp.series(series));

    gulp.task('sass:watch', gulp.series(
        'sass',
        function () {
            var toWatch = options.sassFiles.map((sassFile) => {
                if (sassFile.forEachFolderIn) {
                    return path.join(
                        sassFile.forEachFolderIn,
                        '*',
                        sassFile.input
                    );
                }

                return sassFile.input;
            });

            // console.log(toWatch);

            browserSync.init({
                proxy: options.proxyServer
            });

            gulp.watch(options.watchFilesAndReload).on('change', browserSync.reload)

            gulp.watch(
                toWatch,
                gulp.series('sass')
            );
        }
    ))
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import config from '../config/environment';

// copied and modified from http://ember.zone/handling-environment-data-with-ember-js/
export function initialize(/* container, application */) {
  // Check to we have required optionsConfig, even if only {}
  if(config.optionsConfig === undefined) {
    // possible config properties:
    //   metaNamePrefix - default config.modulePrefix
    //   valueAttr - default 'content'
    //   parentPathIgnoreUpTo - index of number of parent parts in path to ignore, default 2
    throw new Ember.Error("The application must be set up for options with optionsConfig, even if only {} for default config, in config/environment.js.");
  }

  var OptionsReader = function OptionsReader() {

    this.readOptionsKeys = function() {
      var _mapType = function(val) {
        return "" === val ? null : "true" === val ? true : "false" === val ? false : (-1 !== val.indexOf(",") && (val = val.split(",")), val);
      };

      // Grab all the meta tags from the DOM.
      var metaTags = Ember.$("meta");
      var options = Ember.Object.create();
      var metaNamePrefix = config.optionsConfig.metaNamePrefix || config.modulePrefix;
      var re = new RegExp(metaNamePrefix + '\/');

      // Process each of the discovered meta tags.
      for(var i=0; i < metaTags.length; i++) {
        var valueAttr = config.optionsConfig.valueAttr || 'content';
        var key = Ember.$(metaTags[i]).attr('name');
        var value = Ember.$(metaTags[i]).attr(valueAttr);

        // Does the meta tag start with our prefix?
        if (re.test(key)) {
          var nameParts = Ember.A(key.split('/'));
          var propertyName = nameParts.get('lastObject');

          // ignore first 3 parents parts in path, aka MODULE_PREFIX/initializers/options
          var parentPathIgnoreUpTo = config.optionsConfig.parentPathIgnoreUpTo || 2;

          // also skip actual propertyName
          var parents = nameParts.filter(function(item, index) {
            if (index > parentPathIgnoreUpTo && item !== propertyName) {
              return true;
            }
            return false;
          });

          // loop through nesting and create parent objects if necessary
          var currentObject = options;
          if (parents.length > 0 ) {
            parents.forEach(function(item, index) {
              if (!currentObject.hasOwnProperty(item)) {
                currentObject[item] = Ember.Object.create();
              }

              currentObject = currentObject[item];

              // is this last parent set property value
              if (parents.length === index + 1) {
                // Map the string values to actual types.
                currentObject[propertyName] = _mapType(value);
              }
            });
          } else {
            currentObject[propertyName] = _mapType(value);
          }
        }
      }

      return options;
    };
  };

  var optionsReader = new OptionsReader();
  config.options = optionsReader.readOptionsKeys();
}

export default {
  name: 'options',
  initialize: initialize
};
<commit_msg>Handle default of parentPathIgnoreUpTo properly to allow passing 0<commit_after>import Ember from 'ember';
import config from '../config/environment';

// copied and modified from http://ember.zone/handling-environment-data-with-ember-js/
export function initialize(/* container, application */) {
  // Check to we have required optionsConfig, even if only {}
  if(config.optionsConfig === undefined) {
    // possible config properties:
    //   metaNamePrefix - default config.modulePrefix
    //   valueAttr - default 'content'
    //   parentPathIgnoreUpTo - index of number of parent parts in path to ignore, default 2
    throw new Ember.Error("The application must be set up for options with optionsConfig, even if only {} for default config, in config/environment.js.");
  }

  var OptionsReader = function OptionsReader() {

    this.readOptionsKeys = function() {
      var _mapType = function(val) {
        return "" === val ? null : "true" === val ? true : "false" === val ? false : (-1 !== val.indexOf(",") && (val = val.split(",")), val);
      };

      // Grab all the meta tags from the DOM.
      var metaTags = Ember.$("meta");
      var options = Ember.Object.create();
      var metaNamePrefix = config.optionsConfig.metaNamePrefix || config.modulePrefix;
      var re = new RegExp(metaNamePrefix + '\/');

      // Process each of the discovered meta tags.
      for(var i=0; i < metaTags.length; i++) {
        var valueAttr = config.optionsConfig.valueAttr || 'content';
        var key = Ember.$(metaTags[i]).attr('name');
        var value = Ember.$(metaTags[i]).attr(valueAttr);

        // Does the meta tag start with our prefix?
        if (re.test(key)) {
          var nameParts = Ember.A(key.split('/'));
          var propertyName = nameParts.get('lastObject');

          // ignore first 3 parents parts in path, aka MODULE_PREFIX/initializers/options
          var parentPathIgnoreUpTo = Ember.getWithDefault(config, 'optionsConfig.parentPathIgnoreUpTo', 2);

          // also skip actual propertyName
          var parents = nameParts.filter(function(item, index) {
            if (index > parentPathIgnoreUpTo && item !== propertyName) {
              return true;
            }
            return false;
          });

          // loop through nesting and create parent objects if necessary
          var currentObject = options;
          if (parents.length > 0 ) {
            parents.forEach(function(item, index) {
              if (!currentObject.hasOwnProperty(item)) {
                currentObject[item] = Ember.Object.create();
              }

              currentObject = currentObject[item];

              // is this last parent set property value
              if (parents.length === index + 1) {
                // Map the string values to actual types.
                currentObject[propertyName] = _mapType(value);
              }
            });
          } else {
            currentObject[propertyName] = _mapType(value);
          }
        }
      }

      return options;
    };
  };

  var optionsReader = new OptionsReader();
  config.options = optionsReader.readOptionsKeys();
}

export default {
  name: 'options',
  initialize: initialize
};
<|endoftext|>


<commit_before>function ItemsController($scope, Items, Pagination, $timeout, $injector, $window, $fileUploader, Merchants, $resource){
  $injector.invoke(BasicController, this, {$scope: $scope});
  $scope.resource = Items
  $scope.searchOptions.fields = ['name']
  $scope.searchOptions.tooltip = "请输入商品名称"
  $scope.editView = "views/item/edit.html"
  $scope.profileAvatar = "img/avatar.jpg"
  $scope.profileFields = [
    {name: "merchantID", title: "业主ID", required: true, listHide: true, hide: true, isProfileHide:true, createHide: true},
    {name: "code", title: "编码", required: true, hide: true, createHide:true},
    {name: "name", title: "品名", required: true, hide:false},
    {name: "model", title: "型号", createHide:true, hide:false},
    {name: "price", title: "售价", required: true, value:function(entity) {
      entity.fieldClass = entity.fieldClass || {}
      return (entity.price/100).toFixed(2)}, hide:false},
    {name: "mnemonicCode", title: "助记码", listHide: true, createHide:true, hide:true, isProfileHide:true},
    {name: "tags", title: "类别", createHide: true, listHide: true, hide: false, isProfileHide:false, value: function (entity) {
      if(entity.hasOwnProperty('tags') && entity.tags.length) {
        return entity.tags.toString();
      } else {
        return "未分类"
      }
    }},
    {name: "desc", title: "描述", listHide: true, hide:false},
    {name: "createdAt", title: "创建日期", createHide: true, hide: true, createHide:true},
    {name: "status", title: "状态", value:function(entity){
      entity.fieldClass = entity.fieldClass || {}
      if(entity.status === 'sale') {
        entity.fieldClass.status = "label label-success"
        return "上架"
      } else if(entity.status === 'desale') {
        entity.fieldClass.status = "label label-warning"
        return "下架"
      } else {
        return entity.status
      }
    }, hide:true, createHide: true},
    {name: "images", title: "照片", createHide: false, listHide: true, hide: true, isProfileHide:true, isImg:true, value:function (entity) {
      if (entity.hasOwnProperty('images')) {
        return entity.images.toString();
      } else {
        return '尚未上传照片';
      }
    }},
    {name: "updatedAt", title: "更新日期", createHide: false, listHide: true, hide: true, isProfileHide:true}
  ];

  // delete a item
  $scope.remove = function (entity) {
    var obj = {
      id: entity.id,
      status: 'removed'
    }
    Items.update(obj, function (result) {
      $scope.showList();
    }, function (err) {
      console.log('err:\n', err);
    });
  }

  // three params for upload img
  var subdir = 'images';
  var comments = '';
  var uniqueFilename = true;

  // update a item
  $scope.update = function (entity) {
    var tags = [];
    tags.push(entity.tags[0]);
    var obj = entity;
    var price = parseFloat(entity.price*100);
    obj.price = price;
    obj.tags = tags;
    var resource = new $scope.resource(obj);
    resource.$update(function (err) {
      $scope.showList()
    }, function (err) {
      console.log('update error:', err, entity)
    })
  }

  // init for edit page
  $scope.showEdit = function (entity) {
    if (!entity.hasOwnProperty('tags')) {
      entity.tags = [''];
    }
    entity.price = (entity.price/100).toFixed(2);
    $scope.entity = entity;
    $scope.activeView = "views/item/edit.html";
    $scope.trackListPage.activeView = '';
    $scope.showChangePic = false
  }

  // in edit page we can change the pic of the item
  $scope.showChangePic = false
  $scope.changePic = function () {
    $scope.showChangePic = !$scope.showChangePic;
    var uploaderForEdit = $scope.uploaderForEdit = $fileUploader.create({
      scope: $scope,
      url: window.restful.baseURL + '/upload?subdir=' + subdir + '&comments=' + comments + '&uniqueFilename=' + uniqueFilename
    });
    uploaderForEdit.bind('success', function(event, xhr, item, res) {
      var obj = {
        id: $scope.entity.id,
        images: {
          $push: res[0].filename
        },
        imagesID:{
          $push: res[0].id
        }
      }
      Items.update(JSON.stringify(obj), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    });
    uploaderForEdit.bind('completeall', function(event, items) {
      $scope.showList();
      uploaderForEdit = $scope.uploaderForEdit = {};
    });
  };

  // method for change the item's pic
  $scope.uploadForEdit = function () {
    var queue = $scope.uploaderForEdit.queue;
    if (queue.length > 3) {
      alert('上传图片不能超过3张！');
      return;
    }
    for (var i = 0; i < queue.length; i++) {
      if ((queue[i].file.size/1000000)>2) {
        alert('图片大小必须小于2M');
        return;
      }
    }
    if ($scope.entity.hasOwnProperty('images') && $scope.entity.images.length) {
      var qsItem = {
        "id": $scope.entity.id,
        "images": {$pullAll: $scope.entity.images},
        "imagesID": {$pullAll: $scope.entity.imagesID}
      }
      Items.update(JSON.stringify(qsItem), function (result) {
        var Upload = $resource(window.restful.baseURL+'/upload/:id', {id:'@id'});
        var arr = $scope.entity.imagesID || [];
        var jici = 0;
        arr.forEach(function (id) {
          Upload.delete({id: id}, function () {
            jici++;
            if (jici == arr.length) {
              $scope.uploaderForEdit.uploadAll();
            }
          });
        })
      }, function (err) {
        console.log('err:\n', err);
      });
    } else {
      $scope.uploaderForEdit.uploadAll();
    }

  }

  // init for profile page
  $scope.showProfile = function (entity) {
    Items.get({id:entity.id}, function (result) {
      $scope.entity = result;
      $scope.activeView = "views/item/itemProfile.html";
      $scope.trackListPage.activeView = '';
      if (result.hasOwnProperty('images') && result.images.length) {
        $scope.imgs = ($scope.entity.images).map(function (img) {
          return window.restful.baseImgSrcURL + img;
        });
      } else {
        $scope.imgs = [];
      }
    }, function (err) {
      console.log('err:\n', err);
    });
  }

  // init for create page
  $scope.showCreate = function () {
    $scope.entity = {};
    $scope.isShowUpload = false;
    $scope.isHideButton = false;
    $scope.info = false;
    $scope.alert = '';
    $scope.msg = '';
    $scope.activeView = "views/item/create.html";
    $scope.trackListPage.activeView = '';
    var uploader = $scope.uploader = $fileUploader.create({
      scope: $scope,
      url: window.restful.baseURL + '/upload?subdir=' + subdir + '&comments=' + comments + '&uniqueFilename=' + uniqueFilename
    });
    uploader.bind('success', function(event, xhr, item, res) {
      var obj = {
        id: $window.item.id,
        images: {
          $push: res[0].filename
        },
        imagesID:{
          $push: res[0].id
        }
      }
      Items.update(JSON.stringify(obj), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    });
    uploader.bind('completeall', function(event, items) {
      $scope.showList();
      uploader = $scope.uploader = {};
    });
    Merchants.get({id:$scope.currentMerchant.merchant.id}, function (result) {
      $scope.merchantItemTags = result.itemTags || [];
    }, function (err) {
      console.log('err:\n', err);
    })
  }
  $scope.uploadInCreate = function () {
    var queue = $scope.uploader.queue;
    if (queue.length > 3) {
      alert('上传图片不能超过3张！');
      return;
    }
    for (var i = 0; i < queue.length; i++) {
      if ((queue[i].file.size/1000000)>2) {
        alert('图片大小必须小于2M');
        return;
      }
    }
    $scope.uploader.uploadAll();

  }
  // method for create a item
  $scope.create = function (entity) {
    entity.createdAt = Math.round(new Date().getTime() / 1000);
    entity.merchantID = $scope.currentMerchant.merchant.id;
    var obj = {
      createdAt : Math.round(new Date().getTime() / 1000),
      merchantID: $scope.currentMerchant.merchant.id,
      code: $scope.entity.code,
      mnemonicCode:'',
      name: $scope.entity.name,
      price: parseFloat($scope.entity.price*100),
      desc: $scope.entity.desc,
      model: $scope.entity.model,
      tags: [],
      images:[],
      imagesID:[]
    };
    obj.tags.push($scope.entity.tags);
    var tempArr = [];
    obj.tags.forEach(function (tag) {
      if ($scope.merchantItemTags.indexOf(tag) == -1) {
        tempArr.push(tag);
      }
    });
    if (tempArr.length) {
      var qsMerchant = {
        "id": $scope.currentMerchant.merchant.id,
        "itemTags": {$pushAll: tempArr}
      }
      Merchants.update(JSON.stringify(qsMerchant), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    }
    Items.save(obj, function (result) {
      $window.item = {};
      $window.item.id = result.id;
      $window.item.tags = result.tags;
      $scope.isShowUpload = true;
      $scope.isHideButton = true;
      $scope.info = true;
      $scope.alert = 'alert alert-success';
      $scope.msg = '菜品信息创建成功，请上传菜品照片，完成最后的创建';
      $timeout(function () {
        $scope.info = false;
      }, 2000);
    }, function (err) {
      $scope.info = true;
      $scope.alert = 'alert alert-danger';
      $scope.msg = '菜品信息创建失败';
      $timeout(function () {
        $scope.info = false;
      }, 4000);
    });
  }
  $scope.paramsForDelete = 'removed';
  // some params for list page
  $scope.params['status'] = JSON.stringify({
    $ne: 'removed'
  });
  $scope.countQs['status'] = JSON.stringify({
    $ne: 'removed'
  });
  $scope.params['merchantID'] = $scope.currentMerchant.merchant.id;
  $scope.countQs['merchantID'] = $scope.currentMerchant.merchant.id;
  $scope.defaultString = "name";
  widthFunctions();
}
<commit_msg>Add: 商品列表中分类信息<commit_after>function ItemsController($scope, Items, Pagination, $timeout, $injector, $window, $fileUploader, Merchants, $resource){
  $injector.invoke(BasicController, this, {$scope: $scope});
  $scope.resource = Items
  $scope.searchOptions.fields = ['name']
  $scope.searchOptions.tooltip = "请输入商品名称"
  $scope.editView = "views/item/edit.html"
  $scope.profileAvatar = "img/avatar.jpg"
  $scope.profileFields = [
    {name: "merchantID", title: "业主ID", required: true, listHide: true, hide: true, isProfileHide:true, createHide: true},
    {name: "code", title: "编码", required: true, hide: true, createHide:true},
    {name: "name", title: "品名", required: true, hide:false},
    {name: "model", title: "型号", createHide:true, hide:false},
    {name: "price", title: "售价", required: true, value:function(entity) {
      entity.fieldClass = entity.fieldClass || {}
      return (entity.price/100).toFixed(2)}, hide:false},
    {name: "mnemonicCode", title: "助记码", listHide: true, createHide:true, hide:true, isProfileHide:true},
    {name: "tags", title: "类别", createHide: true, listHide: false, hide: false, isProfileHide:false, value: function (entity) {
      if(entity.tags && entity.tags.length > 0) {
        return entity.tags.join(',');
      } else {
        return "未分类"
      }
    }},
    {name: "desc", title: "描述", listHide: true, hide:false},
    {name: "createdAt", title: "创建日期", createHide: true, hide: true, createHide:true},
    {name: "status", title: "状态", value:function(entity){
      entity.fieldClass = entity.fieldClass || {}
      if(entity.status === 'sale') {
        entity.fieldClass.status = "label label-success"
        return "上架"
      } else if(entity.status === 'desale') {
        entity.fieldClass.status = "label label-warning"
        return "下架"
      } else {
        return entity.status
      }
    }, hide:true, createHide: true},
    {name: "images", title: "照片", createHide: false, listHide: true, hide: true, isProfileHide:true, isImg:true, value:function (entity) {
      if (entity.hasOwnProperty('images')) {
        return entity.images.toString();
      } else {
        return '尚未上传照片';
      }
    }},
    {name: "updatedAt", title: "更新日期", createHide: false, listHide: true, hide: true, isProfileHide:true}
  ];

  // delete a item
  $scope.remove = function (entity) {
    var obj = {
      id: entity.id,
      status: 'removed'
    }
    Items.update(obj, function (result) {
      $scope.showList();
    }, function (err) {
      console.log('err:\n', err);
    });
  }

  // three params for upload img
  var subdir = 'images';
  var comments = '';
  var uniqueFilename = true;

  // update a item
  $scope.update = function (entity) {
    var tags = [];
    tags.push(entity.tags[0]);
    var obj = entity;
    var price = parseFloat(entity.price*100);
    obj.price = price;
    obj.tags = tags;
    var resource = new $scope.resource(obj);
    resource.$update(function (err) {
      $scope.showList()
    }, function (err) {
      console.log('update error:', err, entity)
    })
  }

  // init for edit page
  $scope.showEdit = function (entity) {
    if (!entity.hasOwnProperty('tags')) {
      entity.tags = [''];
    }
    entity.price = (entity.price/100).toFixed(2);
    $scope.entity = entity;
    $scope.activeView = "views/item/edit.html";
    $scope.trackListPage.activeView = '';
    $scope.showChangePic = false
  }

  // in edit page we can change the pic of the item
  $scope.showChangePic = false
  $scope.changePic = function () {
    $scope.showChangePic = !$scope.showChangePic;
    var uploaderForEdit = $scope.uploaderForEdit = $fileUploader.create({
      scope: $scope,
      url: window.restful.baseURL + '/upload?subdir=' + subdir + '&comments=' + comments + '&uniqueFilename=' + uniqueFilename
    });
    uploaderForEdit.bind('success', function(event, xhr, item, res) {
      var obj = {
        id: $scope.entity.id,
        images: {
          $push: res[0].filename
        },
        imagesID:{
          $push: res[0].id
        }
      }
      Items.update(JSON.stringify(obj), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    });
    uploaderForEdit.bind('completeall', function(event, items) {
      $scope.showList();
      uploaderForEdit = $scope.uploaderForEdit = {};
    });
  };

  // method for change the item's pic
  $scope.uploadForEdit = function () {
    var queue = $scope.uploaderForEdit.queue;
    if (queue.length > 3) {
      alert('上传图片不能超过3张！');
      return;
    }
    for (var i = 0; i < queue.length; i++) {
      if ((queue[i].file.size/1000000)>2) {
        alert('图片大小必须小于2M');
        return;
      }
    }
    if ($scope.entity.hasOwnProperty('images') && $scope.entity.images.length) {
      var qsItem = {
        "id": $scope.entity.id,
        "images": {$pullAll: $scope.entity.images},
        "imagesID": {$pullAll: $scope.entity.imagesID}
      }
      Items.update(JSON.stringify(qsItem), function (result) {
        var Upload = $resource(window.restful.baseURL+'/upload/:id', {id:'@id'});
        var arr = $scope.entity.imagesID || [];
        var jici = 0;
        arr.forEach(function (id) {
          Upload.delete({id: id}, function () {
            jici++;
            if (jici == arr.length) {
              $scope.uploaderForEdit.uploadAll();
            }
          });
        })
      }, function (err) {
        console.log('err:\n', err);
      });
    } else {
      $scope.uploaderForEdit.uploadAll();
    }

  }

  // init for profile page
  $scope.showProfile = function (entity) {
    Items.get({id:entity.id}, function (result) {
      $scope.entity = result;
      $scope.activeView = "views/item/itemProfile.html";
      $scope.trackListPage.activeView = '';
      if (result.hasOwnProperty('images') && result.images.length) {
        $scope.imgs = ($scope.entity.images).map(function (img) {
          return window.restful.baseImgSrcURL + img;
        });
      } else {
        $scope.imgs = [];
      }
    }, function (err) {
      console.log('err:\n', err);
    });
  }

  // init for create page
  $scope.showCreate = function () {
    $scope.entity = {};
    $scope.isShowUpload = false;
    $scope.isHideButton = false;
    $scope.info = false;
    $scope.alert = '';
    $scope.msg = '';
    $scope.activeView = "views/item/create.html";
    $scope.trackListPage.activeView = '';
    var uploader = $scope.uploader = $fileUploader.create({
      scope: $scope,
      url: window.restful.baseURL + '/upload?subdir=' + subdir + '&comments=' + comments + '&uniqueFilename=' + uniqueFilename
    });
    uploader.bind('success', function(event, xhr, item, res) {
      var obj = {
        id: $window.item.id,
        images: {
          $push: res[0].filename
        },
        imagesID:{
          $push: res[0].id
        }
      }
      Items.update(JSON.stringify(obj), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    });
    uploader.bind('completeall', function(event, items) {
      $scope.showList();
      uploader = $scope.uploader = {};
    });
    Merchants.get({id:$scope.currentMerchant.merchant.id}, function (result) {
      $scope.merchantItemTags = result.itemTags || [];
    }, function (err) {
      console.log('err:\n', err);
    })
  }
  $scope.uploadInCreate = function () {
    var queue = $scope.uploader.queue;
    if (queue.length > 3) {
      alert('上传图片不能超过3张！');
      return;
    }
    for (var i = 0; i < queue.length; i++) {
      if ((queue[i].file.size/1000000)>2) {
        alert('图片大小必须小于2M');
        return;
      }
    }
    $scope.uploader.uploadAll();

  }
  // method for create a item
  $scope.create = function (entity) {
    entity.createdAt = Math.round(new Date().getTime() / 1000);
    entity.merchantID = $scope.currentMerchant.merchant.id;
    var obj = {
      createdAt : Math.round(new Date().getTime() / 1000),
      merchantID: $scope.currentMerchant.merchant.id,
      code: $scope.entity.code,
      mnemonicCode:'',
      name: $scope.entity.name,
      price: parseFloat($scope.entity.price*100),
      desc: $scope.entity.desc,
      model: $scope.entity.model,
      tags: [],
      images:[],
      imagesID:[]
    };
    obj.tags.push($scope.entity.tags);
    var tempArr = [];
    obj.tags.forEach(function (tag) {
      if ($scope.merchantItemTags.indexOf(tag) == -1) {
        tempArr.push(tag);
      }
    });
    if (tempArr.length) {
      var qsMerchant = {
        "id": $scope.currentMerchant.merchant.id,
        "itemTags": {$pushAll: tempArr}
      }
      Merchants.update(JSON.stringify(qsMerchant), function (result) {
      }, function (err) {
        console.log('err:\n', err);
      })
    }
    Items.save(obj, function (result) {
      $window.item = {};
      $window.item.id = result.id;
      $window.item.tags = result.tags;
      $scope.isShowUpload = true;
      $scope.isHideButton = true;
      $scope.info = true;
      $scope.alert = 'alert alert-success';
      $scope.msg = '菜品信息创建成功，请上传菜品照片，完成最后的创建';
      $timeout(function () {
        $scope.info = false;
      }, 2000);
    }, function (err) {
      $scope.info = true;
      $scope.alert = 'alert alert-danger';
      $scope.msg = '菜品信息创建失败';
      $timeout(function () {
        $scope.info = false;
      }, 4000);
    });
  }
  $scope.paramsForDelete = 'removed';
  // some params for list page
  $scope.params['status'] = JSON.stringify({
    $ne: 'removed'
  });
  $scope.countQs['status'] = JSON.stringify({
    $ne: 'removed'
  });
  $scope.params['merchantID'] = $scope.currentMerchant.merchant.id;
  $scope.countQs['merchantID'] = $scope.currentMerchant.merchant.id;
  $scope.defaultString = "name";
  widthFunctions();
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

var winner;

function getWinner(playerMove,computerMove) {
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    console.log("Player chose " + playerMove + ".");
    console.log("Computer chose " + computerMove + ".");
    if ( ((playerMove === 'rock') && (computerMove === 'scissors')) || ((playerMove === 'paper') && (computerMove === 'rock')) || ((playerMove === 'scissors') && (computerMove === 'paper')) ) {
        winner = 'player'; console.log("Player wins.")
    } else if (playerMove === computerMove) {
        winner = 'tie'; console.log("It's a tie.")
    }
    else {
        winner = 'computer'; console.log("Computer wins.")
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var round = 0;

    while (playerWins < 5 && computerWins < 5) {

    round += 1;
    console.log("Round " + round + ":");

    getWinner(getPlayerMove(),getComputerMove());

    if (winner === 'player') {
        playerWins++; console.log("Player's score is now " + playerWins + ".");
    } else if (winner === 'computer') {
        computerWins++; console.log("Computer's score is now " + computerWins + ".");
    } else {
        console.log("Play again.");
    }
}
}

playToFive();<commit_msg>Code has been tested in Chrome console, Codecademy labs, and repl.it. Final commit.<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

var winner; // [!] I moved this variable outside of the scope of the function getWinner in order to reference its value in the playToFive function

function getWinner(playerMove,computerMove) {
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    console.log("Player chose " + playerMove + ".");
    console.log("Computer chose " + computerMove + ".");
    if ( ((playerMove === 'rock') && (computerMove === 'scissors')) || ((playerMove === 'paper') && (computerMove === 'rock')) || ((playerMove === 'scissors') && (computerMove === 'paper')) ) {
        winner = 'player'; console.log("Player wins.")
    } else if (playerMove === computerMove) {
        winner = 'tie'; console.log("It's a tie.")
    }
    else {
        winner = 'computer'; console.log("Computer wins.")
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var round = 0;
    while (playerWins < 5 && computerWins < 5) { // plays a new round until computer or player has 5 wins
    round += 1; console.log("Round " + round + ":"); // logs the current round to the console
    getWinner(getPlayerMove(),getComputerMove()); // executes the round and returns the winner
        if (winner === 'player') { // updates score
            playerWins++; console.log("Player's score is now " + playerWins + ".");
        } else if (winner === 'computer') {
            computerWins++; console.log("Computer's score is now " + computerWins + ".");
        } else {
        console.log("Play again.");
        }
    }
}

playToFive(); // calls playToFive function to begin game<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>created new getWinner code<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {

    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return (move) ? getInput: move;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return (move) ? randomPlay : move;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
  if ( playerMove===computerMove) {
    return "The result is a tie!";
 }
 else if (playerMove==="rock"){

    if(computerMove==="scissors"); {

        return "rock wins";
    }
    { "paper wins";
 }
 if (playerMove===computerMove) {
    return "The result is a tie!";
 }
 else if (playerMove==="scissors") {

    if(computerMove==="paper"); {

        return "scissors wins";
    }
     "rock wins";
 }
if (playerMove===computerMove){
    return "The result is a tie!";
}
else if (playerMove==="paper") {

    if(computerMove==="rock");
return "paper wins";
}
else "scissors win";
}
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Task 3<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput;

}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}

function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();

}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove === "rock") {
        if (computerMove === "rock") {
            return "tie";
        }
        else if (computerMove === "scissors") {
            return "player";
        }
        else if (computerMove === "paper") {
            return "computer";
        }
    }
    if (playerMove === "paper") {
        if (computerMove === "rock") {
            return "player";
        }
        else if (computerMove === "scissors") {
            return "computer";
        }
        else if (computerMove ==="paper") {
            return "tie";
        }
    }
    if (playerMove === "scissors") {
        if (computerMove === "rock") {
            return "computer";
        }
        else if (computerMove === "scissors") {
            return "tie";
        }
        else if (computerMove === "paper") {
            return "player";
        }
    }
    return winner;
}
function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    while (playerWins<5 && computerWins<5) {
        var playerMove = getPlayerMove(move);
        var computerMove = getComputerMove(move);
        var winner = getWinner(playerMove, computerMove);
        console.log("playerWins", playerWins);
        console.log("computerWins", computerWins);
        console.log("winner:", winner);
        if (winner === undefined){
             console.log("Not a Valid Move! Player:" + playerMove + ", Computer:" + computerMove);
        }
        if (winner === "player") {
            playerWins += 1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (winner === "computer") {
            computerWins +=1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (winner === "tie") {
            computerWins +=1;
            playerWins +=1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('You tied. ' + 'The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (playerWins === 5 && computerWins < 5) {
            console.log("You win!");
        } else if (playerWins < 5 && computerWins === 5) {
            console.log("You lose, try again.");
        } else if (playerWins === computerWins) {
            console.log("It's a tie!");
        }

    }
    return [playerWins, computerWins];

}
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
// console.log("win1:", getWinner("foo", "bar"));
// console.log("win2:", getWinner("rock", "paper"));
playToFive();
<commit_msg>project finalized<commit_after>'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}

function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();

}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if (playerMove === "rock") {
        if (computerMove === "rock") {
            return "tie";
        }
        else if (computerMove === "scissors") {
            return "player";
        }
        else if (computerMove === "paper") {
            return "computer";
        }
    }
    if (playerMove === "paper") {
        if (computerMove === "rock") {
            return "player";
        }
        else if (computerMove === "scissors") {
            return "computer";
        }
        else if (computerMove ==="paper") {
            return "tie";
        }
    }
    if (playerMove === "scissors") {
        if (computerMove === "rock") {
            return "computer";
        }
        else if (computerMove === "scissors") {
            return "tie";
        }
        else if (computerMove === "paper") {
            return "player";
        }
    }
    return winner;
}
function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    var move;
    while (playerWins<5 && computerWins<5) {
        var playerMove = getPlayerMove(move);
        var computerMove = getComputerMove(move);
        var winner = getWinner(playerMove, computerMove);
        console.log("playerWins", playerWins);
        console.log("computerWins", computerWins);
        console.log("winner:", winner);
        if (winner === undefined){
             console.log("Not a Valid Move! Player:" + playerMove + ", Computer:" + computerMove);
        }
        if (winner === "player") {
            playerWins += 1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (winner === "computer") {
            computerWins +=1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (winner === "tie") {
            computerWins +=1;
            playerWins +=1;
            console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
            console.log('You tied. ' + 'The score is currently ' + playerWins + ' to ' + computerWins + '\n');
        }
        if (playerWins === 5 && computerWins < 5) {
            console.log("You win!");
        } else if (playerWins < 5 && computerWins === 5) {
            console.log("You lose, try again.");
        } else if (playerWins === computerWins) {
            console.log("It's a tie!");
        }

    }
    return [playerWins, computerWins];

}
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
// console.log("win1:", getWinner("foo", "bar"));
// console.log("win2:", getWinner("rock", "paper"));
playToFive();
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
        if (playerMove == computerMove) {
        winner = "tie";
    } else if ((playerMove == "rock") && (computerMove == "scissors")) {
        winner = "player";
    } else if ((playerMove == "rock") && (computerMove == "paper")) {
        winner = "computer";
    } else if ((playerMove == "paper") && (computerMove == "rock")) {
        winner = "player";
    } else if (((playerMove == "paper") && (computerMove == "scissors"))) {
        winner = "computer";
    } else if (((playerMove == "scissors") && (computerMove == "rock"))) {
        winner = "player";
    } else if (((playerMove == "scissors") && (computerMove == "paper"))) {
        winner = "computer";
    } else { console.log("Error: invalid Move data!") }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // This function should continue to play Rock Paper Scissors until either the
    // player or the computer has won five times.
    // After each 'round', display some text in the console indicating who played
    // what, who won, and what the current scoreboard looks like.
    // For example,
    //  console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    //  console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    for (var playCount = 1; ((playerWins < 5) || (computerWins < 5)); console.log('Scoreboard... Player: ' + playerWins + ' Computer: ' + computerWins + '\n'), playCount += 1) {
        getPlayerMove();
        getComputerMove();
        getWinner();
        if (getWinner != "tie") {
        } else if (getWinner = "player") {
            playerWins += 1;
        } else if (getWinner = "computer") {
            computerWins += 1;
        }
        console.log('Player chose ' + playerMove + '. Computer chose ' + computerMove + '. The' + winner + 'wins round' + playCount + '.' + '\n');
    }
    return [playerWins, computerWins, playCount];
}

<commit_msg>updated playToFive<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
        if (playerMove == computerMove) {
        winner = "tie";
    } else if ((playerMove == "rock") && (computerMove == "scissors")) {
        winner = "player";
    } else if ((playerMove == "rock") && (computerMove == "paper")) {
        winner = "computer";
    } else if ((playerMove == "paper") && (computerMove == "rock")) {
        winner = "player";
    } else if (((playerMove == "paper") && (computerMove == "scissors"))) {
        winner = "computer";
    } else if (((playerMove == "scissors") && (computerMove == "rock"))) {
        winner = "player";
    } else if (((playerMove == "scissors") && (computerMove == "paper"))) {
        winner = "computer";
    } else { console.log("Error: invalid Move data!") }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // This function should continue to play Rock Paper Scissors until either the
    // player or the computer has won five times.
    // After each 'round', display some text in the console indicating who played
    // what, who won, and what the current scoreboard looks like.
    // For example,
    //  console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    //  console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    for (var playCount = 1; ((playerWins < 5) || (computerWins < 5));
    console.log('Scoreboard... Player: ' + playerWins + ' Computer: ' + computerWins + '\n'), playCount += 1) {
        getPlayerMove();
        getComputerMove();
        getWinner();
        if (getWinner != "tie") {
        } else if (getWinner == "player") {
            playerWins += 1;
        } else if (getWinner == "computer") {
            computerWins += 1;
        }
        console.log('Player chose ' + playerMove + '. Computer chose ' + computerMove + '. The' + winner + 'wins round' + playCount + '.' + '\n');
    }
    return [playerWins, computerWins, playCount];
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === "rock" && computerMove === "rock") || (playerMove === "paper" && computerMove === "paper") || (playerMove === "scissors" && computerMove === "scissors"))
    {
        winner = "tie";
    }
    else if ((playerMove === "rock" && computerMove === "paper") || (playerMove === "paper" && computerMove === "scissors") || (playerMove === "scissors" && computerMove === "rock"))
    {
        winner = "computer";
    }
    else if ((playerMove === "rock" && computerMove === "scissors") || (playerMove === "paper" && computerMove === "rock") || (playerMove === "scissors" && computerMove === "paper"))
    {
        winner = "player";
    }
    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    return winner;
}

////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === "rock" && computerMove === "rock") || (playerMove === "paper" && computerMove === "paper") || (playerMove === "scissors" && computerMove === "scissors"))
    {
        winner = "tie";
    }
    else if ((playerMove === "rock" && computerMove === "paper") || (playerMove === "paper" && computerMove === "scissors") || (playerMove === "scissors" && computerMove === "rock"))
    {
        winner = "computer";
    }
    else if ((playerMove === "rock" && computerMove === "scissors") || (playerMove === "paper" && computerMove === "rock") || (playerMove === "scissors" && computerMove === "paper"))
    {
        winner = "player";
    }
    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var result;
    while(playerWins < 5 && computerWins < 5)
    //for(var i = 1; i <= 2; i += 1)
    {
        result = getWinner(getPlayerMove(getInput()), getComputerMove(randomPlay()))
        if (result === "computer")
        {
            computerWins += 1;
        }
        else if (result === "player")
        {
            playerWins += 1;
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }
    return [playerWins, computerWins];
}

////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === "rock" && computerMove === "rock") || (playerMove === "paper" && computerMove === "paper") || (playerMove === "scissors" && computerMove === "scissors"))
    {
        winner = "tie";
    }
    else if ((playerMove === "rock" && computerMove === "paper") || (playerMove === "paper" && computerMove === "scissors") || (playerMove === "scissors" && computerMove === "rock"))
    {
        winner = "computer";
    }
    else if ((playerMove === "rock" && computerMove === "scissors") || (playerMove === "paper" && computerMove === "rock") || (playerMove === "scissors" && computerMove === "paper"))
    {
        winner = "player";
    }
    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    return winner;
}

function playTo(x) {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var result;
    while(playerWins < x && computerWins < x)
    //for(var i = 1; i <= 2; i += 1)
    {
        result = getWinner(getPlayerMove(getInput()), getComputerMove(randomPlay()))
        if (result === "computer")
        {
            computerWins += 1;
        }
        else if (result === "player")
        {
            playerWins += 1;
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }
    return [playerWins, computerWins];
}<commit_msg>clean up accidentally duplicated code<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === "rock" && computerMove === "rock") || (playerMove === "paper" && computerMove === "paper") || (playerMove === "scissors" && computerMove === "scissors"))
    {
        winner = "tie";
    }
    else if ((playerMove === "rock" && computerMove === "paper") || (playerMove === "paper" && computerMove === "scissors") || (playerMove === "scissors" && computerMove === "rock"))
    {
        winner = "computer";
    }
    else if ((playerMove === "rock" && computerMove === "scissors") || (playerMove === "paper" && computerMove === "rock") || (playerMove === "scissors" && computerMove === "paper"))
    {
        winner = "player";
    }
    console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var result;
    while(playerWins < 5 && computerWins < 5)
    //for(var i = 1; i <= 2; i += 1)
    {
        result = getWinner(getPlayerMove(getInput()), getComputerMove(randomPlay()))
        if (result === "computer")
        {
            computerWins += 1;
        }
        else if (result === "player")
        {
            playerWins += 1;
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }
    return [playerWins, computerWins];
}

function playTo(x) {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    var result;
    while(playerWins < x && computerWins < x)
    //for(var i = 1; i <= 2; i += 1)
    {
        result = getWinner(getPlayerMove(getInput()), getComputerMove(randomPlay()))
        if (result === "computer")
        {
            computerWins += 1;
        }
        else if (result === "player")
        {
            playerWins += 1;
        }
        console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');
    }
    return [playerWins, computerWins];
}<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;

    if ((playerMove === 'paper' && computerMove === 'rock')
        || (playerMove === 'rock' && computerMove === 'scissors')
        || (playerMove === 'scissors' && computerMove === 'paper')) {
    winner = 'player';
    }
    else if ((playerMove === 'rock' && computerMove === 'paper')
        || (playerMove === 'paper' && computerMove === 'scissors')
        || (playerMove === 'scissors' && computerMove === 'rock')) {
    winner = 'computer';
    }
    else if (playerMove === computerMove) {
       winner = 'tie';
    }
    return winner;
 }

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

playToFive();<commit_msg>WORKING ON END<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;

    if ((playerMove === 'paper' && computerMove === 'rock')
        || (playerMove === 'rock' && computerMove === 'scissors')
        || (playerMove === 'scissors' && computerMove === 'paper')) {
    winner = 'player';
    }
    else if ((playerMove === 'rock' && computerMove === 'paper')
        || (playerMove === 'paper' && computerMove === 'scissors')
        || (playerMove === 'scissors' && computerMove === 'rock')) {
    winner = 'computer';
    }
    else if (playerMove === computerMove) {
       winner = 'tie';
    }
    return winner;
 }

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    var winner = getWinner(playerMove,computerMove);
    while (playerWins < 5 && computerWins < 5) {
        if (winner === "Player") {
            playerWins += 1;
        }
        else if (winner === "Computer") {
            computerWin +=1;
        }
        getInput()
        randomPlay();
    return [playerWins, computerWins];
}

playToFive();<|endoftext|>