From de76c9c208aea4510e25be96dc8d98f33bb23efe Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Mon, 31 Jul 2017 22:03:09 -0700 Subject: [PATCH 1/8] adding testing exercises --- testing_exercise/testing.js | 27 ++++++++++++++++++ testing_exercise/testingSpec.js | 50 ++++++++++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/testing_exercise/testing.js b/testing_exercise/testing.js index e69de29b..685770d5 100644 --- a/testing_exercise/testing.js +++ b/testing_exercise/testing.js @@ -0,0 +1,27 @@ +function replaceWith(str, l, lreplace) { + return str.split(l).join(lreplace); +} + +//Write a function called expand which takes an array and a number and returns a copy of the array with as many numbers as specified +//expand([1,2,3],3) //[1,2,3,1,2,3,1,2,3] +function expand(arr, num) { + var newArr = []; + for(var i = 1; i <= num; i++) { + newArr = newArr.concat(arr); + } + return newArr; +} +//Write a function called mergeArrays which takes in two arrays and returns one array with the values sorted +function mergeArrays(arr1, arr2){ + var newArr = arr1.concat(arr2).sort(); + return newArr; +} + +//Write a function called mergeObjects which takes in two objects and return an object with the keys and values combined. If the second parameter has the same key - it should override first one. There is a built in function called Object.assign - research it, but do not use it, try to do this on your own! + +function mergeObjects(obj1, obj2) { + for (var key in obj2){ + obj1[key] = obj2[key]; + } + return obj1; +} \ No newline at end of file diff --git a/testing_exercise/testingSpec.js b/testing_exercise/testingSpec.js index aef56b1d..27544b6d 100644 --- a/testing_exercise/testingSpec.js +++ b/testing_exercise/testingSpec.js @@ -1,3 +1,51 @@ var expect = chai.expect; -// WRITE YOUR TESTS HERE! \ No newline at end of file +describe("replaceWith", function () { + it("replaces a capital with a capital", function(){ + expect(replaceWith("Foobar", "F", "B")).to.equal("Boobar"); + }); + it("does not capitalize when it isn't passed a capital", function(){ + expect(replaceWith("Hello", "e", "i")).to.equal("Hillo"); + }); + it("does not get rid of capitalization", function(){ + expect(replaceWith("TeST", "S", "M")).to.equal("TeMT"); + }); +}); + +//Write a function called expand which takes an array and a number and returns a copy of the array with as many numbers as specified +describe("expand", function () { + it("it triples the array when given three", function(){ + expect(expand([1,2,3],3)).to.deep.equal([1,2,3,1,2,3,1,2,3]); + }); + it("does not change the array when passed one", function(){ + expect(expand(["foo", "test"],1)).to.deep.equal(["foo","test"]); + }); +}); + +//Write a function called mergeArrays which takes in two arrays and returns one array with the values sorted +describe("mergeArrays", function () { + it("returns an array and sorts alphabetically", function(){ + expect(mergeArrays(["foo", "test"],["merge", "me"])).to.deep.equal(["foo", "me", "merge", "test"]); + }); + it("returns merged array in numerical order", function(){ + expect(mergeArrays([2, 1], [3, 4])).to.deep.equal([1, 2, 3, 4]); + }); +}); +//Write a function called mergeObjects which takes in two objects and return an object with the keys and values combined. If the second parameter has the same key - it should override first one. There is a built in function called Object.assign - research it, but do not use it, try to do this on your own! +describe("mergeObjects", function () { + it("returns an object with combined keys and values", function(){ + var obj1 = { + name: "Foo", + num: 33 + }; + var obj2 = { + test: "thing", + num: 55 + }; + expect(mergeObjects(obj1, obj2)).to.deep.equal({ + name: "Foo", + test: "thing", + num: 55 + }); + }); +}); \ No newline at end of file From 56896472d751d5951abb38f912669ad685876f08 Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Tue, 1 Aug 2017 21:59:55 -0700 Subject: [PATCH 2/8] partially finished recursion --- recursion_exercise/recursion.js | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/recursion_exercise/recursion.js b/recursion_exercise/recursion.js index e69de29b..11d3885c 100644 --- a/recursion_exercise/recursion.js +++ b/recursion_exercise/recursion.js @@ -0,0 +1,47 @@ +//Write a function called productOfArray which takes in an array of numbers and returns the product of them all +//productOfArray([1,2,3]) // 6 +//productOfArray([1,2,3,10]) // 60 +function productOfArray(arr) { + //returns all elements multiplied + if (arr.length === 1) { + return arr[0]; + } + return arr[0] * productOfArray(arr.slice(1)); +} +//Write a function called collectStrings which accepts an object and returns an array of all the values in the object that have a typeof string + + + +function collectStrings(obj) { + var stringKeys = []; + for (var key in obj) { + if (typeof obj[key] === "object") { + stringKeys = stringKeys.concat(collectStrings(obj[key])); + } else { + stringKeys.push(obj[key]); + } + } + return stringKeys; +} + +//Write a function called contains that searches for a value in a nested object. It returns true if the object contains that value. +var nestedObject = { + data: { + info: { + stuff: { + thing: { + moreStuff: { + magicNumber: 44 + } + } + } + } + } +} +//contains(nestedObject, 44) // true +//contains(nestedObject, "foo") // false +function contains(obj, value) { + return collectStrings(obj).indexOf(value) !== -1; +} + + From ff1b38261befe6fb0da7c20894acf68714a881aa Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Wed, 2 Aug 2017 14:22:27 -0700 Subject: [PATCH 3/8] fixed collectStrings solution to actually collect strings --- recursion_exercise/recursion.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/recursion_exercise/recursion.js b/recursion_exercise/recursion.js index 11d3885c..3cc70990 100644 --- a/recursion_exercise/recursion.js +++ b/recursion_exercise/recursion.js @@ -3,10 +3,12 @@ //productOfArray([1,2,3,10]) // 60 function productOfArray(arr) { //returns all elements multiplied - if (arr.length === 1) { - return arr[0]; + if (arr.length === 0) { + return 1; } return arr[0] * productOfArray(arr.slice(1)); + //destructive + //return arr.shift() * productOfArray(arr[]) } //Write a function called collectStrings which accepts an object and returns an array of all the values in the object that have a typeof string @@ -15,10 +17,11 @@ function productOfArray(arr) { function collectStrings(obj) { var stringKeys = []; for (var key in obj) { + if(typeof obj[key] === 'string'){ + stringKeys.push(obj[key]); + } if (typeof obj[key] === "object") { stringKeys = stringKeys.concat(collectStrings(obj[key])); - } else { - stringKeys.push(obj[key]); } } return stringKeys; @@ -45,3 +48,5 @@ function contains(obj, value) { } + + From a686bba777e622ff734e5697aa5113e78c9761f4 Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Wed, 2 Aug 2017 22:58:35 -0700 Subject: [PATCH 4/8] patially completed lodash exercises --- lodash_exercise/lodash.js | 124 +++++++++++++++++++++++++++----------- 1 file changed, 90 insertions(+), 34 deletions(-) diff --git a/lodash_exercise/lodash.js b/lodash_exercise/lodash.js index 483d734a..3ba1ae64 100644 --- a/lodash_exercise/lodash.js +++ b/lodash_exercise/lodash.js @@ -1,37 +1,93 @@ -function drop(){ - -} - -function fromPairs(){ - -} - -function head(){ - -} - -function take(){ - -} - -function takeRight(){ - -} - -function union(){ - -} - -function zipObject(){ - -} - -function includes(){ - -} - -function sample(){ - +//Creates a slice of array with n elements dropped from the beginning. + //_.drop([1, 2, 3]); +// => [2, 3] +function drop(array, n){ + if (n === undefined){ + return array.slice(1); + } + return array.slice(n); + +} + + +function fromPairs(array) { + if(array.length === 0) { + return undefined; + } else { + var obj = {}; + for(var i = 0; i < array.length; i++) { + obj[array[i][0]] = array[i][1]; + } + return obj; + } +} + +function head(array){ + return array.shift(); +} + +function take(array, num){ + var newArr = []; + if (num === undefined) { + return [array[0]]; + } else if (num >= array.length) { + newArr = array; + } else { + newArr = array.slice(0, num); + } + return newArr; +} + + +function takeRight(array, num){ + if (num === 0) { + return []; + } else if (num >= array.length) { + return array; + } else if (num === undefined) { + return [array[(array.length - 1)]]; + } else + return array.slice(-num); +} + +function union(arr1, arr2) { + var newArr = arr1.slice(); + for (var i = 0; i < arr2.length; i++) { + if (newArr.indexOf(arr2[i]) === -1){ + newArr.push(arr2[i]); + } + } + return newArr; +} + +function zipObject(arr1, arr2) { + var obj = {}; + for(var i = 0; i < arr1.length; i++) { + obj[arr1[i]] = arr2[i]; + } + return obj; +} + + +function includes(input, value, index) { + //check type of input + if (Array.isArray(input)) { + if(index !== undefined){ + var slicedArr= input.slice(index); + return (slicedArr[0] === value); + } else { + return (input.indexOf(value) != -1); + } + } else if (typeof input === "string") { + return (input.indexOf(value) != -1); + } else { + return (Object.values(input).indexOf(value) > -1); + } + +} + +function sample(arr){ + return arr[Math.floor(Math.random() * (arr.length))]; } function cloneDeep(){ From 93c4e0b2bff41a10f8f1d2ec112f7541075d5e8a Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Thu, 3 Aug 2017 22:07:23 -0700 Subject: [PATCH 5/8] some fixes, and canvas project - still need to add timer --- canvas_exercise/shapes_game/index.js | 110 +++++++++++++++++++++++++- lodash_exercise/lodash.js | 114 +++++++++++++-------------- testing_exercise/testingSpec.js | 6 +- 3 files changed, 166 insertions(+), 64 deletions(-) diff --git a/canvas_exercise/shapes_game/index.js b/canvas_exercise/shapes_game/index.js index 0de5f18a..170acbbe 100644 --- a/canvas_exercise/shapes_game/index.js +++ b/canvas_exercise/shapes_game/index.js @@ -1,15 +1,88 @@ window.addEventListener("load", function() { + //flow of what needs to happen: + //drawGameStartText - game starts text is drawn, text is cleared + //game starts when space bar is hit + //drawRandomShape - draws random shape + // shape attached to key + // check if key hit matches expectedkeymap + // also need to reassaign expectedkey from undefined to it's shape + var squareSize = 150; + var shapesArr = [ + "squareWhite", + "triWhite", + "squareRed", + "triRed", + ]; + var currentShape = undefined; - function clear(ctx, width, heigt) { + function clear(ctx, width, height) { + //clears the screen + ctx.clearRect(0, 0, width, height); } function drawRandomShape(ctx, width, height) { + //draws square or triangle + //needs to be in a different location everytime called + clear(ctx, width, height); + var shapeNumber = Math.floor(Math.random() * 4); + var x = Math.floor(Math.random() * (width - squareSize)); + var y = Math.floor(Math.random() * (height - squareSize)); + draw(ctx, shapesArr[shapeNumber], x, y); + updateScore(); + } + + function updateScore(){ + var span = document.getElementById("score-val"); + span.innerText = points; + } + + function draw(ctx, shape, x, y) { + currentShape = shape; + switch (shape) { + case "squareWhite": + ctx.fillStyle = "white"; + ctx.fillRect(x, y, squareSize, squareSize); + break; + case "triWhite": + ctx.fillStyle = "white"; + ctx.beginPath(); + ctx.moveTo(x,y); + ctx.lineTo(x + squareSize, y + squareSize); + ctx.lineTo(x, y + squareSize); + ctx.fill(); + ctx.closePath(); + break; + case "squareRed": + ctx.fillStyle = "red"; + ctx.fillRect(x, y, squareSize, squareSize); + break; + case "triRed": + ctx.fillStyle = "red"; + ctx.beginPath(); + ctx.moveTo(x,y); + ctx.lineTo(x + squareSize, y + squareSize); + ctx.lineTo(x, y + squareSize); + ctx.fill(); + ctx.closePath(); + break; + } } function drawGameStartText(ctx, width, height, score) { + gameOn = true; + ctx.font = '45px serif'; + ctx.fillStyle = "white"; + ctx.fillText('To start game, hit the space bar', 100, 300); } function restartGame(ctx, width, height) { + //gets called after finish first game + //timer reset + //score reset + //game cleared + //addEventListener for hitting the spacebar + //then call generate random shape + } var canvas = document.getElementById("shapes-game"), @@ -24,13 +97,42 @@ window.addEventListener("load", function() { timerSpan = document.getElementById("time-remaining"), scoreSpan = document.getElementById("score-val"), seconds = 3, + points = 0, intervalId; canvas.width = width; canvas.height = height; - document.addEventListener("keyup", function() { - + document.addEventListener("keyup", function(event) { + if (event.keyCode === 32) { // spacebar + drawRandomShape(ctx, width, height); + + } else if (event.keyCode === 37) { // left + if (currentShape === "triRed") { + points++; + } else { + points--; + } + } else if (event.keyCode === 38) { // up + if (currentShape === "triWhite") { + points++ + } else { + points--; + } + } else if (event.keyCode === 39) { // right + if (currentShape === "squareWhite") { + points++; + } else { + points--; + } + } else if (event.keyCode === 40) { // down + if (currentShape === "squareRed") { + points++; + } else { + points--; + } + } + drawRandomShape(ctx, width, height); }); + drawGameStartText(ctx, width, height, 0); }); - diff --git a/lodash_exercise/lodash.js b/lodash_exercise/lodash.js index 3ba1ae64..99e8ff38 100644 --- a/lodash_exercise/lodash.js +++ b/lodash_exercise/lodash.js @@ -1,59 +1,59 @@ //Creates a slice of array with n elements dropped from the beginning. - //_.drop([1, 2, 3]); +//_.drop([1, 2, 3]); // => [2, 3] -function drop(array, n){ - if (n === undefined){ - return array.slice(1); - } - return array.slice(n); +function drop(array, n) { + if (n === undefined) { + return array.slice(1); + } + return array.slice(n); } function fromPairs(array) { - if(array.length === 0) { + if (array.length === 0) { return undefined; } else { var obj = {}; - for(var i = 0; i < array.length; i++) { + for (var i = 0; i < array.length; i++) { obj[array[i][0]] = array[i][1]; } return obj; } -} +} -function head(array){ - return array.shift(); +function head(array) { + return array.shift(); } -function take(array, num){ - var newArr = []; - if (num === undefined) { - return [array[0]]; - } else if (num >= array.length) { - newArr = array; - } else { - newArr = array.slice(0, num); - } - return newArr; +function take(array, num) { + var newArr = []; + if (num === undefined) { + return [array[0]]; + } else if (num >= array.length) { + newArr = array; + } else { + newArr = array.slice(0, num); + } + return newArr; } -function takeRight(array, num){ - if (num === 0) { - return []; - } else if (num >= array.length) { - return array; - } else if (num === undefined) { - return [array[(array.length - 1)]]; - } else +function takeRight(array, num) { + if (num === 0) { + return []; + } else if (num >= array.length) { + return array; + } else if (num === undefined) { + return [array[(array.length - 1)]]; + } else return array.slice(-num); } function union(arr1, arr2) { var newArr = arr1.slice(); for (var i = 0; i < arr2.length; i++) { - if (newArr.indexOf(arr2[i]) === -1){ + if (newArr.indexOf(arr2[i]) === -1) { newArr.push(arr2[i]); } } @@ -62,94 +62,94 @@ function union(arr1, arr2) { function zipObject(arr1, arr2) { var obj = {}; - for(var i = 0; i < arr1.length; i++) { + for (var i = 0; i < arr1.length; i++) { obj[arr1[i]] = arr2[i]; } return obj; } - + function includes(input, value, index) { - //check type of input + //check type of input if (Array.isArray(input)) { - if(index !== undefined){ - var slicedArr= input.slice(index); - return (slicedArr[0] === value); + if (index !== undefined) { + var slicedArr = input.slice(index); + return (slicedArr[0] !== value); } else { - return (input.indexOf(value) != -1); + return (input.indexOf(value) != -1); } } else if (typeof input === "string") { - return (input.indexOf(value) != -1); + return input.indexOf(value) !== -1; } else { - return (Object.values(input).indexOf(value) > -1); + return Object.values(input).indexOf(value) > -1; } } -function sample(arr){ - return arr[Math.floor(Math.random() * (arr.length))]; +function sample(arr) { + return arr[Math.floor(Math.random() * arr.length)]; } -function cloneDeep(){ +function cloneDeep() { } -function sumBy(){ +function sumBy() { } -function inRange(){ +function inRange() { } -function has(){ +function has() { } -function omit(){ +function omit() { } -function pick(){ +function pick() { } -function pickBy(){ +function pickBy() { } -function omitBy(){ +function omitBy() { } -function padEnd(){ +function padEnd() { } -function repeat(){ +function repeat() { } -function upperFirst(str){ +function upperFirst(str) { } -function flatten(){ +function flatten() { } -function zip(){ +function zip() { } -function unzip(){ +function unzip() { } -function flip(){ +function flip() { } -function flattenDeep(){ +function flattenDeep() { } diff --git a/testing_exercise/testingSpec.js b/testing_exercise/testingSpec.js index 27544b6d..13b0088c 100644 --- a/testing_exercise/testingSpec.js +++ b/testing_exercise/testingSpec.js @@ -1,13 +1,13 @@ var expect = chai.expect; describe("replaceWith", function () { - it("replaces a capital with a capital", function(){ + it("replaces a capital with a capital", function(){ expect(replaceWith("Foobar", "F", "B")).to.equal("Boobar"); }); - it("does not capitalize when it isn't passed a capital", function(){ + it("does not capitalize when it isn't passed a capital", function(){ expect(replaceWith("Hello", "e", "i")).to.equal("Hillo"); }); - it("does not get rid of capitalization", function(){ + it("does not get rid of capitalization", function(){ expect(replaceWith("TeST", "S", "M")).to.equal("TeMT"); }); }); From f0fe64edc2a561f1a26b62d2ac71067dfb293d5c Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Sun, 6 Aug 2017 22:14:35 -0700 Subject: [PATCH 6/8] some updates to lodash and es2015 exercises --- es2015_exercise/readme.md | 108 +++++++++++++++++++++++++++++++++++--- lodash_exercise/lodash.js | 30 ++++++++--- 2 files changed, 125 insertions(+), 13 deletions(-) diff --git a/es2015_exercise/readme.md b/es2015_exercise/readme.md index 9e482efa..314605c9 100644 --- a/es2015_exercise/readme.md +++ b/es2015_exercise/readme.md @@ -1,4 +1,4 @@ -## ES2015 Exercise +# ES2015 Exercise Convert the following es5 code blocks into es2015 code: @@ -11,16 +11,27 @@ var person = { }.bind(this),1000) } } +var person2 = { + fullName: "Harry Potter", + sayHi: function(){ + setTimeout(() => { + console.log(`Your name is ${this.fullName}`) + },1000) + } +} ``` ```javascript var name = "Josie" console.log("When " + name + " comes home, so good") +console.log(`When ${name} comes home, so good`); +//Steely Dan? ``` ```javascript var DO_NOT_CHANGE = 42; DO_NOT_CHANGE = 50; // stop me from doing this! +const doNotChange = 42; ``` ```javascript @@ -28,6 +39,8 @@ var arr = [1,2] var temp = arr[0] arr[0] = arr[1] arr[1] = temp +var [a, b] = [1, 2]; +[a, b] = [b, a]; ``` ```javascript @@ -36,6 +49,10 @@ function double(arr){ return val*2 }); } + +function double1(arr){ + return arr.map(value => value * 2); +} ``` ```javascript @@ -43,11 +60,13 @@ var obj = { numbers: { a: 1, b: 2 - } + } } var a = obj.numbers.a; var b = obj.numbers.b; + +var {a, b, c} = obj.numbers; ``` ```javascript @@ -62,14 +81,91 @@ function add(a,b){ } return a+b } +function add(a = 10, b = 10) { + return a + b; +} +//or better +var add = (a = 10, b = 10) => a + b; ``` Research the following functions - what do they do? -`Array.from` - +`Array.from` - It allows you to create arrays from array like objects, things with a length property and indexed elements - has the optional parameter .map() to perform a function on each element in the new array. which syntax would be like: Array.from(obj, mapFn, thisArg) Fancy using arrow functions: Array.from([1, 2, 3], x => x + x) //[2, 4, 6] + +`Object.assign` - _not a deep clone_ but basically copies the enumerable and own properties from a source object to a target object. Uses get on source and set on target - so it assigns properties vs just copying or defining new properties example of cloning an object - BUT not a deep clone + +```javascript +var obj = {a: 1}; +var copy = Object.assign({}, obj) +console.log(copy); //{a: 1} +``` + +using to merge objects: + +```javascript +var o1 = {a : 1}; +var o2 = {b : 2}; +var o3 = {c : 3}; +var obj = Object.assign(o1, o2, o3); +console.log(obj); //{a: 1, b: 2, c: 3} +``` + +watch out when you merge objects with the same properties though ==> the properties are overwritten by other objects that have the properties later in the parameters order + +```javascript +var o1 = {a : 1, b: 1, c: 1}; +var o2 = {b : 2, c: 2}; +var o3 = {c : 3}; +var obj =Object.assign({}, o1, o2, o3); +console.log(obj); //{a: 1, b: 2, c: 3} +``` + +Also: + +```javascript +var v1 = 'abc'; +var v2 = true; +var v3 = 10; +var v4 = Symbol('foo'); + +var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); +// Primitives will be wrapped, null and undefined will be ignored. +// Note, only string wrappers can have own enumerable properties. +console.log(obj); // { "0": "a", "1": "b", "2": "c" } +``` -`Object.assign` - +`Array.includes` - determines if an array includes a certain element, returns a boolean. -`Array.includes` - +syntax: -`String.startsWith` - +```javascript +arr.includes(searchElement); +arr.includes(searchElement, fromIndex); +``` + +Parameters: the element to search for and the optional fromIndex: the position in this array at which to begin searching for the searched element, a negative value searches from the index of array.length + fromIndex. defaults to zero + +```javascript +var a = [1, 2, 3]; +a.includes(2); //true +a.includes(4); //false +``` + +`String.startsWith` - determines whether a string begins with the characters of a specified string, returning boolean + +syntax: + +```javascript +stringWhatever.startsWith("thing I', searching for", position); +``` + +parameters: searchString: characters to be searched for at the start of this string position: (optional) the position in this string at which to begin searching for searchString, defaults to zero _Also case sensitive_ + +```javascript +//startswith +var str = 'To be, or not to be, that is the question.'; + +console.log(str.startsWith('To be')); // true +console.log(str.startsWith('not to be')); // false +console.log(str.startsWith('not to be', 10)); // true +``` diff --git a/lodash_exercise/lodash.js b/lodash_exercise/lodash.js index 99e8ff38..81730d4b 100644 --- a/lodash_exercise/lodash.js +++ b/lodash_exercise/lodash.js @@ -73,10 +73,10 @@ function includes(input, value, index) { //check type of input if (Array.isArray(input)) { if (index !== undefined) { - var slicedArr = input.slice(index); - return (slicedArr[0] !== value); + var slicedArr = input.slice(index + 1); + return (slicedArr[index] === value); } else { - return (input.indexOf(value) != -1); + return (input.indexOf(value) > -1); } } else if (typeof input === "string") { return input.indexOf(value) !== -1; @@ -90,12 +90,28 @@ function sample(arr) { return arr[Math.floor(Math.random() * arr.length)]; } -function cloneDeep() { - +function cloneDeep(input) { + //recursively clones value + if (Array.isArray(input)) { + for (let i = 0; i < input.length; i++) { + var newArr = []; + newArr = newArr.concat(cloneDeep(input[i])); + } + return newArr; + } + return Object.assign({}, input); } -function sumBy() { - +function sumBy(arr, funOrKey) { + var sum = 0; + for (var i = 0; i < arr.length; i++) { + if (typeof funOrKey === "function") { + sum += funOrKey(arr[i]); + } else { + sum += arr[i][funOrKey]; + } + } + return sum; } function inRange() { From 14ffca63af4f5d2aed1d0f747da9ec70f82b6eb8 Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Wed, 9 Aug 2017 23:15:30 -0700 Subject: [PATCH 7/8] call apply bind exercises --- call_apply_bind_exercise/callApplyBind.js | 46 +++++++++++++++++++++++ call_apply_bind_exercise/readme.md | 32 ++++++++++------ 2 files changed, 66 insertions(+), 12 deletions(-) diff --git a/call_apply_bind_exercise/callApplyBind.js b/call_apply_bind_exercise/callApplyBind.js index e69de29b..78d66d0d 100644 --- a/call_apply_bind_exercise/callApplyBind.js +++ b/call_apply_bind_exercise/callApplyBind.js @@ -0,0 +1,46 @@ +function sumEvenArguments() { + var arr = [].slice.call(arguments); + var sum = 0; + for(var i = 0; i <= arr.length; i++) { + if (arr[i] % 2 === 0) { + sum += arr[i]; + } + } + return sum; +} + +function arrayFrom() { + var arr = [].slice.call(arguments); + return arr; +} + +function invokeMax(fn, max) { + var counter = 0; + return function() { + var innerArgs = [].slice.call(arguments); + if (counter >= max) { + return "Maxed Out!"; + } else { + counter++; + return fn.apply(this, arguments); + } + } +} +///yeah still need clarification on how this works ^ + +function guessingGame(amount) { + var answer = Math.floor(Math.random() * 10); + var guesses = 0; + return function(guess) { + guesses++; + if (guesses > amount) { + return "You are all done playing!"; + } else if (answer < guess) { + return "You're too high!"; + } else if (answer > guess) { + return "You're too low!"; + } else if (answer === guess) { + return "You got it!"; + } + } +} diff --git a/call_apply_bind_exercise/readme.md b/call_apply_bind_exercise/readme.md index cbc3cd03..35222db1 100644 --- a/call_apply_bind_exercise/readme.md +++ b/call_apply_bind_exercise/readme.md @@ -11,15 +11,23 @@ var obj = { } } } + +function sayHi() { + return `This person's name is ${this.fullName}`; +} +var person = { + fullName : "Harry Potter" +} +sayHi.call(person); ``` - List two examples of "array-like-objects" that we have seen. - - - - + - arguments + - the result of getElementsByClassName ### Functions to write: -Make the tests pass for the following functions: +Make the tests pass for the following functions: - Write a function called `sumEvenArguments` which takes all of the arguments passed to a function and returns the sum of the even ones. @@ -29,7 +37,7 @@ sumEvenArguments(1,2,6) // 8 sumEvenArguments(1,2) // 2 ``` -- Write a function called `arrayFrom` which converts an array-like-object into an array. +- Write a function called `arrayFrom` which converts an array-like-object into an array. ```javascript function sample(){ @@ -55,23 +63,23 @@ addOnlyThreeTimes(1,2) // 3 addOnlyThreeTimes(1,2) // "Maxed Out!" ``` -Write a function called `guessingGame` which takes in one parameter `amount`. The function should return another function that takes in a parameter called `guess`. In the outer function, you should create a variable called `answer` which is the result of a random number between 0 and 10 as well as a variable called `guesses` which should be set to 0. +Write a function called `guessingGame` which takes in one parameter `amount`. The function should return another function that takes in a parameter called `guess`. In the outer function, you should create a variable called `answer` which is the result of a random number between 0 and 10 as well as a variable called `guesses` which should be set to 0. -In the inner function, if the guess passed in is the same as the random number (defined in the outer function) - you should return the string "You got it!". If the guess is too high return "You're too high!" and if it is too low, return "You're too low!". You should stop the user from guessing if the amount of guesses they have made is greater than the initial `amount` passed to the outer function. +In the inner function, if the guess passed in is the same as the random number (defined in the outer function) - you should return the string "You got it!". If the guess is too high return "You're too high!" and if it is too low, return "You're too low!". You should stop the user from guessing if the amount of guesses they have made is greater than the initial `amount` passed to the outer function. You will have to make use of closure to solve this problem. ```javascript var game = guessingGame(5) -game(1) // "You're too low!" +game(1) // "You're too low!" game(8) // "You're too high!" game(5) // "You're too low!" -game(7) // "You got it!" -game(1) // "You are all done playing!" +game(7) // "You got it!" +game(1) // "You are all done playing!" var game2 = guessingGame(3) -game2(5) // "You're too low!" +game2(5) // "You're too low!" game2(3) // "You're too low!" -game2(1) // "No more guesses the answer was 0" -game2(1) // "You are all done playing!" +game2(1) // "No more guesses the answer was 0" +game2(1) // "You are all done playing!" ``` From 0d841c92db11a665a7fa21114c754bde3639aaf6 Mon Sep 17 00:00:00 2001 From: Sarah Farnsworth-kumli Date: Thu, 10 Aug 2017 21:57:57 -0700 Subject: [PATCH 8/8] prototype exercises --- intermediate_oop/tic_tac_toe/js/main.js | 26 +++++++++++++ prototypes_exercise/prototypes.js | 49 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/intermediate_oop/tic_tac_toe/js/main.js b/intermediate_oop/tic_tac_toe/js/main.js index 379d891d..77da55c9 100644 --- a/intermediate_oop/tic_tac_toe/js/main.js +++ b/intermediate_oop/tic_tac_toe/js/main.js @@ -1,2 +1,28 @@ +var X = "X"; +var O = "O"; +var E = "_"; + document.addEventListener("DOMContentLoaded", function() { + function Game() { + this.nextPlayer = X; + this.board = new Board(); + + } + + function Board() { + this.grid = [ + [E, E, E], + [E, E, E], + [E, E, E], + ]; + + } }); +//what classes do I want? +//Game - win? occupied?, Board- display, makeMove(0,2,"x") +//Cells- current state, has an x, o or unoccupied +//player- could be an x or o +//ok to do vanilla javascript as long as you put it into classes +//var game = new game constructor +//call function on game that sets up the board +//some cb when the boad gets clicked diff --git a/prototypes_exercise/prototypes.js b/prototypes_exercise/prototypes.js index e69de29b..fbee57e3 100644 --- a/prototypes_exercise/prototypes.js +++ b/prototypes_exercise/prototypes.js @@ -0,0 +1,49 @@ +function Person (firstName, lastName, favoriteColor, favoriteNumber, favoriteFoods) { + this.firstName = firstName, + this.lastName = lastName, + this.favoriteColor = favoriteColor, + this.favoriteNumber = favoriteNumber, + this.favoriteFoods = []; + this.family = []; +}; + +Person.prototype.fullName = function (){ + return `${this.firstName} ${this.lastName}`; +}; +Person.prototype.toString = function () { + return `${this.fullName()}, Favorite Color: ${this.favoriteColor}, Favorite Number: ${this.favoriteNumber}`; +} +Person.prototype.addToFamily = function(person) { + if (person instanceof Person && !this.family.includes(person)) { + this.family.push(person); + return this.family; + } +}; + +var sarah = new Person("Sarah", "Farnsworth", "blue"); + +Array.prototype.map = function (cb) { + var newArr =[]; + for (let i =0; i < this.length; i++) { + newArr.push(cb(this[i], i, this)); + } + return newArr; +}; + +Function.prototype.bind = function (thisArg, ...outerArgs){ + var _this = this; + return function (...innerArgs) { + return _this.apply(thisArg, outerArgs.concat(innerArgs)); + } +}; + + + +String.prototype.reverse = function () { + var result = []; + var str = this.split(""); + for (var i = str.length - 1; i > 0; i++) { + result.push(str[i]); + } + return result.join(''); +}