diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..1034b25b Binary files /dev/null and b/.DS_Store differ diff --git a/ajax_with_jquery_exercise/index.css b/ajax_with_jquery_exercise/index.css new file mode 100644 index 00000000..24445857 --- /dev/null +++ b/ajax_with_jquery_exercise/index.css @@ -0,0 +1,18 @@ +.row{ + margin-bottom: 30px; +} +#btn_group{ + width: 100%; + display: flex; + flex-direction: + row; justify-content: space-around; +} +form button{ + width: 100px; +} +.glyphicon{ + margin: 5px; +} +.hideNoLogin{ + visibility: hidden; +} \ No newline at end of file diff --git a/ajax_with_jquery_exercise/index.html b/ajax_with_jquery_exercise/index.html new file mode 100644 index 00000000..29f30c20 --- /dev/null +++ b/ajax_with_jquery_exercise/index.html @@ -0,0 +1,50 @@ + + + + + Linker + + + + + +
+
+
icon
+
+
+
+ +
+ +
+
+ + + + + \ No newline at end of file diff --git a/ajax_with_jquery_exercise/index.js b/ajax_with_jquery_exercise/index.js new file mode 100644 index 00000000..6b6b8817 --- /dev/null +++ b/ajax_with_jquery_exercise/index.js @@ -0,0 +1,203 @@ +$(document).ready(function(){ + //variables + var $login_form = $(`#login-form`); + var $email = $(`#inp-email`); + var $pword = $(`#inp-password`); + var $login_fail = $(`#login-fail`); + var $login_link = $(`#login-link`); + var $links = $(`#links`); + var $fav = $(`#favor-link`); + var fav = []; + var all = []; + + //imeadiat calls + if(!!localStorage.getItem('auth_token')) getFav(); + getTop().then(function(data){ + console.log(data); + all = data; + displayAll(data); + }); + + //click functions + $fav.click(function(){ + console.log('fav click'); + if(!localStorage.getItem('auth_token')){ + $login_form .toggleClass("hidden"); + }else if($fav.text() === `Favoriets`){ + $fav.text('All'); + displayFav(fav); + }else{ + $fav.text('Favoriets'); + displayAll(all); + } + }); + + $login_link.click(function(){ + if($login_link.text() === `Logout`){ + localStorage.removeItem('auth_token'); + $login_link.text('Login'); + fav = []; + }else{ + $login_form .toggleClass("hidden"); + } + }); + + $(`#login-btn`).click(function(e){ + e.preventDefault(); + + console.log($email.val(), $pword.val()); + getLogin($email.val(), $pword.val()) + .then(function(token){ + console.log(token) + $login_fail.addClass('hidden'); + $login_form.addClass('hidden'); + $login_link.text('Logout'); + getFav(); + }) + .fail(function(){ + $login_fail.removeClass('hidden'); + }) + }); + + $(`#signup-btn`).click(function(e){ + e.preventDefault(); + + console.log($email.val(), $pword.val(), true); + getLogin($email.val(), $pword.val(), true) + .then(function(token){ + console.log(token) + $login_fail.addClass('hidden'); + $login_form.addClass('hidden'); + $login_link.text('Logout'); + }) + .fail(function(){ + $login_fail.removeClass('hidden'); + }) + }); + + $links.on('click', '.star', function(e){ + var id = $(e.target).attr('storyid'); + setFav(id); + }); + + // regular functions + function isFav(sid){ + return fav.some(function(sid,v, v.story_id, sid == v.story_id){ + console.log(v); + return sid === v.story_id; + }); + } + + function displayAll(arr){ + $links.empty(); + arr.forEach(function(v) { + displayLink(v.title, + v.url, + v.id, + isFav(v.id), + !!localStorage.getItem('auth_token')); + }); + } + + function displayFav(arr){ + $links.empty(); + arr.forEach(function(v) { + displayLink(v.title, + v.url, + v.storyId, + true, + true); + }); + } + + function displayLink(title, link, storyId=0, favor = false, login = false){ + var loginClass = 'hideNoLogin'; + if(login) loginClass = 'showOnLogin'; + let html = ``; + let shortLink = ''; + if(link) { shortLink = link.split('/').filter(v => v.includes('.')); } + if(favor) html = ``; + { html += `${title} ( ${shortLink[0]} )`; } + let $lin = $('
  • '); + $lin.html(html); + if(favor) $lin.addClass('favor'); + $lin.addClass('bg-warning') + $links.append($lin); + } + + function storyFromID(id){ + + + for(let s of all){ + if(s.id == id) { + return s; + } + } + } + + //ajax functions + function getTop(){ + return $.get('https://hacker-news.firebaseio.com/v0/' + + 'topstories.json?print=pretty') + .then(function(topstories){ + console.log(topstories); + return Promise.all(topstories.slice(0,50).map(function(v,i){ + return $.get( + `https://hacker-news.firebaseio.com/v0/` + + `item/${topstories[i]}.json?print=pretty`) + })); + }) + .fail((err) => console.warn(err)); + } + + function getFav() { + return $.ajax({ + method: "GET", + headers: { + "Authorization": localStorage.getItem('auth_token'), + }, + 'url': 'https://hn-favorites.herokuapp.com/stories.json', + }) + .then((favorites) => {console.log(favorites); return fav = favorites;}) + .fail((err) => console.warn(err)); + } + + function getLogin(email, password, signup = false){ + var urlEnd = 'login'; + if(signup) urlEnd = 'signup'; + + return $.ajax({ + method: "POST", + headers: { + "Content-Type": "application/json" + }, + url: `https://hn-favorites.herokuapp.com/${urlEnd}`, + data: JSON.stringify({ + 'email': email, + 'password': password + }) + }).then(function(data) { + localStorage.setItem('auth_token', data.auth_token); + auth_token = data.auth_token; + return(data.auth_token); + }) + } + + function setFav(id){ + var s = storyFromID(id); + + return $.ajax({ + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": localStorage.getItem('auth_token'), + }, + url: `https://hn-favorites.herokuapp.com/stories.json`, + data: JSON.stringify({ + "hacker_news_story": s, + }) + }) + .then((res) => console.log(res)) + } + +}); \ No newline at end of file diff --git a/call_apply_bind_exercise/callApplyBind.js b/call_apply_bind_exercise/callApplyBind.js index e69de29b..fcc4817a 100644 --- a/call_apply_bind_exercise/callApplyBind.js +++ b/call_apply_bind_exercise/callApplyBind.js @@ -0,0 +1,50 @@ +"use strict" + +function sumEvenArguments(){ + var arr = [].slice.call(arguments); + return arr.reduce( + function(t, v){ + if(v % 2 === 0) { return t+v; } + else { return t;} + },0); +} + +function arrayFrom(obj){ + return [].slice.call(obj); + //return Array.prototype.slice.call(obj); + /* + var arr = []; + + for(let i = 0; i < obj.length; i++){ + arr.push(obj[i]); + } + + return arr; + */ +} + +function invokeMax(fn, max){ + var count = 0; + + return function(){ + if(++count > max) return `Maxed Out!`; + var arr = [].slice.call(arguments); + + return fn.apply(this, arr); + }; + +} + +function guessingGame(amount){ + var count = 0; + var answer = Math.floor(Math.random() * 11); + + return function(guess){ + if(count++ === amount) { return `No more guesses the answer was ${answer}`; } + else if(count > amount) { return `You are all done playing!`; } + else if(answer > guess){ return "You're too low!"; } + else if(answer < guess){ return "You're too high!"; } + else if(answer === guess){ return "You got it!"; } + } + +} diff --git a/call_apply_bind_exercise/callApplyBindSpec.js b/call_apply_bind_exercise/callApplyBindSpec.js index 609e3ff0..08037827 100644 --- a/call_apply_bind_exercise/callApplyBindSpec.js +++ b/call_apply_bind_exercise/callApplyBindSpec.js @@ -32,4 +32,63 @@ describe("#invokeMax", function(){ expect(addOnlyThreeTimes(1,2)).to.equal("Maxed Out!") expect(addOnlyThreeTimes(1,2)).to.equal("Maxed Out!") }); +}); + +describe("#guessingGame", function(){ + + it("shuould return the right type", function(){ + var game = guessingGame(0); + expect(typeof game).to.equal('function') + expect(typeof game(0)).to.equal('string') + }); + + it("inner function should return the correct results", function(){ + var game = guessingGame(0); + expect(game(0).substring(0,31)).to.equal('No more guesses the answer was ') + expect(game(0)).to.equal('You are all done playing!') + expect(game(-1)).to.equal('You are all done playing!') + game = guessingGame(10); + for(let t = 0; t < 10; t++){ + expect(game(-1)).to.equal("You're too low!") + } + expect(game(-1).substring(0,31)).to.equal('No more guesses the answer was ') + expect(game(-1)).to.equal('You are all done playing!') + expect(game(-1)).to.equal('You are all done playing!') + game = guessingGame(12); + for(let t = 0; t < 12; t++){ + expect(game(11)).to.equal("You're too high!") + } + expect(game(11).substring(0,31)).to.equal('No more guesses the answer was ') + expect(game(11)).to.equal('You are all done playing!') + expect(game(-1)).to.equal('You are all done playing!') + game = guessingGame(11) + var gotWin = false; + for(let t = 0; t < 11; t++){ + if(game(t) === "You got it!"){ + gotWin = true; + break; + } + } + expect(gotWin).to.equal(true) + }); + + it("should have choose every possiblity and change", function(){ + var cntObj = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0,}; + for(let t = 0; t < 1000000; t++){ + let game = guessingGame(11); + for(let n = 0; n < 11; n++){ + if(game(n) === "You got it!"){ + cntObj[n]++; + break; + } + } + + // return false or expect(flase).to.equal(true) + + } + for(let n = 0; n < 11; n++){ + expect(cntObj[n] > 10).to.equal(true) + } + }); + }); \ No newline at end of file diff --git a/call_apply_bind_exercise/readme.md b/call_apply_bind_exercise/readme.md index 36f0fedb..28cedae6 100644 --- a/call_apply_bind_exercise/readme.md +++ b/call_apply_bind_exercise/readme.md @@ -13,9 +13,40 @@ var obj = { } ``` +```javascript +var obj = { + fullName: "Harry Potter", + person: { + sayHi: function(){ + return "This person's name is " + obj.fullName + } + } +} + +console.log( obj.person.sayHi() ); + + +var newObj = { + fullName: "Harry Potter", + sayHi() { return `This person's name is ${this.fullName}`; } + } + +console.log( newObj.sayHi() ); + +var newerObj = { + fullName: "Harry Potter",} + +function sayHi() { return `This person's name is ${this.fullName}`; } + +console.log( sayHi.call(obj)); +console.log( sayHi.call(newObj)); +console.log( sayHi.call(newerObj)); + +``` + - List two examples of "array-like-objects" that we have seen. - - - - + - arguments + - jQuery selectors like $('p'); ### Functions to write: diff --git a/canvas_exercise/shapes_game/index.html b/canvas_exercise/shapes_game/index.html index 97529df5..6232fca5 100644 --- a/canvas_exercise/shapes_game/index.html +++ b/canvas_exercise/shapes_game/index.html @@ -10,33 +10,57 @@
    -
    - -
    -
    -

    Score

    -

    0

    -

    Timer

    -

    30

    -
    -

    Legend

    -
    -
    -
    -

    Left

    -
    -
    -

    Right

    + +
    +
    + +
    + +
    + +
    +

    Score

    +

    0

    +
    +
    +

    Timer

    +

    30

    +
    + +
    + +

    Legend

    + +
    +
    +
    +

    Left

    +
    + +
    +
    +
    +

    Right

    +
    + +

    Up

    -
    -
    +
    + +
    +

    Down

    -
    + +
    + +
    +
    +
    \ No newline at end of file diff --git a/canvas_exercise/shapes_game/index.js b/canvas_exercise/shapes_game/index.js index 0de5f18a..a42dbc54 100644 --- a/canvas_exercise/shapes_game/index.js +++ b/canvas_exercise/shapes_game/index.js @@ -1,15 +1,91 @@ window.addEventListener("load", function() { - function clear(ctx, width, heigt) { + function clear() { + ctx.clearRect(0,0,width,height); } - function drawRandomShape(ctx, width, height) { + function drawRandomShape() { + let top = Math.floor(Math.random() * (height -50)); + let left = Math.floor(Math.random() * (width -50)); + let pick = Math.floor(Math.random() * 4); + clear(); + + switch (pick){ + case 0: //white0 white triangle = up + expectedKey = 'ArrowUp'; + ctx.fillStyle = "white"; + ctx.beginPath(); + ctx.moveTo(left,top); + ctx.lineTo(left+50, top+50); + ctx.lineTo(left, top+50); + ctx.fill(); + ctx.closePath(); + break; + case 1: //red1 red square = down + expectedKey = 'ArrowDown'; + ctx.fillStyle = 'red'; + ctx.fillRect( + left, + top, + 50, + 50); + break; + case 2: //red0 red triangle = left + expectedKey = 'ArrowLeft'; + ctx.fillStyle = "red"; + ctx.beginPath(); + ctx.moveTo(left,top); + ctx.lineTo(left+50, top+50); + ctx.lineTo(left, top+50); + ctx.fill(); + ctx.closePath(); + break; + case 3: //white1 white square = right + expectedKey = 'ArrowRight'; + ctx.fillStyle = 'white'; + ctx.fillRect( + top, + left, + 50, + 50); + break; + } + } - function drawGameStartText(ctx, width, height, score) { + function drawGameStartText() { + console.log('End Game'); + clear(); + ctx.font = '2em serif'; + ctx.textAlign = 'center'; + ctx.fillStyle = 'white'; + ctx.fillText('Press the space bar to start the game.', + Math.floor(width/2), + Math.floor(height/2.25)); + if(score > 0){ + ctx.fillText('Last score is ' + score, + Math.floor(width/2), + Math.floor(height/2)); + } + } - function restartGame(ctx, width, height) { + function startGame(){ + console.log('Starting Game'); + scoreSpan.innerText = score = 0; + seconds = 30; + gameOn = true; + clear(); + drawRandomShape(); + + intervalId = setInterval(function(){ + timerSpan.innerText = --seconds; + if(seconds <= 0) { + clearInterval(intervalId); + gameOn = false; + drawGameStartText(); + } + }, 1000); } var canvas = document.getElementById("shapes-game"), @@ -18,19 +94,28 @@ window.addEventListener("load", function() { gameOn = false, expectedKey = undefined, ctx = canvas.getContext('2d'), - // white triangle = up, red square = down, - // red triangle = left, white square = right - expectedKeysMap = {white0: 38, red1: 40, red0: 37, white1: 39}, timerSpan = document.getElementById("time-remaining"), scoreSpan = document.getElementById("score-val"), - seconds = 3, + score = 0, + seconds = 0, intervalId; canvas.width = width; canvas.height = height; - document.addEventListener("keyup", function() { - + document.addEventListener("keyup", function(e) { + if(e.key === ' ' && !gameOn){ + startGame(); + }else if(gameOn && e.key == expectedKey){ //right key + scoreSpan.innerText = ++score; + drawRandomShape(); + }else if(gameOn && 'ArrowUpArrowDownArrowLeftArrowRight'.includes(e.key)){ //wrong key + scoreSpan.innerText = --score; + drawRandomShape(); + } }); + + //On Load + drawGameStartText(); }); diff --git a/canvas_exercise/shapes_game/styles.css b/canvas_exercise/shapes_game/styles.css index cbe4fa83..84caaed0 100644 --- a/canvas_exercise/shapes_game/styles.css +++ b/canvas_exercise/shapes_game/styles.css @@ -11,11 +11,11 @@ body { padding: 10px; } .canvas-container, #shapes-game { - height: 750px; - width: 800px; + height: 90vh; } -.scores { +.key { + height: 90vh; padding: 10px; text-align: center; } @@ -30,6 +30,7 @@ body { } .triangle-bottomleft-red { + margin: 0 auto; width: 0; height: 0; border-bottom: 50px solid red; @@ -37,6 +38,7 @@ body { } .triangle-bottomleft-black { + margin: 0 auto; width: 0; height: 0; border-bottom: 54px solid black; @@ -44,6 +46,7 @@ body { } .triangle-inner-white { + margin: 0 auto; position: relative; top: 2px; left: 2px; @@ -54,6 +57,7 @@ body { } .triangle-left { + margin: 0 auto; width: 0; height: 0; border-top: 23px solid transparent; @@ -62,6 +66,7 @@ body { } .inner-triangle { + margin: 0 auto; position: relative; top: -20px; left: 2px; @@ -73,12 +78,14 @@ body { } .red-square { + margin: 0 auto; width: 50px; height: 50px; background-color: red; } .white-square { + margin: 0 auto; width: 50px; height: 50px; background-color: white; diff --git a/es2015_exercise/readme.md b/es2015_exercise/readme.md index 9e482efa..8abdd80d 100644 --- a/es2015_exercise/readme.md +++ b/es2015_exercise/readme.md @@ -11,16 +11,31 @@ var person = { }.bind(this),1000) } } + +// 2015 +var person = { + fullName: "Harry Potter", + sayHi(){ + setTimeout(() => console.log(`Your name is ${this.fullName}`),1000) + } +} ``` ```javascript var name = "Josie" console.log("When " + name + " comes home, so good") + +// 2015 +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! + +// 2015 +const DO_NOT_CHANGE = 42; ``` ```javascript @@ -28,6 +43,10 @@ var arr = [1,2] var temp = arr[0] arr[0] = arr[1] arr[1] = temp + +// 2015 +let [ta, tb, ...tc] = arr; +arr = [tb, ta, ...tc]; ``` ```javascript @@ -36,6 +55,9 @@ function double(arr){ return val*2 }); } + +// 2015 +var double = arr => arr.map(val => val*2); ``` ```javascript @@ -48,6 +70,9 @@ var obj = { var a = obj.numbers.a; var b = obj.numbers.b; + +// 2015 +var {a, b} = obj.numbers; ``` ```javascript @@ -62,6 +87,9 @@ function add(a,b){ } return a+b } + +// 2015 +var add = (a = 10,b = 10) => a+b; ``` Research the following functions - what do they do? diff --git a/intermediate_oop/tic_tac_toe/css/main.css b/intermediate_oop/tic_tac_toe/css/main.css index c009bbb2..0f362e13 100644 --- a/intermediate_oop/tic_tac_toe/css/main.css +++ b/intermediate_oop/tic_tac_toe/css/main.css @@ -8,7 +8,7 @@ body { width: 185px; height: 165px; margin: 3px; - background-color: #bfbfbf; + border: 7px solid #bfbfbf; vertical-align: top; font-size: 700%; color: red; @@ -24,4 +24,17 @@ body { #message { font-size: 3em; +} +#board{ + width: 600px; + height: 525px; + margin: auto; +} +.X{ + color: green; + border: 5px solid green; +} +.O{ + color: blue; + border: 5px solid blue; } \ No newline at end of file diff --git a/intermediate_oop/tic_tac_toe/index.html b/intermediate_oop/tic_tac_toe/index.html index 00c74eb9..6102a83c 100644 --- a/intermediate_oop/tic_tac_toe/index.html +++ b/intermediate_oop/tic_tac_toe/index.html @@ -11,13 +11,14 @@ - - - + + +

    Tic Tac Toe

    -
    +
    +
    @@ -34,6 +35,7 @@

    Tic Tac Toe

    +

    diff --git a/intermediate_oop/tic_tac_toe/js/main.js b/intermediate_oop/tic_tac_toe/js/main.js index 379d891d..613ee8cc 100644 --- a/intermediate_oop/tic_tac_toe/js/main.js +++ b/intermediate_oop/tic_tac_toe/js/main.js @@ -1,2 +1,142 @@ document.addEventListener("DOMContentLoaded", function() { -}); + //Imediate Calls + var game = new Game(); + + //set up web clicks + $('#new-game').click(function(){ + game.reset(); + }) + + + //Functions + function Game(){ + this.player = 'X'; + this.message = new Message(); + this.board = new Board(this); + this.gameOn = true; + } + Game.prototype.reset = function(){ + this.player = 'X'; + this.board.clear(); + this.message.clear(); + this.board.changePlayer(this.player); + this.gameOn = true; + } + Game.prototype.play = function(row, col){ + //check for leagal move + if(this.gameOn && this.board.isEmpty(row,col)){ + //mark play + this.board.play(row,col,this.player); + //check for win or tie + if(this.winLooseOrDraw()){ + this.gameOn = false; + this.message.set(this.winLooseOrDraw()); + } + //change players + this.player = (this.player === 'X'? 'O':'X'); + this.board.changePlayer(this.player); + //this.board. + } + } + Game.prototype.winLooseOrDraw = function(){ + let ties = 0; + for(let row = 0; row < 3; row++){ + let count = {X:0, O:0, "":0}; + for(let col = 0; col < 3; col++){ + count[this.board.get(row, col)]++; + } + if(count['X']>0 && count['O']>0) ties++; + else if(count['X'] === 3) return 'X Wins!'; + else if(count['O'] === 3) return 'O Wins!'; + //console.log(count,ties); + } + for(let col = 0; col < 3; col++){ + let count = {X:0, O:0, "":0}; + for(let row = 0; row < 3; row++){ + count[this.board.get(row, col)]++; + } + if(count['X']>0 && count['O']>0) ties++; + else if(count['X'] === 3) return 'X Wins!'; + else if(count['O'] === 3) return 'O Wins!'; + //console.log(count,ties); + } + let count = {X:0, O:0, "":0}; + for(let row = 0, col=0; row < 3; row++, col++){ + count[this.board.get(row, col)]++; + } + if(count['X']>0 && count['O']>0) ties++; + else if(count['X'] === 3) return 'X Wins!'; + else if(count['O'] === 3) return 'O Wins!'; + count = {X:0, O:0, "":0}; + for(let row = 2, col=0; row >= 0; row--, col++){ + count[this.board.get(row, col)]++; + } + if(count['X']>0 && count['O']>0) ties++; + else if(count['X'] === 3) return 'X Wins!'; + else if(count['O'] === 3) return 'O Wins!'; + + if(ties === 8) return 'Tie Game'; + else return false; + } + + function Board(game){ + this.game = game; + this.$board = $('#board'); + this.squares = []; + + for(let r = 0; r < 3; r++){ + let row = []; + for(let col = 0; col < 3; col++){ + row.push(new Squares($(`#square_${r}_${col}`))); + } + this.squares.push(row); + } + + this.$board.on('click', '.square', function(e){ + var [row, col] = e.target.id.split('_').slice(1); + this.game.play(row,col); + }.bind(this)); + + } + Board.prototype.clear = function(){ + $('.square').text('').removeClass('X O'); + } + Board.prototype.get = function(row, col){ + return this.squares[row][col].get(); + } + Board.prototype.isEmpty = function(row, col){ + return this.squares[row][col].isEmpty(); + } + Board.prototype.play = function(row, col, player){ + this.squares[row][col].set(player); + } + Board.prototype.changePlayer = function(player){ + this.$board.removeClass('X O'); + this.$board.addClass(player); + } + + function Squares($jObj){ + this.$jObj = $jObj; + } + Squares.prototype.isEmpty = function(){ + return this.$jObj.text() === ''; + } + Squares.prototype.set = function(val){ + this.$jObj.text(val); + this.$jObj.addClass(val); + } + Squares.prototype.get = function(){ + return this.$jObj.text(); + } + + function Message(){ + this.$message = $('#message'); + } + Message.prototype.set = function(msg){ + this.$message.text(msg); + } + Message.prototype.clear = function(msg){ + this.$message.text(''); + } + +}); \ No newline at end of file diff --git a/jquery_exercise/icon.gif b/jquery_exercise/icon.gif new file mode 100644 index 00000000..c04be1a4 Binary files /dev/null and b/jquery_exercise/icon.gif differ diff --git a/jquery_exercise/icon.png b/jquery_exercise/icon.png new file mode 100644 index 00000000..e69de29b diff --git a/jquery_exercise/index.css b/jquery_exercise/index.css new file mode 100644 index 00000000..345814a7 --- /dev/null +++ b/jquery_exercise/index.css @@ -0,0 +1,6 @@ +.row{ + margin-bottom: 30px; +} +.glyphicon{ + margin: 5px; +} \ No newline at end of file diff --git a/jquery_exercise/index.html b/jquery_exercise/index.html new file mode 100644 index 00000000..40465cb4 --- /dev/null +++ b/jquery_exercise/index.html @@ -0,0 +1,44 @@ + + + + + Linker + + + + + +
    +
    +
    +
    icon
    + +
    + +
    + +
    +
    + + + + + \ No newline at end of file diff --git a/jquery_exercise/index.js b/jquery_exercise/index.js new file mode 100644 index 00000000..630bd825 --- /dev/null +++ b/jquery_exercise/index.js @@ -0,0 +1,67 @@ +$(document).ready(function(){ + var $submit_form = $('#submit-form'); + var $inp_title = $('#inp-title'); + var $inp_url = $('#inp-url'); + var links = JSON.parse(localStorage.getItem('links')); + if(links === null){ + links = [ + { + favor: true, + title: "Isn't this the best site you have ever seen?", + link: 'file:///Users/chaim/Dropbox/rithm/canvas.html' + }]; + } + var $links = $('#links'); + + function displayLink(favor, title, link){ + let html = ''; + let shortLink = link.split('/').filter(v => v.includes('.')); + if(favor) html = ''; + html += '' + title + '(' + shortLink[0] + ')'; + let $lin = $('
  • '); + $lin.html(html); + if(favor) $lin.addClass('favor'); + $lin.addClass('bg-warning') + $links.append($lin); + } + + function saveLinks() { + localStorage.setItem('links', JSON.stringify(links)); + } + + for(let lin of links){ + displayLink(lin.favor, lin.title, lin.link); + } + + $('#submit-link').click(function(){ + $submit_form.toggleClass("hidden"); + }); + $('#favor-link').click(function(){ + $links.find('li').not('.favor').toggleClass('hidden'); + }); + $submit_form.submit(function(e){ + e.preventDefault(); + + displayLink(false, $inp_title.val(), $inp_url.val()); + links.push({ + favor: false, + title: $inp_title.val(), + link: $inp_url.val()}); + $inp_title.val(''); + $inp_url.val(''); + saveLinks(); + + }); + $links.on('click', '.star', function(e){ + e.preventDefault(); + + var $target = $(e.target); + + $target.toggleClass('glyphicon-star-empty glyphicon-star'); + var index = $target.parent().index(); + links[index].favor = $target.hasClass('glyphicon-star'); + $target.parent().toggleClass('favor'); + saveLinks(); + }); + +}); \ No newline at end of file diff --git a/lodash_exercise/lodash.js b/lodash_exercise/lodash.js index 483d734a..18cbde7e 100644 --- a/lodash_exercise/lodash.js +++ b/lodash_exercise/lodash.js @@ -1,99 +1,301 @@ -function drop(){ - +function drop(arr, skip = 1){ + return arr.slice(skip); } -function fromPairs(){ - -} +function fromPairs(arr){ + var obj = {}; -function head(){ + for(let p = 0; p < arr.length; p++){ + obj[arr[p][0]] = arr[p][1]; + } + return obj; } -function take(){ - +function head(arr){ + return arr[0]; } -function takeRight(){ +function take(arr, n = 1){ + return arr.slice(0, n); +} +function takeRight(arr, n = 1){ + return arr.reduce(function(t,c,i,a){ + if(i > arr.length-1-n){ + t.push(c); + return t; + }else return t; + },[]); } function union(){ - + var resObj = {}; + var resArr = []; + + for(let i = 0; i < arguments.length; i++){ + let arr = arguments[i]; + + for(let v of arr){ + var newKey = !resObj.hasOwnProperty(JSON.stringify(v)); + if(newKey){ + resArr.push(v); + resObj[JSON.stringify(v)] = 'Now I have it.'; + } + } + + } + + return resArr; } -function zipObject(){ +function zipObject(keys, vals){ + var obj = {}; -} + for(let i = 0; i < keys.length; i++){ + obj[keys[i]] = vals[i]; + } -function includes(){ + return obj; +} +function includes(input, val, fromIndex = 0){ + if(Array.isArray(input)){ + for(let i = fromIndex; i < input.length; i++) + { + if(input[i] === val) + return true; + } + }else if(typeof input === 'object'){ + for(let k in input){ + if(input[k] === val){ + return true; + } + } + }else if(typeof input === 'string'){ + for(let i = fromIndex; i < input.length; i++){ + var temp = input.slice(i, i+ val.length); + if(temp === val) return true; + } + } + + return false; } -function sample(){ +function sample(obj){ + if(Array.isArray(obj)){ + return obj[Math.floor(Math.random() * obj.length)]; + } + else{ + let keys = Object.keys(obj); + let k = Math.floor(Math.random() * keys.length); + return(obj[keks[k]]); + } } -function cloneDeep(){ +function cloneDeep(obj){ + var newObj = {} + if(Array.isArray(obj)) newObj = []; + + for(let k in obj){ + if(typeof obj[k] === 'object'){ newObj[k] = cloneDeep(obj[k]);} + else newObj[k] = obj[k]; + } + return newObj; } -function sumBy(){ +function sumBy(arr, cb){ + var total = 0; + var fn; + if(typeof cb === 'string'){ + fn = function(obj){ + return obj[cb]; + } + }else{ + fn = cb; + } + + for(let e of arr){ + total += fn(e); + } + + return total; +} +function inRange(num, start, end){ + if(!end){ + end = start; + start = 0; + } + + if(end < start){ + return num <= start && num > end; + } + else { + return num >= start && num < end; + } + } -function inRange(){ +function has(obj, path){ + var keys, isDefined = obj; + if(typeof path === 'string') { keys = path.split('.'); } + else { keys = path; } -} + for(let k of keys){ + isDefined = isDefined[k]; + if(isDefined === undefined) return false; + } -function has(){ + return true; + + /* + var keys; + if(typeof path === 'string') { keys = path.split('.'); } + else { keys = path; } + + if(keys.length === 0) return true; + if(obj[keys[0]] === undefined) return false; + return has(obj[keys], keys.slice[1]); + */ } -function omit(){ +function omit(obj, keys){ + var newObj = {}; + + for(let key in obj){ + newObj[key] = obj[key]; + } + + for(let key of keys){ + delete(newObj[key]); + } + return newObj; } -function pick(){ +function pick(obj, keys){ + var newObj = {}; + for(let k of keys){ + newObj[k] = obj[k]; + } + + return newObj; } -function pickBy(){ +function pickBy(obj, fn){ + var newObj = {}; + + for(let key in obj){ + if(fn(obj[key])) newObj[key] = obj[key]; + } + return newObj; } -function omitBy(){ +function omitBy(obj, fn){ + var newObj = {}; + for(let key in obj){ + if(!fn(obj[key])) newObj[key] = obj[key]; + } + + return newObj; } -function padEnd(){ +function padEnd(str, len, pad = " "){ + var newStr = str; + + while(newStr.length < len) { newStr += pad; } + return newStr.substring(0, len); } -function repeat(){ +function repeat(str, num){ + var newStr = ''; + for(let i = 0; i < num; i++) newStr += str; + + return newStr; } function upperFirst(str){ + return str[0].toUpperCase() + str.substring(1); + } -function flatten(){ +function flatten(arr){ + var newArr = []; + + for(let v of arr){ + if(Array.isArray(v)){ + for(let sv of v) newArr.push(sv); + } + else { + newArr.push(v); + } + } + return newArr; } function zip(){ + var newArr = []; + for(let a = 0; a < arguments[0].length; a++){ + let temp = []; + + for(let i = 0; i < arguments.length; i++){ + temp.push(arguments[i][a]); + } + + newArr.push(temp); + } + + return newArr; } -function unzip(){ +function unzip(arr){ + var newArr = []; + + for(let a = 0; a < arr[0].length; a++){ + let temp = []; + for(let i = 0; i < arr.length; i++){ + temp.push(arr[i][a]); + } + + newArr.push(temp); + } + + console.log(newArr); + return newArr; } -function flip(){ +function flip(fn){ + return function(...args){ + var rev = args.reverse(); + return fn(...rev); + } } -function flattenDeep(){ +function flattenDeep(arr){ + var newArr = []; + + for(let v of arr){ + if(Array.isArray(v)){ + newArr = newArr.concat(flattenDeep(v)); + } + else { + newArr.push(v); + } + } + return newArr; } diff --git a/lodash_exercise/lodashSpec.js b/lodash_exercise/lodashSpec.js index f0e90e9c..8f0d1707 100644 --- a/lodash_exercise/lodashSpec.js +++ b/lodash_exercise/lodashSpec.js @@ -73,6 +73,15 @@ describe("#takeRight", function(){ describe("#union", function(){ it("returns a new array of combined values.", function(){ expect(union([2], [1, 2])).to.deep.equal([2, 1]) + expect(union([2])).to.deep.equal([2]) + }); + it("takes arrays of other primetives", function(){ + expect(union([2], ['one', 'two'])).to.deep.equal([2, 'one', 'two']) + expect(union(['one', 'two', 'three'], ['three', 'four'])).to.deep.equal(['one', 'two', 'three', 'four']) + }); + it("takes arrays of objects", function(){ + expect(union([[2]], ['one', [2], 'two', [2,3],{'number':4}])).to.deep.equal([[2], 'one', 'two', [2,3], {'number':4}]) + expect(union(['one', 'two', 'three'], ['three', 'four'])).to.deep.equal(['one', 'two', 'three', 'four']) }); }); @@ -110,18 +119,22 @@ describe("#cloneDeep", function(){ it("should create a copy of an array when passed one", function(){ expect(cloneDeep([1,2,3])).to.be.instanceof(Array); }); - it("should create a copy of an array when passed one", function(){ + it("should create a copy of an object when passed one", function(){ expect(cloneDeep({})).to.be.instanceof(Object); }); it("should create a deep copy of an array", function(){ var objects = [{ 'a': 1 }, { 'b': 2 }]; var deep = cloneDeep(objects); expect(deep[0] === objects[0]).to.equal(false) + expect(deep).to.deep.equal(objects) }); it("should create a deep copy of an object", function(){ - o = {} - o2 = cloneDeep(o) + var o = {} + var o2 = cloneDeep(o) expect(o === o2).to.equal(false) + o = {'k': 1, 'k2': [1,2,3,{'val': true, 'val1': 'string'},4,5,6], 'k3': 'finish'}; + expect(cloneDeep(o)===o).to.equal(false) + expect(cloneDeep(o)).to.deep.equal(o) }); }); diff --git a/prototypes_exercise/prototypes.js b/prototypes_exercise/prototypes.js index e69de29b..7991205c 100644 --- a/prototypes_exercise/prototypes.js +++ b/prototypes_exercise/prototypes.js @@ -0,0 +1,78 @@ +function Person( + firstName, lastName, favoriteColor, favoriteNumber, favoriteFoods =[] + ) +{ //"Elie", "Schoppik", "purple", 34 + this.firstName = firstName; + this.lastName = lastName; + this.favoriteColor = favoriteColor; + this.favoriteNumber = favoriteNumber; + this.favoriteFoods = favoriteFoods; + this.fullName = function(){ return `${this.firstName} ${this.lastName}`;}; + this.family = []; +} + +Person.prototype.toString = function() + { return `${this.fullName()}, Favorite Color: ${this.favoriteColor}, Favorite Number: ${this.favoriteNumber}` }; +Person.prototype.addToFamily = function(fm){ + if(this.family.includes(fm)) return this.family.length; + if(fm instanceof Person === false) return this.family.length; + + this.family.push(fm); + + return this.family.length; +}; + +Array.prototype.map = function(fn, keepUndefined = false){ + var newArr = []; + + for(let i = 0; i < this.length; i++){ + if(this[i] !== undefined || keepUndefined){ + newArr.push(fn(this[i], i, this)); + } + } + + return newArr; +} + +String.prototype.reverse = function(){ + return this.split('').reverse().join(''); +} + +function rev(str){ + return str.split('').reverse().join(''); +} + +/*Function.prototype.bind = function(thisArg, ...args){ + var fnThis = this; + + return function(...newArgs){ + return fnThis.apply(thisArg, args.concat(newArgs)); + } + +}*/ + +Function.prototype.bind = function(thisArg, ...args){ + var fnThis = this; + + return function(...newArgs){ + //return fnThis.apply(thisArg, args.concat(newArgs)); + thisArg.__TempFunction__ = fnThis; + let temp = thisArg.__TempFunction__(...args,...newArgs); + delete thisArg.__TempFunction__ ; + return temp; + } + +} + +Array.prototype.reduce = function(fn, init, keepUndefined = false){ + for(let i = 0; i < this.length; i++){ + if(i === 0 && init === undefined){ + init = this[0]; + continue; + }else if(this[i] !== undefined || keepUndefined){ + init = fn(init, this[i], i, this); + } + } + + return init; +} \ No newline at end of file diff --git a/testing_exercise/testing.js b/testing_exercise/testing.js index e69de29b..2f3d050e 100644 --- a/testing_exercise/testing.js +++ b/testing_exercise/testing.js @@ -0,0 +1,41 @@ +function replaceWith(str, target, replacement){ + return str + .split('') + .map(function(v){ + if(v === target) return replacement; + else return v; + }).join(''); +} + +function expand(arr, num) { + var a = []; + + for(let i = 0; i < num; i++){ + a = a.concat(arr); + } + + return a; +} + +function acceptNumbersOnly(...args) { + for(let a of args){ + if(typeof a !== 'number' || isNaN(a)){ + return false; + } + } + + return true; +} + +function mergeArrays(arr1, arr2) { + return arr1.concat(arr2).sort(function(a, b){return a-b;}); +} + +function mergeObjects(...args) { + return args.reduce(function(t,v){ + Object.keys(v).forEach(function(sv){ + t[sv] = v[sv]; + }); + return t; + },{}); +} \ No newline at end of file diff --git a/testing_exercise/testingSpec.js b/testing_exercise/testingSpec.js index aef56b1d..60ad1315 100644 --- a/testing_exercise/testingSpec.js +++ b/testing_exercise/testingSpec.js @@ -1,3 +1,97 @@ var expect = chai.expect; -// WRITE YOUR TESTS HERE! \ No newline at end of file +describe('This will test the replaceWith function', function(){ + + it('replaceWith should be a function', function() { + expect(typeof replaceWith).to.equal('function'); + }); + it('replaceWith should return correct values', function () { + expect(replaceWith("awesome", "e", "z")).to.equal("awzsomz"); + expect(replaceWith("Foo", "F", "B")).to.equal("Boo"); + }); + it('replaceWith should be case sensitive', function () { + expect(replaceWith("awesomE", "e", "z")).to.equal("awzsomE"); + expect(replaceWith("Foo", "f", "B")).to.equal("Foo"); + expect(replaceWith("ffFFfFB", "f", "B")).to.equal("BBFFBFB"); + }); + +}); + +describe('This will test the expand function', function(){ + + it('expand should be a function', function() { + expect(typeof expand).to.equal('function'); + }); + it('expand should return correct values', function () { + expect(expand([1,2,3],3)).to.deep.equal([1,2,3,1,2,3,1,2,3]); + expect(expand(["foo", "test"],1)).to.deep.equal(["foo","test"]); + expect(expand(["foo", "test"],0)).to.deep.equal([]); + }); + +}); + +describe('This will test the acceptNumbersOnly function', function(){ + + it('expand should be a function', function() { + expect(typeof acceptNumbersOnly).to.equal('function'); + }); + + it('acceptNumbersOnly should return correct values', function () { + expect(acceptNumbersOnly(1,"foo")).to.equal(false); + expect(acceptNumbersOnly(1,2,3,4,5,6,7)).to.equal(true); + expect(acceptNumbersOnly(1)).to.equal(true); + }); + + it('acceptNumbersOnly should deal with objects input', function () { + expect(acceptNumbersOnly([])).to.equal(false); + expect(acceptNumbersOnly({})).to.equal(false); + }); + + it('acceptNumbersOnly should deal with strings input', function () { + expect(acceptNumbersOnly('')).to.equal(false); + expect(acceptNumbersOnly('5')).to.equal(false); + }); + + it('acceptNumbersOnly should deal with null input', function () { + expect(acceptNumbersOnly(null)).to.equal(false); + }); + + it('acceptNumbersOnly should deal with NaN input', function () { + expect(acceptNumbersOnly(NaN)).to.equal(false); + }); +}); + +describe('This will test the mergeArrays function', function(){ + + it('mergeArrays should be a function', function() { + expect(typeof mergeArrays).to.equal('function'); + }); + it('mergeArrays should return correct values', function () { + expect(mergeArrays([2,1],[3,4])).to.deep.equal([1,2,3,4]); + }); + +}); + +describe('This will test the mergeObjects function', function(){ + var obj1= { + name: "Foo", + num: 33 + } + var obj2 = { + test: "thing", + num: 55 + } + var obj12 = { + name: "Foo", + test: "thing", + num: 55 + } + + it('mergeObjects should be a function', function() { + expect(typeof mergeObjects).to.equal('function'); + }); + it('mergeObjects should return correct values', function () { + expect(mergeObjects(obj1, obj2)).to.deep.equal(obj12); + }); + +}); \ No newline at end of file