diff --git a/call_apply_bind_exercise/callApplyBind.js b/call_apply_bind_exercise/callApplyBind.js index e69de29b..7aecb951 100644 --- a/call_apply_bind_exercise/callApplyBind.js +++ b/call_apply_bind_exercise/callApplyBind.js @@ -0,0 +1,136 @@ +// Fix the following code: + +var obj = { + fullName: "Harry Potter", + person: { + sayHi: function(){ + return "This person's name is " + this.fullName + } + } +} +obj.person.sayHi.call(obj) + + + +var obj = { + fullName: "Harry Potter", + sayHi: function(){ + return "This person's name is " + this.fullName + } +} + + + + + + +// Write a function called sumEvenArguments which takes all of the arguments passed to a function and returns the sum of the even ones. +// sumEvenArguments(1,2,3,4) // 6 +// sumEvenArguments(1,2,6) // 8 +// sumEvenArguments(1,2) // 2 + +//I feel like there should be an easier way to do this with less code .... +function sumEvenArguments() { + var arr = [].slice.call(arguments) + var evens = [] + arr.forEach(function(element) { + if (element % 2===0) { + evens.push(element) + } + }) + + var sum = 0 + evens.forEach(function(element) { + sum = sum + element + }) + return sum +} + + +// Write a function called arrayFrom which converts an array-like-object into an array. +// function sample(){ +// var arr = arrayFrom(arguments) +// if(!arr.reduce) throw "This is not an array!" +// return arr.reduce(function(acc,next){ +// return acc+next; +// },0) +// } + +function arrayFrom() { + var arr = [].slice.call(arguments) + return arr +} + + +// Write a function called invokeMax which accepts a function and a maximum amount. invokeMax should return a function that when called increments a counter. If the counter is greater than the maximum amount, the inner function should return "Maxed Out" + +// function add(a,b){ +// return a+b +// } + +// var addOnlyThreeTimes = invokeMax(add,3); +// addOnlyThreeTimes(1,2) // 3 +// addOnlyThreeTimes(2,2) // 4 +// addOnlyThreeTimes(1,2) // 3 +// addOnlyThreeTimes(1,2) // "Maxed Out!" + +function invokeMax(fn, max) { + // var outerArgs = [].slice.call(arguments) + var counter = 0 + + return function() { + if (counter === max) { + return "Maxed Out!" + } else { + counter++ + return fn.apply(this,arguments) //ES 5 + // return fn(...arguments) //ES2015 + } + } +} + + + +// 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. + +// You will have to make use of closure to solve this problem. + +// var game = guessingGame(5) +// 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!" + +// var game2 = guessingGame(3) +// 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!" + + +function guessingGame(amount) { + var answer = (Math.floor(Math.random() *11)) + var guesses = 0 + return function() { + var guess = [].slice.call(arguments); + // var guess = args[0] + guesses++ + if (guesses > amount) { + return "No more guesses, the answer was " + answer + } else if (guess > answer) { + return "You're too high!" + } else if (guess < answer) { + return "You're too low!" + } else { + return "You got it!" + } + + } + +} + + + diff --git a/canvas_exercise/shapes_game/index.js b/canvas_exercise/shapes_game/index.js index 0de5f18a..cdfce004 100644 --- a/canvas_exercise/shapes_game/index.js +++ b/canvas_exercise/shapes_game/index.js @@ -1,15 +1,67 @@ window.addEventListener("load", function() { - function clear(ctx, width, heigt) { + + function clear(ctx, width, height) { + ctx.clearRect(0,0,canvas.width,canvas.height) + } + + function createTriangle(x,y) { + ctx.beginPath(); + ctx.moveTo(x,y); + ctx.lineTo(x+100,y+100); + ctx.lineTo(x,y+100); + ctx.fill(); + ctx.closePath(); } + function drawRandomShape(ctx, width, height) { + var shape = (Math.floor(Math.random() *4))+1 //number from 1-4 + var x = (Math.floor(Math.random() * 700))+1 //wont go out of bounds on x axis + var y = (Math.floor(Math.random() * 650))+1 //wont go out of bounds on y axis + + + if (shape === 1) { + ctx.fillStyle = "white" + createTriangle(x,y) + expectedKey = 38 + + } else if (shape === 2) { + ctx.fillStyle = "red" + ctx.fillRect(x,y,100,100) + expectedKey = 40 + + } else if (shape === 3) { + ctx.fillStyle = "red" + createTriangle(x,y) + expectedKey = 37 + + } else if (shape === 4) { + ctx.fillStyle = "white" + ctx.fillRect(x,y,100,100) + expectedKey = 39 + + } } - function drawGameStartText(ctx, width, height, score) { + function drawGameStartText(ctx, width, height) { + + ctx.fillStyle = "white" + ctx.font = "38px serif" + ctx.fillText("Press the space bar to start a new game",100, 350) +} + + function restartGame(ctx, width, height, score) { + + drawGameStartText(ctx,width,height) + ctx.font = "25px serif" + ctx.fillText("Score: " + score, 350,400) + } - function restartGame(ctx, width, height) { + function clearAndShow(ctx,width,height) { + clear(ctx,width,height) + drawRandomShape(ctx,width,height) } var canvas = document.getElementById("shapes-game"), @@ -23,14 +75,42 @@ window.addEventListener("load", function() { expectedKeysMap = {white0: 38, red1: 40, red0: 37, white1: 39}, timerSpan = document.getElementById("time-remaining"), scoreSpan = document.getElementById("score-val"), - seconds = 3, + seconds = 0, intervalId; canvas.width = width; canvas.height = height; - document.addEventListener("keyup", function() { - + drawGameStartText(ctx, width, height) + + document.addEventListener("keyup", function(e) { + //I feel like this nested if statements can be condensed. + if (timerSpan.innerHTML > 29) { + if (e.keyCode === 32) { + clearAndShow(ctx,width,height) // when space is first pressed, clear the words and show the first shape. + var decreaseTimerId = setInterval(function(){ + timerSpan.innerHTML --; // decrease timer span + seconds ++ // variable to check when 30 seconds has elapsed ... somehow I could not use timerSpan.innerHTML to check?? + if (seconds === 30) { + clearInterval(decreaseTimerId); + clear(ctx, width, height) + //show score on the screen and reset all the variables. + restartGame(ctx,width,height,scoreSpan.innerHTML) + seconds = 0; + timerSpan.innerHTML = 30 + scoreSpan.innerHTML = 0 + } + },1000) + } + //^ everything above checks if the space key is pressed and do some action based on a condition. + } else if (e.keyCode === expectedKey) { + scoreSpan.innerHTML ++ + } else { + scoreSpan.innerHTML -- + } + + clearAndShow(ctx,width,height) }); + }); diff --git a/es2015_exercise/readme.md b/es2015_exercise/readme.md index 9e482efa..defe5e67 100644 --- a/es2015_exercise/readme.md +++ b/es2015_exercise/readme.md @@ -12,17 +12,31 @@ var person = { } } ``` +var person = { + fullName: "Harry Potter", + sayHi(){ + setTimeout(() => console.log("Your name is " + this.fullName).bind(this),1000) + } +} + ```javascript var name = "Josie" console.log("When " + name + " comes home, so good") ``` +var name = "Josie" +console.log(`When ${name} comes home, so good`) + + ```javascript var DO_NOT_CHANGE = 42; DO_NOT_CHANGE = 50; // stop me from doing this! ``` +const DO_NOT_CHANGE = 42; +DO_NOT_CHANGE = 50; // stop me from doing this! + ```javascript var arr = [1,2] var temp = arr[0] @@ -30,6 +44,11 @@ arr[0] = arr[1] arr[1] = temp ``` +var [b,a] = arr +-- or -- +var [a,b] = arr +var arr = [b,a] + ```javascript function double(arr){ return arr.map(function(val){ @@ -38,6 +57,10 @@ function double(arr){ } ``` +var double = (arr) => arr.map(val => val*2); + + + ```javascript var obj = { numbers: { @@ -50,6 +73,10 @@ var a = obj.numbers.a; var b = obj.numbers.b; ``` +var{a,b} = obj.numbers + + + ```javascript function add(a,b){ if(a === 0) a = 0 @@ -64,12 +91,18 @@ function add(a,b){ } ``` +var add = (a=10, b=10) => a+b + + + + + Research the following functions - what do they do? -`Array.from` - +`Array.from` - Creates an array from an array-like object -`Object.assign` - +`Object.assign` - Creates a new object with key-value pairs copied from another array. -`Array.includes` - +`Array.includes` - checks if a value is in the array but does not return the index -`String.startsWith` - +`String.startsWith` - returns true or false based on whether the string begins with the argument passed. diff --git a/jquery_exercise/app.js b/jquery_exercise/app.js new file mode 100644 index 00000000..2a149800 --- /dev/null +++ b/jquery_exercise/app.js @@ -0,0 +1,67 @@ +$(document).ready(function(){ + + var $article = $("#articles") + + //the form is toggling on and off + var $addNew = $('#addNew') + var $formToggle = $('#formToggle') + $addNew.click(function() { + $form.toggle('form-inline-block form-inline') + }) + + var $favToggle = $('#fav') + var $notFavorites = $('.glyphicon-star-empty') + $favToggle.click(function() { + //this does not work yet. + + $notFavorites.parent().toggle('hidden block') + + // for (var i = 0; i < $notFavorites.length; i++) { + // $notFavorites.eq(i).next().addClass('hidden') + // } + //add class of hidden to li + // add something to ol tag that makes it unordered. + + }) + + var $form = $('.form-inline') + var $title = $('#title') + var $url = $('#url') + + $form.on('submit', function(e) { // adds a new list item when the submit button is pressed. + e.preventDefault(); //prevents the form from refreshing the page + + + var $newLi = $('
  • '); + var $newStar = $('', { + class: "glyphicon glyphicon-star-empty" + }); + var $newATag = $('', { + href: $url.val(), + text: " " +$title.val() + }) + + $newLi.append($newStar); + $newLi.append($newATag) + + + + $article.append($newLi) + + $title.val("") + $form.toggle() + }) + + + //toggle the star + $article.on('click', 'span', function(e) { + $(e.target).toggleClass('glyphicon-star glyphicon-star-empty') + }) + + + +}) + + + + diff --git a/jquery_exercise/index.html b/jquery_exercise/index.html new file mode 100644 index 00000000..f2285462 --- /dev/null +++ b/jquery_exercise/index.html @@ -0,0 +1,66 @@ + + + + + Document + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jquery_exercise/style.css b/jquery_exercise/style.css new file mode 100644 index 00000000..3a9fca4f --- /dev/null +++ b/jquery_exercise/style.css @@ -0,0 +1,67 @@ +#name{ + padding-right:40px; + font-size: 25px; + font-weight: bold; + display:inline-block; +} + +.main{ + background-color: gray; + font: 20px; + color:black; + padding-top:5px; + padding-right:10px; + padding-left:10px; + padding-bottom:5px; +} + +#addNew { + font-size: 15px; + font-weight:normal; + color:black; + display:inline-block; +} + +#fav { + font-size: 15px; + font-weight:normal; + color:black; + display:inline-block; +} +/* +p { + font-size:15px; + font-weight:normal; + color:black; +}*/ + +.header{ + background-color:orange; + display:block; + padding:10px; +} + +#articles { + padding-top:5px; +} + + +.form-inline { + display:none; +} + +.form-inline-block { + display:block; +} + +a{ + color:black; +} + +.hidden { + display:none; +} + +.block { + display:block; +} \ No newline at end of file diff --git a/lodash_exercise/lodash.js b/lodash_exercise/lodash.js index 483d734a..44edc9a2 100644 --- a/lodash_exercise/lodash.js +++ b/lodash_exercise/lodash.js @@ -1,88 +1,337 @@ -function drop(){ - +function drop(array, n){ + if (n === 0) { + return array; + } else if (!n) { + return array.slice(1) + } else { + return array.slice(n) + } } -function fromPairs(){ - +function fromPairs(arr){ +var obj = {}; + for (var i = 0; i < arr.length; i++){ + obj[arr[i][0]] = arr[i][1]; + } +return obj; } -function head(){ - +function head(arr){ +if (arr.length === 0) { + return undefined; +}else { + return arr[0] +} } -function take(){ +function take(arr, n){ +if (n === 0) { + return []; +} else if (!n) { + return arr.slice(0,1) +} else { + return arr.slice(0,n) +} } -function takeRight(){ - +function takeRight(arr, n){ + if (n === 0) { + return []; + } else if (!n) { + return arr.slice(arr.length-1) + } else if (n > arr.length) { + return arr.slice(0) + } else { + return arr.slice(n-1) + } } function union(){ + var arr = []; + + for (var x = 0; x < arguments.length; x++) { + for (var i = 0; i < arguments[x].length; i++) { + if (arr.indexOf(arguments[x][i]) === -1) { + arr.push(arguments[x][i]); + } + } + } + return arr; +} +function zipObject(arr1,arr2){ +var obj = {} + for (var i = 0; i < arr1.length; i++) { + if (!(arr2[i])){ + obj[arr1[i]] = undefined; + } else { + obj[arr1[i]] = arr2[i]; + } + } +return obj; } -function zipObject(){ +function includes(collection, value, check){ + + if (typeof collection === "string") { + return (collection.search(value) !== -1) + } else if (Array.isArray(collection)) { + if (!check) { + return (collection.indexOf(value) !== -1) + } else { + return (collection[check] === value) + } + } else if (typeof collection === "object") { + for (var key in collection) { + return (collection[key] === value) + } + } } -function includes(){ +function sample(collection){ +var random = Math.random() + if (Array.isArray(collection)) { + var arrLength = Math.floor(random * collection.length) + return collection[arrLength]; + } else if (typeof collection === "object") { + var keys = [] + for (var key in collection) { + keys.push(key) + } + return collection[keys[Math.floor(random * keys.length)]] + } +} +function cloneDeep(value){ +var arr = []; +var obj = {}; + +function helper(object) { + for (var key in object); + if (typeof object === "object") { + return obj[key] = helper(object[key]) + } else { + return obj[key] = value[key]; + } } -function sample(){ + if (Array.isArray(value)) { + for (var i = 0; i < value.length; i ++) { + if (typeof value[i] === "object") { + holder = helper(value) + arr.push(holder) + } else { + var holder = value[i]; + arr.push(holder); + } + } + return arr; + } else if (typeof value === "object") { + for (var key in value) { + obj[key] = value[key]; + } + return obj; + } } -function cloneDeep(){ - +function sumBy(arr, fn) { +var sum = 0; + for (var i = 0 ; i < arr.length; i++) { + if (typeof fn === "function"){ + sum += fn(arr[i]); + } else { + sum += arr[i][fn] + } + } +return sum; } -function sumBy(){ +function inRange(num, start, end){ +var arr = []; -} -function inRange(){ + if (!end) { + end = start; + start = 0; + for (var i = start; i < end; i++) { + arr.push(i) + } -} + } else if (start > end) { + for (var i = end; i < start; i++) { + arr.push(i); + } + + } else { + for (var i = start; i < end; i++) { + arr.push(i) + } + } -function has(){ + return (arr.indexOf(Math.floor(num)) !== -1) } -function omit(){ -} +function has(object,path){ +var arr = []; + function helper(obj) { + for (var key in obj) { + arr.push(key); + if (typeof obj[key] === "object") { + return helper(obj[key]); + } + } + } -function pick(){ +helper(object); -} +if (Array.isArray(path)) { + for (var i = 0; i < path.length; i ++){ + if (arr.indexOf(path[i]) !== -1) { + return true + } + } +} else if (typeof path === "string") { + if (arr.indexOf(path) !== -1) { + return true + } + } +return false + + + + + + +// //recurse through object, without grabbing all the keys first. +// function has(object,path){ +// function helper(obj) { +// for (var key in obj) { +// if (typeof obj[key] === "object") { +// return helper(obj[key]); +// } +// } +// } -function pickBy(){ +// if (Array.isArray(path)) { +// for (var i = 0; i < path.length; i ++){ +// if (arr.indexOf(path[i]) !== -1) { +// return true +// } +// } +// } else if (typeof path === "string") { +// if (arr.indexOf(path) !== -1) { +// return true +// } +// } +// return false + + +} + +function omit(object, remove){ +var newObj = {}; +for (var key in object) { + if (remove.indexOf(key) === -1) { + newObj[key] = object[key]; + } +} +return newObj; } -function omitBy(){ +function pick(obj, add){ +var newObj = {}; +for (var key in obj) { + if (add.indexOf(key) !== -1) { + newObj[key] = obj[key]; + } +} +return newObj; +} +function pickBy(obj, fn){ +var newObj = {} +for (var key in obj) { + if (fn(obj[key])) { + newObj[key] = obj[key]; + } +} +return newObj; } -function padEnd(){ +function omitBy(obj, fn){ +var newObj = {}; +for (var key in obj) { + if (!fn(obj[key])) { + newObj[key] = obj[key]; + } +} +return newObj; +} +function padEnd(str, length, char){ + if (!char) { + char = " " + } + while (str.length < length) { + str = str + char; + } + if (str.length > length) { + return str.slice(0,length); + } else if (str.length === length) { + return str + } } -function repeat(){ +function repeat(str, n){ + + if (n === 0) { + return "" + } else if (n > 0) { + if (n === 1) { + return str; + } + return str + repeat(str, n-1) + } } + + function upperFirst(str){ +return (str[0].toUpperCase()) + (str.slice(1)) +} +function flatten(arr){ +var newArr = []; + for (var i = 0; i < arr.length; i++) { + if (Array.isArray(arr[i])) { + return newArr.concat(arr[i]) + } else { + newArr.push(arr[i]) + } + } } -function flatten(){ -} +//bonus +//not finished function zip(){ +var zippedArr = [] +var iteration = arguments[0].length + for (var i = 0; i < arguments.length; i++) { + // call recursion here. + } + +function helper(arr) { + // do this while not equal to iteration. +} } @@ -90,10 +339,33 @@ function unzip(){ } -function flip(){ +//not finished +function flip(fn){ + var flippedArr = [] + for (var i = 0; i < arguments.length; i++) { + flippedArr.unshift(arguments[i]) + } + + return fn(flippedArr); } -function flattenDeep(){ + +function flattenDeep(array){ +var newArr = []; + + function helper(arr) { + for (var i = 0; i < arr.length; i++) { + if (Array.isArray(arr[i])) { + helper(arr[i]); + } else { + newArr.push(arr[i]); + } + } + } + +helper(array); +return newArr; + } diff --git a/prototypes_exercise/prototypes.js b/prototypes_exercise/prototypes.js index e69de29b..597bc293 100644 --- a/prototypes_exercise/prototypes.js +++ b/prototypes_exercise/prototypes.js @@ -0,0 +1,98 @@ +// Create a constructor function for a Person. Each person should have a firstName, lastName, +// favoriteColor, favoriteNumber and favoriteFoods (which should be an array). + +function Person(firstName, lastName, favoriteColor, favoriteNumber, ...favoriteFoods) { + this.firstName = firstName; + this.lastName = lastName; + this.favoriteColor = favoriteColor; + this.favoriteNumber = favoriteNumber; + this.favoriteFoods = favoriteFoods; + this.family = [] +} + + +// Add a function on the Person.prototype called fullName that returns the +// firstName and lastName property of an object created by the Person constructor concatenated together. + +// var p = new Person("Shana", "Malarkin", "Green", 38); +// p.fullName(); // Shana Malarkin + +Person.prototype.fullName = function() { + return `${this.firstName} ${this.lastName}` +} + +// Overwrite the toString method from the Object prototype by creating a toString method for Person. +// The toString method should return a string in the following format: + +// var p = new Person("Shana", "Malarkin", "Green", 38); +// p.toString(); // Shana Malarkin, Favorite Color: Green, Favorite Number: 38 + +Person.prototype.toString = function() { + return `${this.firstName} ${this.lastName}, Favorite Color: ${this.favoriteColor}, Favorite Number: ${this.favoriteNumber}` +} + + +// Add a property on the Person object called family which is an empty array. +// Person.prototype.__proto__.family = []; + +// Add a function on the Person.prototype called addToFamily which adds an object constructed from the Person +// constructor to the family array. To make sure that the object you are adding is an object construced from the +// Person constructor - take a look at the instanceofoperator. Make sure that your family array does not include duplicates! +// This method should return the length of the family array. + +// var p = new Person("Shana", "Malarkin", "Green", 38) +// p.family; // [] +// p.addToFamily(p); // 1 +// p.family.length; // 1 +// p.addToFamily(p); // 1 - No duplicates! +// p.family.length; // Length should still be 1 + +Person.prototype.addToFamily = function(person) { + if (person instanceof Person && !this.family.includes(person)) { + // if (this.family.indexOf(person) === -1 && person.family !== undefined) { + this.family.push(person) + } + return this.family.length +} + + +// Implement your own version of Array.prototype.map + +Array.prototype.map = function(fn) { + var returnArr = [] + for (var i = 0; i < this.length; i++) { + returnArr.push(fn(this[i],i,this)); + } + return returnArr; +} + + + + + +//Implement a function that reverses a string and place it on the String.prototype + +String.prototype.reverse = function() { + var reversedArr = [] + for (var i = this.length-1; i >=0; i--) { + reversedArr.push(this[i]) + } + return reversedArr.join("") +} + + + +//Implement your own version of Function.prototype.bind + +Function.prototype.bind = function(thisArg, ...outerArgs) { + var _this = this; //initial function + + return function (...innerArgs) { + // return _this.apply(thisArg,outerArgs.concat(innerArgs)) //this way for apply + return _this.call(thisArg,...(outerArgs.concat(innerArgs))) //this way for call + } +} + + + + diff --git a/recursion_exercise/recursion.js b/recursion_exercise/recursion.js index e69de29b..e8eafaa0 100644 --- a/recursion_exercise/recursion.js +++ b/recursion_exercise/recursion.js @@ -0,0 +1,181 @@ +// - Write a function called `productOfArray` which takes in an array of numbers and returns the product of them all + +function productOfArray(arr) { + 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 arr = [] +function helper(a){ + for (var key in a){ + if (typeof(a[key]) === "object") { + helper(a[key]) + } else { + arr.push(a[key]) + } + } +} +helper(obj) +return arr; +} + + + +// - Write a function called `contains` that searches for a value in a nested object. It returns true if the object contains that value. + +function contains(nestedObject, value) { + for (var key in nestedObject) { + if (typeof(nestedObject[key]) === "object") { + if (contains(nestedObject[key], value)) { + return true + }; + } + if (nestedObject[key] === value) { + return true; + } + } + return false +} + + + +// - [https://www.codewars.com/kata/the-real-size-of-a-multi-dimensional-array/train/javascript](https://www.codewars.com/kata/the-real-size-of-a-multi-dimensional-array/train/javascript) +function realSize(arrays) { +var count = 0; + function helper(a) { + for (var i =0; i < a.length; i++) { + if (Array.isArray(a[i]) === true) { + helper(a[i]) + }else if (Number.isInteger(a[i])) { + count++; + } + } + } +helper(arrays) +return count; +} + + + +// - [https://www.codewars.com/kata/sum-squares-of-numbers-in-list-that-may-contain-more-lists/train/javascript](https://www.codewars.com/kata/sum-squares-of-numbers-in-list-that-may-contain-more-lists/train/javascript) + +function SumSquares(l){ +var sum = 0 +function helper(a) { + for (var i = 0; i < a.length; i++) { + if (Array.isArray(a[i]) === true) { + helper(a[i]) + } else if (Number.isInteger(a[i])) { + sum += (a[i] * a[i]) + } + } + } + helper(l) + return sum +} + + +// - [https://www.codewars.com/kata/recursive-replication](https://www.codewars.com/kata/recursive-replication) +function replicate(times, number) { +if (times === 1) { + return [number]; +} +if (times < 1) { +return []; +} +return [number].concat(replicate(times-1, number)) +} + + +// Write a function called search that finds a value in an array and returns the index where the value is at. If the value is not found, the function should return negative 1. +function search(arr,val) { + var index = 0 + function helper(a,v) { + for (var i = 0; i < a.length; i++) { + if (a[i] === v) { + return i + } + } + return -1; + } +return helper(arr,val) + +} + + +//Refactor your search function to use a faster algorithm called binary search https://www.youtube.com/watch?v=JQhciTuD3E8. +function binarySearch(arr,val) { +var l = 0; +var r = arr.length - 1; +var middle = Math.floor((l+r)/2); + + function helper(a,v,l,r) { + middle = Math.floor((l+r)/2); + if (l > r) { + return middle = -1; + } + if (a[middle] === v) { + return middle + } else if (v > a[middle]) { + l = middle+1 + helper(a,v,l, r) + } else { + r = middle -1 + helper(a,v, l, r) + } + } +helper(arr,val,l,r) +return middle +} + +// //iterative +// function binary(arr, val) { +// var l = 0 +// var r = arr.length-1 +// var middle = 0; + +// while (true) { +// if (l > r) { +// return -1 +// } + +// middle = Math.floor((l+r)/2) + +// if (arr[middle] === val) { +// return middle +// } else if (val > arr[middle]) { +// l = middle +1 +// } else { +// r = middle - 1 +// } +// } +// } + + + + +//- Write a function called `stringifyNumbers` which takes in an object and finds all of the values which are numbers and converts them to strings. Recursion would be a great way to solve this! + +function stringifyNumbers(obj) { + var answer = {} + for (var key in obj) { + if (typeof obj[key] === "number") { + answer[key] = obj[key].toString(); + } else if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + answer[key] = stringifyNumbers(obj[key]) + } else { + answer[key] = obj[key]; + } + } + return answer; +} + + + diff --git a/recursion_exercise/recursionSpec.js b/recursion_exercise/recursionSpec.js index 5bc841fe..2306ee0a 100644 --- a/recursion_exercise/recursionSpec.js +++ b/recursion_exercise/recursionSpec.js @@ -78,8 +78,8 @@ describe("#search", function(){ expect(search([1,2,3,4,5,6,7],6)).to.equal(5) }); it("should return -1 if the value is not found", function(){ - expect(search([1,2,3,4]),0).to.equal(-1) - expect(search([1,2]),11).to.equal(-1) + expect(search([1,2,3,4],0)).to.equal(-1) + expect(search([1,2],11)).to.equal(-1) }); }); diff --git a/testing_exercise/testing.js b/testing_exercise/testing.js index e69de29b..1772c027 100644 --- a/testing_exercise/testing.js +++ b/testing_exercise/testing.js @@ -0,0 +1,50 @@ +function replaceWith(str, character, replace){ + var strArr = str.split(""); + for (var i = 0; i < strArr.length; i++) { + if (strArr[i] === character) { + strArr[i] = replace; + } + } + return strArr.join(""); +} + + +function expand(arr, num) { + var output = []; + for (var i = 1; i <= num; i++) { + for (var j = 0; j< arr.length; j++){ + output.push(arr[j]); + } + } + return output +} + + +function acceptNumbersOnly(){ + for (var i = 0; i < arguments.length; i++){ + if (typeof arguments[i] !== "number" || arguments[i] % 1 !== 0) { + return false; + } + } + return true; +} + + +function mergeArrays(arr1,arr2) { + return arr1.concat(arr2).sort() +} + +function mergeObjects(obj1, obj2) { + var joined = {}; + for (var key in obj1) { + joined[key] = obj1[key]; + } + for (var keys in obj2) { + if (joined[keys]) { + delete joined[keys]; + } + joined[keys] = obj2[keys]; + } + return joined; +} + diff --git a/testing_exercise/testingSpec.js b/testing_exercise/testingSpec.js index aef56b1d..87ed8890 100644 --- a/testing_exercise/testingSpec.js +++ b/testing_exercise/testingSpec.js @@ -1,3 +1,42 @@ var expect = chai.expect; -// WRITE YOUR TESTS HERE! \ No newline at end of file +// WRITE YOUR TESTS HERE! + +describe("replaceWith", function(){ + it("returns right answer", function() { + expect(replaceWith("awesome", "e", "z")).to.equal("awzsomz"); + expect(replaceWith("Foo", "F", "B")).to.equal("Boo"); + }); + +}); + + +describe("expand", function() { + it("returns right length", function() { + expect(expand(["foo", "test"],1)).to.deep.equal(["foo","test"]); + expect(expand([1,2,3],3)).to.deep.equal([1,2,3,1,2,3,1,2,3]); + }); +}) + +describe("acceptNumbersOnly", function() { + it("returns the right bool", function(){ + expect(acceptNumbersOnly(1,"foo")).to.equal(false); + expect(acceptNumbersOnly(1,2,3,4,5,6,7)).to.equal(true); + expect(acceptNumbersOnly(1,2,3,4,5,6,NaN)).to.equal(false); + }); + +}) + + +describe("mergeArrays", function() { + it("merged arrays", function() { + expect(mergeArrays([2,1],[3,4])).to.deep.equal([1,2,3,4]); + }) +}) + +describe("mergeObjects", function() { + it("merge objects", function() { + expect(mergeObjects({name: "Foo", num: 33}, {test: "thing", num: 55})).to.deep.equal({name: "Foo", test: "thing", num: 55}); + }) +}) +