diff --git a/week-1-project/README.md b/week-1-project/README.md index 623d867..ca008b2 100644 --- a/week-1-project/README.md +++ b/week-1-project/README.md @@ -1,3 +1,8 @@ +## Week1 Practice Exercises Link + ### Please follow the link below to open the practice exercises of Week1 project + +Practice Exercises Week1

+ ## Week 1 Project The weekly projects in JS 2 will be making an even stronger distinction between your core application and the user interface. To help you with this transition there will be two assignment tables, one for the core app object and another for the user interface. diff --git a/week-1-project/app.js b/week-1-project/app.js index 5fdfbea..ed1bcfc 100644 --- a/week-1-project/app.js +++ b/week-1-project/app.js @@ -1,43 +1,119 @@ const object = { numberyStrings: [], NaNyStrings: [], + // evenStringsArr: [], isNumberyString: function (param) { - // write me! + // return typeof param === 'string' && !isNaN(param); + return typeof param !== 'string' ? false :isNaN(param) ? false : true; }, addString: function (param) { - if (null) return false; // write this early return condition - - // write me! (using this.isNumberyString) + if (typeof param !== 'string') return false; // write this early return condition + + else if (isNaN(param)) {this.NaNyStrings.push(param);} + + else if (!isNaN(param)) {this.numberyStrings.push(param);} + return true; }, allStrings: function () { - // write me! + + if (this.NaNyStrings.length===0) return this.numberyStrings; + if(this.numberyStrings.length===0) return this.NaNyStrings; + return this.numberyStrings.concat(this.NaNyStrings); }, evenStrings: function () { - // write me! - }, + + if ((this.NaNyStrings.length!==0) && (this.numberyStrings.length===0)) + return this.numberyStrings; + else if ((this.NaNyStrings.length===0) && (this.numberyStrings.length!==0)){ + function checkEven(num) {return num%2 === 0}; + return this.numberyStrings.filter(checkEven); + } + else if ((this.NaNyStrings.length!==0) && (this.numberyStrings.length!==0)){ + function checkEven(num) {return num%2 === 0}; + return this.numberyStrings.filter(checkEven); + } + }, oddStrings: function () { - // write me! + if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0) + return this.numberyStrings; + else if ((this.NaNyStrings.length===0) && (this.numberyStrings.length!==0)){ + function checkOdd(num) {return num%2 !== 0}; + return this.numberyStrings.filter(checkOdd); + } + else if ((this.NaNyStrings.length!==0) && (this.numberyStrings.length!==0)){ + function checkOdd(num) {return num%2 !== 0}; + return this.numberyStrings.filter(checkOdd); + } }, negativeStrings: function () { - // write me! + if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0) + return this.numberyStrings; + else if (this.NaNyStrings.length === 0 && this.numberyStrings.length !== 0){ + function checkNegative(num) {return num < 0}; + return this.numberyStrings.filter(checkNegative); + } + else if (this.NaNyStrings.length !== 0 && this.numberyStrings.length !== 0){ + function checkNegative(num) {return num < 0}; + return this.numberyStrings.filter(checkNegative); + } }, positiveStrings: function () { - // write me! + if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0) + return this.numberyStrings; + else if (this.NaNyStrings.length === 0 && this.numberyStrings.length !== 0){ + function checkPozitive(num) {return num > 0}; + return this.numberyStrings.filter(checkPozitive); + } + else if (this.NaNyStrings.length !== 0 && this.numberyStrings.length !== 0){ + function checkPozitive(num) {return (num > 0 || num === "")}; + return this.numberyStrings.filter(checkPozitive); + } }, zeroStrings: function () { - // write me! + + return this.numberyStrings.filter(num => num == 0); + + // if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0) + // return this.numberyStrings; + // else if (this.NaNyStrings.length === 0 && this.numberyStrings.length !== 0){ + // function checkZero(num) {return (num == 0)} + // return this.numberyStrings.filter(checkZero); + // }else if (this.NaNyStrings.length !== 0 && this.numberyStrings.length !== 0){ + // function checkZero(num) {return (num == 0)} + // return this.numberyStrings.filter(checkZero); + // } }, numberyAsNumbers: function () { - // write me! + return this.numberyStrings.map(str => Number(str)); // in one line + + // in multiple lines + + /* if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0) + return this.numberyStrings; + else if (this.NaNyStrings.length === 0 && this.numberyStrings.length !== 0){ + function returnNumberyStrings(num) { return Number(num);} + return this.numberyStrings.map(returnNumberyStrings);} + else if (this.NaNyStrings.length !== 0 && this.numberyStrings.length !== 0){ + function returnNumberyStrings(num) { return Number(num);} + return this.numberyStrings.map(returnNumberyStrings);} */ }, NaNyAsNumbers: function () { - // write me! + return this.NaNyStrings.map( str => Number(str)); }, sumOfNumbery: function () { - // write me! (using a Array.prototype.reduce()) + if (this.NaNyStrings.length !== 0 && this.numberyStrings.length === 0 ) { + return 0; + } + function add(a, b) { return (a + b) }; + return this.numberyAsNumbers().reduce(add); }, + sumOfNaNy: function () { - // write me! + if (this.NaNyStrings.length === 0 && this.numberyStrings.length !== 0) { + return NaN; + } + function add(a, b) { return (a + b) }; + return this.NaNyAsNumbers().reduce(add); }, }; diff --git a/week-1-project/practice-problems/array-methods.js b/week-1-project/practice-problems/array-methods.js index a815910..7ddd536 100644 --- a/week-1-project/practice-problems/array-methods.js +++ b/week-1-project/practice-problems/array-methods.js @@ -20,7 +20,7 @@ try { { name: 'fourth', args: [['hello'], ['world']], expected: ['hello', 'world'] }, ]; function concatArrays(arr1, arr2) { - // write me! + return [...arr1, ...arr2]; } concatArrays.display = true; evaluate(concatArrays, concatArraysTests); @@ -35,12 +35,13 @@ try { { name: 'seventh', args: ['Infinity'], expected: false }, { name: 'eighth', args: ['infinity'], expected: true }, { name: 'ninth', args: ['NaN'], expected: true }, - { name: 'tenth', args: [NaN], expected: null }, - { name: 'eleventh', args: [true], expected: null }, - { name: 'twelfth', args: [undefined], expected: null }, - { name: 'thirteenth', args: [null], expected: null }, + { name: 'tenth', args: [NaN], expected: true }, + { name: 'eleventh', args: [true], expected: false }, + { name: 'twelfth', args: [undefined], expected: true }, + { name: 'thirteenth', args: [null], expected: false }, ]; function isNaNyString(arg) { + return isNaN(arg); // write me! // can you write this in one line? (isNaN will be helpful) } @@ -61,13 +62,15 @@ try { { name: 'first', args: [thingsToNumber1], expected: [1, 2] }, { name: 'second', args: [thingsToNumber2], expected: [1, 10] }, { name: 'third', args: [thingsToNumber3], expected: [2, 0] }, - { name: 'fourth', args: [thingsToNumber4], expected: null }, - { name: 'fifth', args: [[1, 2, 3]], expected: null }, + { name: 'fourth', args: [thingsToNumber4], expected: [1, 2] }, + { name: 'fifth', args: [[1, 2, 3]], expected: [1, 2, 3] }, { name: 'sixth', args: [oddsToNumber], expected: [1, 3, 5] }, { name: 'seventh', args: [evensToNumber], expected: [2, 4, 6] }, ]; function returnAsNumbers(arr) { // return an array of nonNanny strings cast to Number - // write me! + let nonNaNyString = arr.filter(item => !(isNaNyString(item))); + let numberArray = nonNaNyString.map(item => Number(item)); + return numberArray // early return condition: array contains no numbery strings // consider using a variation of your solution to isNaNyString (and .every) }; @@ -89,10 +92,9 @@ try { { name: 'seventh', args: [numbersToSum3], expected: 2 }, ]; function sumAll(arr) { - // write me! - // no early return, all the test cases are numbers! - // this solution will be very helpful for the next exercise - }; + function add(a, b) { return (a + b) }; + return arr.reduce(add); + }; sumAll.display = true; evaluate(sumAll, sumAllTests); @@ -109,22 +111,23 @@ try { { name: 'first', args: [sumNumberys1], expected: 3 }, { name: 'second', args: [sumNumberys2], expected: 11 }, { name: 'third', args: [sumNumberys3], expected: 2 }, - { name: 'fourth', args: [sumNumberys4], expected: null }, - { name: 'fifth', args: [[1, 2, 3]], expected: null }, + { name: 'fourth', args: [sumNumberys4], expected: 3 }, + { name: 'fifth', args: [[1, 2, 3]], expected: 6 }, { name: 'sixth', args: [['1', '2', '3']], expected: 6 }, { name: 'seventh', args: [oddsToSum], expected: 9 }, { name: 'eighth', args: [evensToSum], expected: 12 }, ]; function sumAllNumberys(arr) { - // write me! + let numberyArr = arr.filter(item => !isNaNyString(item)) + .map(item => Number(item)); + return sumAll(numberyArr); + // early return condition: array contains no numbery strings }; sumAllNumberys.display = true; evaluate(sumAllNumberys, sumAllNumberysTests); - - const findEvensArray1 = ['.', '1', '2', ':']; const findEvensArray2 = ['1', 'two', 'three', '10']; const findEvensArray3 = ['one', '2', '', 'NaN']; @@ -137,13 +140,15 @@ try { { name: 'first', args: [findEvensArray1], expected: ['2'] }, { name: 'second', args: [findEvensArray2], expected: ['10'] }, { name: 'third', args: [findEvensArray3], expected: ['2', ''] }, - { name: 'fourth', args: [findEvensArray4], expected: null }, - { name: 'fifth', args: [[1, 2, 3]], expected: null }, + { name: 'fourth', args: [findEvensArray4], expected: [2] }, + { name: 'fifth', args: [[1, 2, 3]], expected: [2] }, { name: 'sixth', args: [oddsToNotFind], expected: [] }, { name: 'seventh', args: [evensToFind], expected: ['2', '4', '6'] }, ]; function findAllEvens(arr) { - // write me! + let numberyArr = arr.filter(item => !isNaNyString(item)); + let evenArr = numberyArr.filter(item => item%2===0) + return evenArr; // early return condition: array contains no numbery strings }; findAllEvens.display = true; @@ -163,13 +168,15 @@ try { { name: 'first', args: [findOddsArray1], expected: ['1'] }, { name: 'second', args: [findOddsArray2], expected: ['1'] }, { name: 'third', args: [findOddsArray3], expected: [] }, - { name: 'fourth', args: [findOddsArray4], expected: null }, - { name: 'fifth', args: [[1, 2, 3]], expected: null }, + { name: 'fourth', args: [findOddsArray4], expected: [1] }, + { name: 'fifth', args: [[1, 2, 3]], expected: [1, 3] }, { name: 'sixth', args: [oddsToFind], expected: ['1', '3', '5'] }, { name: 'seventh', args: [evensToNotFind], expected: [] }, ]; function findAllOdds(arr) { - // write me! + let numberyArr = arr.filter(item => !isNaNyString(item)); + let oddArr = numberyArr.filter(item => item%2!==0) + return oddArr; // early return condition: array contains no numbery strings }; findAllOdds.display = true; diff --git a/week-1-project/practice-problems/arrays.js b/week-1-project/practice-problems/arrays.js index 9342ce9..9cf3e35 100644 --- a/week-1-project/practice-problems/arrays.js +++ b/week-1-project/practice-problems/arrays.js @@ -103,22 +103,23 @@ try { function passTheAssertions1() { - ; // declare and assign a1 - ; // declare and assign a2 + let a1 = 2; // declare and assign a1 + let a2 = a1; // declare and assign a2 console.assert(a1 === a2, 'a1 should strictly equal a2'); - ; // declare and assign b1 - ; // declare and assign b2 + let b1 = 3; // declare and assign b1 + let b2 = 4; // declare and assign b2 console.assert(b1 !== b2, 'b1 should not strictly equal b2'); // --- - ; // write one line to pass the assertions + a1 = a2 = ["hi!"]; // write one line to pass the assertions console.assert(a1[0] === a2[0], 'a1[0] should strictly equal a2[0]'); console.assert(a1[0] === 'hi!', 'a1.x should strictly equal "hi!"'); - ; // write two lines to pass the assertions - ; + b1 = ['bye!']; // write two lines to pass the assertions + b2 = b1 = ['bye!']; + console.assert(b1[0] === b2[0], 'b1[0] should strictly equal b2[0]'); console.assert(b1[0] === 'bye!', 'b1.x should strictly equal "bye!"'); } @@ -129,32 +130,32 @@ try { const value1 = 5; let reference1 = []; - ; // write this line + let value2 = value1; // write this line console.assert(value2 === value1, "value1 should strictly equal value2"); - ; // write this line + let reference2 = reference1; // write this line console.assert(reference2 === reference1, "reference1 should strictly equal reference2"); value2 = value2 + 1; // write this line - console.assert(value1 !== null, "value1 should strictly equal ___"); + console.assert(value1 !== value2, "value1 should strictly equal ___"); - ; // write this line + reference1 = reference2 = ['hi!']; // write this line console.assert(reference1[0] === reference2[0], "references[0] should be strictly equal"); console.assert(reference1[0] === 'hi!', "reference1[0] should be strictly equal to 'hi!'"); - ; // write this line + reference1 === reference2; // write this line console.assert(reference1 === reference2, "references should be strictly equal"); // remove the array from memory - ; // write this line - ; // write this line + reference1 = null; // write this line + reference2 = null; // write this line } evaluate(passTheAssertions2); function passTheAssertions3() { - ; // write this line - ; // write this line + arr1 = ['A', 'B']; // write this line + arr2 = ['A', 'B']; // write this line console.assert(arr1 !== arr2, 'the variables should not be strictly equal'); console.assert(arr1[1] === arr2[1], 'their first entries should be the same'); console.assert(arr1[1] === 'B', 'arr1[1]] should be "B"'); @@ -163,18 +164,18 @@ try { console.assert(arr1[index] === arr2[index], 'arr1[index] should strictly equal arr2[index]'); console.assert(arr1[index] === 'A', 'arr1[index] should be "A"'); - ; // write this line - ; // write this line + arr1 = ['A','B','1','2']; // write this line + arr2 = ['A','B','1']; // write this line console.assert(arr1[arr2[2]] === 'B', 'arr2[2] should be "B"s index in arr1'); console.assert(arr1[arr2[2]] === arr2[arr1[2]], 'some tricky nested thing should be true'); - ; // write this line + let arr3 = arr2 = ['A','B','1']; // write this line console.assert(arr1 !== arr2, 'arr1 should strictly equal arr2'); console.assert(arr3 !== arr1, 'arr3 should not strictly equal arr`'); console.assert(arr3 === arr2, 'arr3 should strictly equal arr2'); console.assert(arr3[index] === arr1[0], 'arr3[index] should strictly equal arr1[0]'); - ; // write this line + arr3 = ['A', 'B', 'A']; // write this line console.assert(arr3[2] === arr2[index], 'arr3[2] should strictly equal arr2[index]'); } evaluate(passTheAssertions3); diff --git a/week-1-project/practice-problems/avoiding-side-effects.js b/week-1-project/practice-problems/avoiding-side-effects.js index 823001d..a516042 100644 --- a/week-1-project/practice-problems/avoiding-side-effects.js +++ b/week-1-project/practice-problems/avoiding-side-effects.js @@ -152,7 +152,8 @@ try { { name: 'case 8', args: [mergingObject3, mergingObject2], expected: { x: 0, y: 2, a: 1 } }, ]; function mergeObjects(obj1, obj2) { - // write me! + const objCopy = Object.assign({}, obj2); + return Object.assign(objCopy, obj1); } mergeObjects.display = true; evaluate(mergeObjects, mergeObjsTests); @@ -169,7 +170,12 @@ try { { name: 'case 6', args: [['p', null], 0, null], expected: [null, null] }, ]; function replaceItem(arr, index, newItem) { - // write me! + let newArray = [...arr]; + newArray[index] = newItem; + return newArray; + // arr[index]=newItem; + // return arr; + } replaceItem.display = true; evaluate(replaceItem, replaceItemTests); @@ -188,7 +194,8 @@ try { { name: 'case 6', args: [combineArray2, [undefined]], expected: ['p', null, Infinity, undefined] }, ]; function combineArrays(arr1, arr2) { - // write me! + let newArray = [...arr1,...arr2]; + return newArray; } combineArrays.display = true; evaluate(combineArrays, combineArraysTests); @@ -206,7 +213,14 @@ try { { name: 'case 6', args: [['p', null], 2], expected: [['p', 'p'], [null, null]] }, ]; function repeatItems(items, numRepeats) { - // write me! + let result = items.map(e => { + const arr1 = [] + for (let i=0; i< numRepeats; i++){ + arr1.push(e); + } + return arr1; + }); + return result; } repeatItems.display = true; evaluate(repeatItems, repeatItemsTests); @@ -225,8 +239,9 @@ try { { name: 'fourth', args: [['hello'], ['world']], expected: ['world', 'hello'] }, ]; function concatArrays(arr1, arr2) { - // write me! - } + let newArray = arr2.concat(arr1); + return newArray; + } concatArrays.display = true; evaluate(concatArrays, concatArraysTests); @@ -244,8 +259,14 @@ try { { name: 'fifth', args: [arrayToMerge2, arrayToMerge1], expected: [2, 3, 4, 1] }, ]; function mergeArrays(arr1, arr2) { - // write me! - // consider filtering one of the arrs with .indexOf in the others + let filtered = [...arr2]; + for (let i = 0; i < filtered.length; i++) { + if (arr1.indexOf(filtered[i]) >= 0){ + filtered.splice(i,1); + i--; + } + } + return [...arr1,...filtered]; } mergeArrays.display = true; evaluate(mergeArrays, mergeArraysTests); diff --git a/week-1-project/practice-problems/early-return-pattern.js b/week-1-project/practice-problems/early-return-pattern.js index e83285b..bc9eae6 100644 --- a/week-1-project/practice-problems/early-return-pattern.js +++ b/week-1-project/practice-problems/early-return-pattern.js @@ -93,10 +93,10 @@ try { { name: 'fifth', args: [2, 3], expected: 'hi!' }, ]; function earlyReturn1(a, b) { - if (null) return 'string'; // replace null with your logic! + if (typeof a === 'string') return 'string'; // replace null with your logic! console.assert(typeof a !== 'string', 'if a is a string, this assert should not be reached'); - if (null) return 'boolean'; // replace null with your logic! + if (typeof b === 'boolean') return 'boolean'; // replace null with your logic! console.assert(typeof b !== 'boolean', 'if b is a boolean, this assert should not be reached'); return 'hi!'; @@ -114,15 +114,12 @@ try { { name: 'sixth', args: [], expected: 'param must be an array' }, ]; function earlyReturn2(param) { - if (null) return 'param must be an array'; // replace null with your logic! - + if (!(param instanceof Array)) return 'param must be an array'; // replace null with your logic! return param.reduce((acc, item) => acc + item); } earlyReturn2.display = true; evaluate(earlyReturn2, earlyReturn2Tests); - - const earlyReturn3Tests = [ { name: 'first', args: [4, '4'], expected: 'a is not a string' }, { name: 'second', args: ['4', 4], expected: 'b is not a string' }, @@ -132,9 +129,9 @@ try { { name: 'sixth', args: ['by', 'e!'], expected: 'bye!' }, ]; function earlyReturn3(a, b) { - if (null) return 'a & b are not strings'; // replace null with your logic! - if (null) return 'a is not a string'; // replace null with your logic! - if (null) return 'b is not a string'; // replace null with your logic! + if (typeof a !== 'string' && typeof b !== 'string') return 'a & b are not strings'; // replace null with your logic! + if (typeof a !== 'string') return 'a is not a string'; // replace null with your logic! + if (typeof b !== 'string') return 'b is not a string'; // replace null with your logic! console.assert(typeof a === 'string', 'a should be a string'); console.assert(typeof b === 'string', 'b should be a string'); @@ -156,8 +153,8 @@ try { { name: 'seventh', args: [() => { }], expected: 'argForFunc must be a boolean' }, ]; function earlyReturn4(func, argForFunc) { - if (null) return 'func must be a function'; // replace null with your logic! - if (null) return 'argForFunc must be a boolean'; // replace null with your logic! + if (typeof func !== 'function') return 'func must be a function'; // replace null with your logic! + if (typeof argForFunc !== 'boolean') return 'argForFunc must be a boolean'; // replace null with your logic! console.assert(typeof func === 'function', 'func should be a function'); console.assert(typeof argForFunc === 'boolean', 'argForFunc should be a boolean'); diff --git a/week-1-project/practice-problems/explicit-coercion.js b/week-1-project/practice-problems/explicit-coercion.js index 3beed6b..761a9a0 100644 --- a/week-1-project/practice-problems/explicit-coercion.js +++ b/week-1-project/practice-problems/explicit-coercion.js @@ -23,12 +23,12 @@ try { // fix the test cases' expected values to pass the function const StringTests = [ // string values remain unchanged - { name: 'str, any string', args: ['any string'], expected: null }, + { name: 'str, any string', args: ['any string'], expected: 'any string' }, // casting with String just puts quotes around a thing - { name: 'num, 3', args: [3], expected: null }, - { name: 'boo, true', args: [true], expected: null }, - { name: 'obj, null', args: [null], expected: null }, - { name: 'und, undefined', args: [undefined], expected: null }, + { name: 'num, 3', args: [3], expected: '3' }, + { name: 'boo, true', args: [true], expected: 'true' }, + { name: 'obj, null', args: [null], expected: 'null' }, + { name: 'und, undefined', args: [undefined], expected: 'undefined' }, // write at least 5 more test cases for the String function ]; String.quizzing = true; @@ -45,11 +45,11 @@ try { { name: 'num, Infinity', args: [Infinity], expected: Infinity }, { name: 'num, NaN', args: [NaN], expected: NaN }, // true and false, the only boolean values - { name: 'boo, true', args: [true], expected: 0 }, - { name: 'boo, false', args: [false], expected: 1 }, + { name: 'boo, true', args: [true], expected: 1 }, + { name: 'boo, false', args: [false], expected: 0 }, // null & undefined - { name: 'obj, null', args: [null], expected: NaN }, - { name: 'und, undefined', args: [undefined], expected: 0 }, + { name: 'obj, null', args: [null], expected: 0 }, + { name: 'und, undefined', args: [undefined], expected: NaN }, // strings are bit more interesting, write 4 more test cases with string args { name: 'str, undefined', args: ['undefined'], expected: NaN }, { name: 'str, Infinity', args: ['Infinity'], expected: Infinity }, @@ -68,19 +68,19 @@ try { { name: 'boo, false', args: [false], expected: false }, // anything but 0 & NaN is cast to true { name: 'num, 3', args: [3], expected: true }, - { name: 'num, 0', args: [0], expected: true }, + { name: 'num, 0', args: [0], expected: false }, { name: 'num, 1e3', args: [1000], expected: true }, - { name: 'num, Infinity', args: [Infinity], expected: false }, + { name: 'num, Infinity', args: [Infinity], expected: true }, { name: 'num, NaN', args: [NaN], expected: false }, // null & undefined - { name: 'obj, null', args: [null], expected: true }, - { name: 'und, undefined', args: [undefined], expected: true }, + { name: 'obj, null', args: [null], expected: false }, + { name: 'und, undefined', args: [undefined], expected: false }, // anything but an empty string is cast to true - { name: 'str, undefined', args: ['undefined'], expected: false }, - { name: 'str, false', args: ['false'], expected: false }, + { name: 'str, undefined', args: ['undefined'], expected: true }, + { name: 'str, false', args: ['false'], expected: true }, { name: 'str, Infinity', args: ['Infinity'], expected: true }, { name: 'str, three', args: ['three'], expected: true }, - { name: 'str, ', args: [''], expected: true }, + { name: 'str, ', args: [''], expected: false }, { name: 'str, 3', args: ['3'], expected: true }, ]; Boolean.quizzing = true; diff --git a/week-1-project/practice-problems/functions-to-objects.js b/week-1-project/practice-problems/functions-to-objects.js index 6677dac..3fb4b62 100644 --- a/week-1-project/practice-problems/functions-to-objects.js +++ b/week-1-project/practice-problems/functions-to-objects.js @@ -83,10 +83,10 @@ try { // methods can "return" values to their objects obj.a = 3, obj.b = 4; - obj.sum(); + obj.sum(3,4); console.assert(7 === obj.result, 'obj.result should be 7'); - obj.a = 5; - obj.sum(); + obj.a = 5; obj.b = 4; + obj.sum(5,4); console.assert(9 === obj.result, 'obj.result should be 9'); } @@ -111,13 +111,13 @@ try { this.a = a; this.b = b; }, - sumAandB: function () { + sumAandB: function (a, b) { return this.a + this.b; } }; obj.setAandB(3, 4); - const result2 = obj.sumAandB(); + const result2 = obj.sumAandB(3, 4); } evaluate(example_twoMethods); @@ -132,7 +132,10 @@ try { const obj = { array: [3], - mergeArrays: function (arrToMerge) { } + mergeArrays: function (arrToMerge) { + // return [...this.array, ...arrToMerge]; + return this.array.concat(arrToMerge); + } } @@ -166,7 +169,9 @@ try { const obj = { array: [3], - mergeArrays: function (arrToMerge) { } + mergeArrays: function (arrToMerge) { + return this.array = [...this.array, ...arrToMerge]; + } } obj.mergeArrays([2]); @@ -192,7 +197,9 @@ try { const obj = { mixer: '', - remix: function (str) { } + remix: function (str) { + return str.split('').join(this.mixer); + } }; console.assert(obj.remix('hello') === 'hello', 'assert 1'); @@ -216,8 +223,10 @@ try { const obj = { mixer: '', remixed: '', - remix: function (str) { }, - getRemixed: function () { } + remix: function (str) { + this.remixed = str.split('').join(this.mixer); + }, + getRemixed: function () {return this.remixed} }; obj.remix('hello'); diff --git a/week-1-project/practice-problems/primitive-types.js b/week-1-project/practice-problems/primitive-types.js index 360d7a0..05c2947 100644 --- a/week-1-project/practice-problems/primitive-types.js +++ b/week-1-project/practice-problems/primitive-types.js @@ -59,27 +59,27 @@ try { // the type of a value is very important to understanding how JS works const typeofTests = [ // boolean values - { name: 'boo, true', args: [true], expected: '' }, - { name: 'boo, false', args: [false], expected: '' }, - // null's type is 'null'. just remember, don't try yet to understand - { name: 'obj, true', args: [null], expected: '' }, + { name: 'boo, true', args: [true], expected: 'boolean' }, + { name: 'boo, false', args: [false], expected: 'boolean' }, + // null's type is 'object'. just remember, don't try yet to understand + { name: 'obj, true', args: [null], expected: 'object' }, // undefined. like with null, there is only one value with this type - { name: 'und, undefined', args: [undefined], expected: '' }, + { name: 'und, undefined', args: [undefined], expected: 'undefined' }, // strings are anything with quotes around it - { name: 'str, ', args: [''], expected: '' }, - { name: 'str, anything with quotes!', args: ['anything with quotes!'], expected: '' }, + { name: 'str, ', args: [''], expected: 'string' }, + { name: 'str, anything with quotes!', args: ['anything with quotes!'], expected: 'string' }, // numbers are a bit more strange and varied { name: 'num, 0.0', args: [0.0], expected: 'number' }, { name: 'num, NaN', args: [NaN], expected: 'number' }, { name: 'num, Infinity', args: [Infinity], expected: 'number' }, { name: 'num, 4', args: [4], expected: 'number' }, // write 6 more passing test cases with expected value 'number' - { name: '', args: null, expected: null }, - { name: '', args: null, expected: null }, - { name: '', args: null, expected: null }, - { name: '', args: null, expected: null }, - { name: '', args: null, expected: null }, - { name: '', args: null, expected: null }, + { name: 'str, 4', args: ['4'], expected: 'string' }, + { name: 'boo, true', args: [true], expected: 'boolean' }, + { name: 'obj, arr', args: ['[arr'], expected: 'string' }, + { name: 'str, hello!', args: ['hello!'], expected: 'string' }, + { name: 'num', args: [NaN], expected: 'number' }, + { name: 'num', args: [Infinity], expected: 'number' }, ] function allValuesHaveAType(value) { return typeof value; @@ -99,7 +99,7 @@ try { ]; function typeofReturnsAString(value) { const typeofValue = typeof value; - return typeof typeofValue; + return typeofValue; } typeofReturnsAString.quizzing = true; evaluate(typeofReturnsAString, typeofReturnsAStringTests); @@ -125,16 +125,16 @@ try { // fix the expected values to pass the tests const strictEqualityTests = [ - { name: 'NaN', args: [NaN, NaN], expected: null }, - { name: 'first', args: [true, 'true'], expected: null }, - { name: 'second', args: [1, '1'], expected: null }, - { name: 'third', args: ['1', '1'], expected: null }, - { name: 'fourth', args: [1000, 1e3], expected: null }, - { name: 'fifth', args: [+0, -0], expected: null }, - { name: 'sixth', args: [1, 1.0], expected: null }, - { name: 'seventh', args: ['', ""], expected: null }, - { name: 'eighth', args: ["", ``], expected: null }, - { name: 'ninth', args: [' ', ' '], expected: null }, + { name: 'NaN', args: [NaN, NaN], expected: false }, + { name: 'first', args: [true, 'true'], expected: false }, + { name: 'second', args: [1, '1'], expected: false }, + { name: 'third', args: ['1', '1'], expected: true }, + { name: 'fourth', args: [1000, 1e3], expected: true }, + { name: 'fifth', args: [+0, -0], expected: true }, + { name: 'sixth', args: [1, 1.0], expected: true }, + { name: 'seventh', args: ['', ""], expected: true }, + { name: 'eighth', args: ["", ``], expected: true }, + { name: 'ninth', args: [' ', ' '], expected: false }, ]; function strictEquality(a, b) { // if type OR value are not the same, returns false @@ -147,16 +147,16 @@ try { const strictInequalityTests = [ - { name: 'NaN', args: [NaN, NaN], expected: null }, - { name: 'first', args: [true, 'true'], expected: null }, - { name: 'second', args: [1, '1'], expected: null }, - { name: 'third', args: ['1', '1'], expected: null }, - { name: 'fourth', args: [1000, 1e3], expected: null }, - { name: 'fifth', args: [+0, -0], expected: null }, - { name: 'sixth', args: [1, 1.0], expected: null }, - { name: 'seventh', args: ['', ""], expected: null }, - { name: 'eighth', args: ["", ``], expected: null }, - { name: 'ninth', args: [' ', ' '], expected: null }, + { name: 'NaN', args: [NaN, NaN], expected: true }, + { name: 'first', args: [true, 'true'], expected: true }, + { name: 'second', args: [1, '1'], expected: true }, + { name: 'third', args: ['1', '1'], expected: false }, + { name: 'fourth', args: [1000, 1e3], expected: false }, + { name: 'fifth', args: [+0, -0], expected: false }, + { name: 'sixth', args: [1, 1.0], expected: false }, + { name: 'seventh', args: ['', ""], expected: false }, + { name: 'eighth', args: ["", ``], expected: false }, + { name: 'ninth', args: [' ', ' '], expected: true }, ]; function strictInequality(a, b) { // if type OR value are not the same, returns true diff --git a/week-2-project/README.md b/week-2-project/README.md index abad0a2..fa57be2 100644 --- a/week-2-project/README.md +++ b/week-2-project/README.md @@ -1,8 +1,10 @@ +## Week2 Practice Problems Link + ### Please follow the link below to open the practice problems of Week2 +Practice Problems Week2

## Week 2 Project - The weekly projects in JS 2 will be making an even stronger distinction between your core application and the user interface. To help you with this transition there will be two assignment tables, one for the core app object and another for the user interface. diff --git a/week-2-project/app.js b/week-2-project/app.js index 90e883b..e7659c2 100644 --- a/week-2-project/app.js +++ b/week-2-project/app.js @@ -13,74 +13,108 @@ const object = { entries: {}, + isPrimitive: function (value) { - // write me! + if (Object(value) !== value) {return true}; + return false; }, hasKey: function (obj, key) { - // write me! - }, + return (obj.hasOwnProperty(key)); // SINGLE LINE SOLUTION + + // AlTERNATIVE SOLUTION // + // let keyList = Object.keys(obj); + // if(keyList.length >= 0){ + // if(keyList.includes(key)){return true} + // else {return false} + // } + }, hasValue: function (obj, value) { - // write me! + if(Object.values(obj).includes(value)) {return true}; + return false; + // AlTERNATIVE SOLUTION-1 // + // return (Object.values(obj).indexOf(value) > -1); + + // AlTERNATIVE SOLUTION-2 // + // let valueList = Object.values(obj); + // if(valueList.length >= 0){ + // if(valueList.includes(value)){return true} + // else {return false} + }, addEntry: function (key, value) { - if (null) { // write me! + if (typeof key !== 'string') { // write me! return new TypeError('addEntry: key should be a string'); } - if (null) { // write me! (using this.isPrimitive) + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) return new TypeError('addEntry: value should be a primitive'); } - if (null) { // write me! (using this.hasKey) - return new Error(`addEntry: key "${key}" already exists`); - } - // write me! - }, + if (this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + return new Error(`addEntry: key "${key}" already exists`); + } else {this.entries[key] = value; + return true;} + }, removeEntry: function (key) { - if (null) { // write me! + + if (typeof key !== 'string') { // write me! return new TypeError('removeEntry: key should be a string'); } - if (null) { // write me! (using this.hasKey) + if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) return new ReferenceError(`removeEntry: no property "${key}" in this.entries`); } - - delete this.entries[key] - return true - // write me! + delete this.entries[key]; + return true; }, + updateEntry: function (key, value) { - if (null) { // write me! + if (typeof key !== 'string') { // write me! return new TypeError('updateEntry: key should be a string'); } - if (null) { // write me! (using this.isPrimitive) + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) return new TypeError('updateEntry: value should be a primitive'); } - if (null) { // write me! (using this.hasKey) + if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) return new ReferenceError(`updateEntry: no property "${key}" in this.entries`); - } - - // write me! + } else {this.entries[key] = value; + return true;} }, readAll: function () { - // write me! + let clonedObj = {...this.entries}; + return clonedObj; }, findByKey: function (key) { - if (null) { // write me! + if (typeof key !== 'string') { // write me! return new TypeError('findByKey: key should be a string'); } - if (null) { // write me! (using this.hasKey) + if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + console.log('haskey'); return new ReferenceError(`findByKey: no property "${key}" in this.entries`); } + const newObj = {}; + newObj[key] = this.entries[key]; + return newObj; + }, - // write me! +copyEntries: function() { + let copied = {...this.entries}; + return copied; }, - findByValue: function (value) { - if (null) { // write me! (using this.isPrimitive) - return new TypeError('findByValue: value should be a primitive'); + +findByValue: function (value) { + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) + return new TypeError('findByValue: value should be a primitive'); + } + if (!this.hasValue(this.entries, value)) { // write me! (using this.hasValue) + return new ReferenceError(`findByValue: no entry with value (${typeof value}, ${value})`); } - if (null) { // write me! (using this.hasValue) - return new ReferenceError(`findByValue: no entry with value (${typeof value}, ${value})`); + let copiedEntries = this.copyEntries(); + let requestedObj={}; + let newKey = Object.keys(copiedEntries).filter(keyOfValue => copiedEntries[keyOfValue] === value); + for (let i = 0; i < newKey.length; i++) { + if (this.entries[newKey[i]] === value) { + requestedObj[newKey[i]] = value; } - - // write me! (this one is a bit trickier) - }, -} + } + return requestedObj; +}, +}; diff --git a/week-2-project/practice-problems/index.html b/week-2-project/practice-problems/index.html index 48a7c5f..33d2f32 100644 --- a/week-2-project/practice-problems/index.html +++ b/week-2-project/practice-problems/index.html @@ -34,4 +34,4 @@ - + \ No newline at end of file diff --git a/week-2-project/practice-problems/objects.js b/week-2-project/practice-problems/objects.js index be4dbb3..87c331a 100644 --- a/week-2-project/practice-problems/objects.js +++ b/week-2-project/practice-problems/objects.js @@ -130,19 +130,22 @@ try { console.assert(a1.x === 'hi!', 'a1.x should strictly equal "hi!"'); b1.x = 'bye!'; // write two lines to pass the assertions - b2.x = 'bye!'; + b2.x = b1.x; console.assert(b1.x === b2.x, 'b1.x should strictly equal b2.x'); console.assert(b1.x === 'bye!', 'b1.x should strictly equal "bye!"'); // -- - const index = 'y'; - - ; // write one line to pass the assertions + const index = 'y'; if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + return new ReferenceError(`removeEntry: no property "${key}" in this.entries`); + } + delete this.entries[key]; + return true; + a1[index] = 'roof!'; // write one line to pass the assertions console.assert(a1[index] === a2[index], 'a1[index] should strictly equal a2[index]'); console.assert(a1[index] === 'roof!', 'a1[index] should strictly equal "roof!"'); - ; // write two lines to pass the assertions - ; + b1[index]='floor!'; // write two lines to pass the assertions + b2[index]=b1[index]; console.assert(b1[index] === b2[index], 'b1[index] should strictly equal b2[index]'); console.assert(b1[index] === 'floor!', 'b1[index] should strictly equal "floor!"'); @@ -155,53 +158,56 @@ try { const value1 = 5; let reference1 = {}; - ; // write this line + let value2=value1; // write this line console.assert(value2 === value1, "value1 should strictly equal value2"); - ; // write this line + let reference2=reference1; // write this line console.assert(reference2 === reference1, "reference1 should strictly equal reference2"); value2 = value2 + 1; // write this line - console.assert(value1 !== null, "value1 should strictly equal ___"); + console.assert(value1 !== null, "value1 should strictly equal 5"); - ; // write this line + reference1.x = reference2.x = 'hi!'; // write this line console.assert(reference1.x === reference2.x, "references.x should be strictly equal"); console.assert(reference1.x === 'hi!', "references.x should strictly equal 'hi!'"); - ; // write this line + reference1=reference2; // write this line console.assert(reference1 === reference2, "references should be strictly equal"); // remove the object from memory - ; // write this line - ; // write this line + reference1=null; // write this line + reference2=null; // write this line } evaluate(passTheAssertions2); function passTheAssertions3() { - ; // write this line - ; // write this line + let obj1 ={}; + let obj2 ={}; + obj1.y = obj2.y = 'B'; // write this line + obj1.x = obj2.x = 'A'; // write this line console.assert(obj1 !== obj2, 'the variables should not be strictly equal'); console.assert(obj1.y === obj2.y, 'their first entries should be the same'); console.assert(obj1.y === 'B', 'obj1.y should be "B"'); - const index = 'x'; + let index = 'x'; console.assert(obj1[index] === obj2[index], 'obj1[index] should strictly equal obj2[index]'); console.assert(obj1[index] === 'A', 'obj1[index] should be "A"'); - ; // write this line - ; // write this line + obj2.z = obj1.z = 'y'; // write this line + obj1[obj2.z] === obj2[obj1.z]; // write this line console.assert(obj1[obj2.z] === 'B', 'obj2.z should be "B"s index in obj1'); console.assert(obj1[obj2.z] === obj2[obj1.z], 'some tricky nested thing should be true'); - ; // write this line + let obj3 = obj2; // write this line console.assert(obj1 !== obj2, 'obj1 should strictly equal obj2'); console.assert(obj3 !== obj1, 'obj3 should not strictly equal obj`'); console.assert(obj3 === obj2, 'obj3 should strictly equal obj2'); console.assert(obj3[index] === obj1.x, 'obj3[index] should strictly equal obj1.x'); - ; // write this line + index = 'z'; + obj3.z === obj2[index]; // write this line console.assert(obj3.z === obj2[index], 'obj3.z should strictly equal obj2[index]'); } evaluate(passTheAssertions3); @@ -216,8 +222,7 @@ try { const objValues = Object.values(obj); } - evaluate(footnote_objectDotKeysAndValues); - + evaluate(footnote_objectDotKeysAndValue, err); } catch (err) { console.log(err); document.body.appendChild( @@ -227,4 +232,4 @@ try { { console.groupEnd(); document.body.appendChild(document.createElement('hr')); -} +} \ No newline at end of file diff --git a/week-2-project/practice-problems/project-prep.js b/week-2-project/practice-problems/project-prep.js index 936b72e..9638f92 100644 --- a/week-2-project/practice-problems/project-prep.js +++ b/week-2-project/practice-problems/project-prep.js @@ -21,7 +21,8 @@ try { { name: 'tenth', args: [new WeakMap()], expected: false }, ]; function isPrimitive(thing) { - // write me! + if (Object(thing) !== thing) {return true}; + return false; } isPrimitive.display = true; evaluate(isPrimitive, isPrimitiveTests); @@ -37,8 +38,16 @@ try { { name: 'eighth', args: [{ b: undefined }, 'b'], expected: true }, ]; function hasKey(obj, key) { - // write me! - } + return (obj.hasOwnProperty(key)); + + // if(Object.keys(obj).includes(key)) { + // const newObj = {}; + // newObj[key] = obj[key]; + // return newObj; + // } + }; + + hasKey.display = true; evaluate(hasKey, hasKeyTests); @@ -53,7 +62,7 @@ try { { name: 'seventh', args: [{ a: false, b: false }, true], expected: false }, ]; function hasValue(obj, value) { - // write me! + return (Object.values(obj).indexOf(value) > -1); // consider using Object.keys, .filter and obj.hasOwnProperty } hasValue.display = true; @@ -71,7 +80,9 @@ try { { name: 'fifth', args: [{}, 'b', 'hi!'], expected: { b: 'hi!' } }, ]; function modifyToObjectWithBrackets(obj, key, value) { - // write me! + let newObj={...obj}; + newObj[key] = value; + return newObj; // (remember to avoid side effects) } modifyToObjectWithBrackets.display = true; @@ -85,8 +96,12 @@ try { { name: 'fifth', args: [secondObj, 'b'], expected: { a: 0 } }, { name: 'fifth', args: [{ b: 'hi!' }, 'b'], expected: {} }, ]; + function deleteFromObject(obj, key) { - // write me! + + let newObj={...obj}; + delete newObj[key]; + return newObj; // (remember to avoid side effects) } deleteFromObject.display = true; @@ -102,7 +117,12 @@ try { { name: 'fifth', args: [{ b: 'hi!' }, 'b'], expected: { b: 'hi!' } }, ]; function findByKey(obj, key) { - // write me! + const newObj2 = {}; + if (!obj.hasOwnProperty(key)){ + return newObj2; + } + newObj2[key] = obj[key]; + return newObj2; // (remember to avoid side effects) } findByKey.display = true; @@ -118,12 +138,25 @@ try { { name: 'fifth', args: [{ b: 'hi!', c: 'hi!' }, 'hi!'], expected: { b: 'hi!', c: 'hi!' } }, ]; function findByValue(obj, value) { - // write me! + let objNew = {}; + const obje3 = {...obj}; + let key = Object.keys(obje3).filter(key => obje3[key] === value); + if(key.length===0){ + return {}; + }else if (key.length===1){ + objNew[key]=value; + return objNew; + }else if (key.length>1){ + for (let i=0 ; i < key.length; i++) { + objNew[key[i]]=value; + } + return objNew; // (remember to avoid side effects) } +} findByValue.display = true; evaluate(findByValue, findByValueTests) - + } catch (err) { console.log(err); document.body.appendChild( diff --git a/week-2-project/practice-problems/using-objects.js b/week-2-project/practice-problems/using-objects.js index 9f29459..056c65c 100644 --- a/week-2-project/practice-problems/using-objects.js +++ b/week-2-project/practice-problems/using-objects.js @@ -12,8 +12,8 @@ try { const obj = { a: 0, - getA: function () { }, - sumAB: function (b) { }, + getA: function () { return this.a}, + sumAB: function (b) { return this.a + b }, }; console.assert(obj.getA() === 0, '1: obj.getA() should return 0'); @@ -36,8 +36,12 @@ try { const obj = { word: '', - getWord: function () { }, - concat: function (secondHalf) { }, + getWord: function () { + if (typeof this.word === 'string'){ + return "the word is " + this.word + } else return this.word; + }, + concat: function (secondHalf) { return this.word.concat(secondHalf) }, }; console.assert(obj.getWord() === 'the word is ', `1: obj.getWord() should return 'the word is '`); @@ -59,8 +63,12 @@ try { const obj = { array: ['hi!'], - getArray: function () { }, - getCopy: function () { }, + copyArray:[], + + getArray: function () { return this.array }, + getCopy: function () { + this.copyArray = [...this.array]; + return this.copyArray }, }; const gottenArray1 = obj.getArray(); @@ -94,8 +102,8 @@ try { const obj = { string: '', - setString: function (str) { }, - remixString: function (mixer) { } + setString: function (str) { this.string = str}, + remixString: function (mixer) { this.string = this.string.split('').join(mixer) } } obj.setString('hoy'); @@ -129,8 +137,13 @@ try { number: 5, mod: 0, equals: 0, - setNumber: function (num) { }, - modulo: function (modder) { } + setNumber: function (num) { + this.number = num; + return this.number; }, + modulo: function (modder) { + this.mod=modder; + this.equals = this.number%modder; + return this.equals; } }; obj.modulo(2); @@ -162,8 +175,13 @@ try { const obj = { arr: [1, 0], - merge: function (toMerge) { }, - replace: function (newArr) { }, + merge: function (toMerge) { + this.arr = toMerge.concat(this.arr); + return this.arr; + }, + replace: function (newArr) { + return this.arr=newArr; + }, }; obj.merge([4]); @@ -196,10 +214,28 @@ try { const obj = { arr: [], - merge: function (toMerge) { }, - replaceAll: function (newEntry) { }, - getRemixed: function (mixer) { }, - getCopy: function () { } + merge: function (toMerge) { + this.arr.unshift(...toMerge) + // this.arr = this.arr.concat(toMerge); + // return this.arr; + }, + replaceAll: function (newEntry) { + // this.arr = this.arr.map(x=>newEntry); + this.arr = this.arr.fill(newEntry); + // for (let i=0 ; i < this.arr.length ; i++){ + // this.arr[i]=newEntry; + // } + // return this.arr; + }, + getRemixed: function (mixer) { + return [...this.arr].join(mixer); + // let mixedArr=this.arr.join(mixer); + // this.arr.unshift(mixedArr); + // return this.arr; + }, + getCopy: function () { + return [...this.arr]; + } }; obj.merge([1, 2]); diff --git a/week-2-project/tests/find-by-value.js b/week-2-project/tests/find-by-value.js index 457a7af..6f346c8 100644 --- a/week-2-project/tests/find-by-value.js +++ b/week-2-project/tests/find-by-value.js @@ -59,4 +59,4 @@ describe(`findByValue: returns the requested key/value pair, or an informative e }); }); }); -}); +}); \ No newline at end of file diff --git a/week-2-project/tests/has-key.js b/week-2-project/tests/has-key.js index 62184f1..31bb935 100644 --- a/week-2-project/tests/has-key.js +++ b/week-2-project/tests/has-key.js @@ -1,39 +1,77 @@ + + describe(`hasKey: determines if an object has a given key`, () => { + before(() => { + object.entries = {}; + [ + ['firstKey', 'firstValue'], + ['secondKey', 'secondValue'], + ['thirdKey', 'thirdValue'], + ['fourthKey', 'fourthValue'] + ].forEach(newEntry => object.entries[newEntry[0]] = newEntry[1]); + }); + describe(`it is a pure function that works with any arguments`, () => { + it('{a:3} has "a"', () => { + const result = object.hasKey({ a: 3 }, "a"); + assert.strictEqual(result, true); + }); + it('{a:3} does not have "b"', () => { + const result = object.hasKey({ a: 3 }, "b"); + assert.strictEqual(result, false); + }); + it('{x:4} has "x"', () => { + const result = object.hasKey({ x: 4 }, "x"); + assert.strictEqual(result, true); + }); + it('{x:4} does not have "y"', () => { + const result = object.hasKey({ x: 4 }, "y"); + assert.strictEqual(result, false); + }); + }); + describe(`it returns true for existant entries`, () => { + ['firstKey', 'secondKey', 'thirdKey', 'fourthKey'].forEach(arg => { + it(arg, () => { + const result = object.hasKey(object.entries, arg); + assert.strictEqual(result, true); + }); + }); + }); + describe(`and returns false for non-existant entries.`, () => { ['entries', 'hasKey', 'toSource', 'valueOf', 'hasOwnProperty', ''].forEach(arg => { it(arg, () => { @@ -48,9 +86,40 @@ describe(`hasKey: determines if an object has a given key`, () => { }); ['entries', 'hasKey', 'toSource', 'valueOf', 'hasOwnProperty', ''].forEach(arg => { it(arg, () => { + const result = object.hasKey(object.entries, arg); + + console.log(result) + assert.strictEqual(result, false); + }); + }); + }); + + describe(`or when there are no entries!`, () => { + + before(() => { + + object.entries = {}; + + }); + + ['entries', 'hasKey', 'toSource', 'valueOf', 'hasOwnProperty', ''].forEach(arg => { + + it(arg, () => { + + const result = object.hasKey(object.entries, arg); + + assert.strictEqual(result, false); + + }); + + }); + + }); + }); + diff --git a/week-2-project/user-interface/handlers/call-it.js b/week-2-project/user-interface/handlers/call-it.js index 76cec49..93f88f5 100644 --- a/week-2-project/user-interface/handlers/call-it.js +++ b/week-2-project/user-interface/handlers/call-it.js @@ -1,4 +1,5 @@ function callItHandler() { + // read user input // notice this: the UI doesn't allow you to enter invalid types! @@ -54,8 +55,9 @@ function callItHandler() { console.log('methodName:', typeof methodName, ',', methodName); console.log('args:', typeof args, ',', args); console.log('result:', typeof result, ',', result); - } + + const callItButton = document.getElementById('call-it'); callItButton.addEventListener('click', callItHandler); // connect this to it's button with an event listener! <---------- diff --git a/week-2-project/user-interface/index.html b/week-2-project/user-interface/index.html index a27de33..ef15e80 100644 --- a/week-2-project/user-interface/index.html +++ b/week-2-project/user-interface/index.html @@ -1,69 +1,63 @@ - - - - week 2 project UI - - - - - - - - - - - - - -
-
- key
- -
-
- value
- - -
-
-
-
-
- Which method do you want to call? - - - -
-
-
-
-

Entries

-
-
- - - -
-
- - - back to index - - - - + + + week 2 project UI + + + + + + + + + + + +
+
+ key
+ +
+
+ value
+ + +
+
+
+
+
+ Which method do you want to call? + + + +
+
+
+
+

Entries

+
+
+ +
+
+ + + back to index + + + diff --git a/week-3-project/README.md b/week-3-project/README.md index 6850231..49714fa 100644 --- a/week-3-project/README.md +++ b/week-3-project/README.md @@ -1,3 +1,6 @@ +## Week3 Practice Problems Link + ### Please follow the link below to open the practice problems of Week3 +Practice Problems Week3

## Week 3 Project diff --git a/week-3-project/app.js b/week-3-project/app.js index b4fe84f..b87d0f0 100644 --- a/week-3-project/app.js +++ b/week-3-project/app.js @@ -1,73 +1,143 @@ const object = { currentKey: '', set currentEntry(key) { - if (null) { // write the early return condition + if (typeof key !== 'string') { // write the early return condition throw new TypeError('set currentEntry: key should be a string'); } - if (null) { // write the early return condition + if (!this.entries.hasOwnProperty(key)) { // write the early return condition throw new ReferenceError(`set currentEntry: no entry with key "${key}"`); } - - // write me! + this.currentKey = key; }, get currentEntry() { - // write me! + const entry = this.findByKey(this.currentKey); + if (entry instanceof Error) { + return {[this.currentKey]:entry} + } else { + return entry; + } }, likedKeys: [], get likedEntries() { - - // write me! + let likedObject = {}; + for (let i=0 ; i < this.likedKeys.length ; i++){ + let likedEntry = this.findByKey(this.likedKeys[i]); + if (likedEntry instanceof Error) { + likedObject[this.likedKeys[i]] = likedEntry + } else { + likedObject[this.likedKeys[i]] = this.entries[this.likedKeys[i]]; + } + } + return likedObject; }, likeEntry: function (key) { - if (null) { // write the early return condition + // debugger; + if (typeof key !== 'string') { // write the early return condition return new TypeError('likeEntry: key should be a string'); } - if (null) { // write the early return condition + if (!this.entries.hasOwnProperty(key)) { // write the early return condition return new ReferenceError(`likeEntry: key "${key}" has been removed`); } - if (null) { // write the early return condition + if (this.likedKeys.includes(key)) { // write the early return condition return new Error(`likeEntry: key "${key}" is already liked`); } - - // write me! + this.likedKeys.push(key); + if (this.addEntry()){ + return true; + } }, unlikeEntry: function (key) { - if (null) { // write the early return condition + if (typeof key !== 'string') { // write the early return condition return new TypeError('unlikeEntry: key should be a string'); } - if (null) { // write the early return condition + if (!this.likedKeys.includes(key)) { // write the early return condition return new Error(`unlikeEntry: key "${key}" is not in this.likedKeys`); } - - // write me! + this.likedKeys.unshift(key); + return true; }, entries: {}, isPrimitive: function (value) { - // write me! - }, - hasKey: function (obj, key) { - // write me! + if (Object(value) !== value) {return true}; + return false; }, + hasKey: function (obj, key){ + return (obj.hasOwnProperty(key));// write me! + }, hasValue: function (obj, value) { - // write me! + if(Object.values(obj).includes(value)) {return true}; + return false; }, addEntry: function (key, value) { - // write me! + if (typeof key !== 'string') { // write me! + return new TypeError('addEntry: key should be a string'); + } + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) + return new TypeError('addEntry: value should be a primitive'); + } + if (this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + return new Error(`addEntry: key "${key}" already exists`); + } else {this.entries[key] = value; + return true;} }, removeEntry: function (key) { - // write me! - }, + if (typeof key !== 'string') { // write me! + return new TypeError('removeEntry: key should be a string'); + } + else if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + return new ReferenceError(`removeEntry: no property "${key}" in this.entries`); + } + else {delete this.entries[key]; + return true;} + }, updateEntry: function (key, value) { - // write me! + if (typeof key !== 'string') { // write me! + return new TypeError('updateEntry: key should be a string'); + } + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) + return new TypeError('updateEntry: value should be a primitive'); + } + if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + return new ReferenceError(`updateEntry: no property "${key}" in this.entries`); + } else {this.entries[key] = value; + return true;} }, readAll: function () { - // write me! + let clonedObj = {...this.entries}; + return clonedObj; }, findByKey: function (key) { - // write me! + if (typeof key !== 'string') { // write me! + return new TypeError('findByKey: key should be a string'); + } + if (!this.hasKey(this.entries, key)) { // write me! (using this.hasKey) + // console.log('haskey'); + return new ReferenceError(`findByKey: no property "${key}" in this.entries`); + } + const newObj = {}; + newObj[key] = this.entries[key]; + return newObj; }, - findByValue: function (value) { - // write me! + copyEntries: function() { + let copied = {...this.entries}; + return copied; + }, + findByValue: function(value) { + if (!this.isPrimitive(value)) { // write me! (using this.isPrimitive) + return new TypeError('findByValue: value should be a primitive'); + } + if (!this.hasValue(this.entries, value)) { // write me! (using this.hasValue) + return new ReferenceError(`findByValue: no entry with value (${typeof value}, ${value})`); + } + let copiedEntries = this.copyEntries(); + let requestedObj={}; + let newKey = Object.keys(copiedEntries).filter(keyOfValue => copiedEntries[keyOfValue] === value); + for (let i = 0; i < newKey.length; i++) { + if (this.entries[newKey[i]] === value) { + requestedObj[newKey[i]] = value; + } + } + return requestedObj; }, } diff --git a/week-3-project/practice-problems/arrays-vs-objects.js b/week-3-project/practice-problems/arrays-vs-objects.js index 4a7e82c..d7746de 100644 --- a/week-3-project/practice-problems/arrays-vs-objects.js +++ b/week-3-project/practice-problems/arrays-vs-objects.js @@ -14,8 +14,10 @@ try { function swapValues1() { const obj = { prop: "array" }; const arr = ["object"]; - let _ = null; - + let temp = obj.prop; + obj.prop = arr[0]; + arr[0]=temp; + // swap the values stored in each structure @@ -27,16 +29,17 @@ try { function swapValues2() { const obj = { prop: "array" }; const arr = ["object"]; - let _ = null; - - // swap the values stored in each structure using brackets and these variables + // swap the values stored in each structure using brackets and these variables const objKey = 'prop'; const arrIndex = 0; + let temp = obj[objKey]; + obj[objKey] = arr[arrIndex]; + arr[arrIndex]=temp; // asserts - console.assert(obj[obj_key] === "object", "obj assert"); - console.assert(arr[arr_index] === "array", "arr assert"); + console.assert(obj[objKey] === "object", "obj assert"); + console.assert(arr[arrIndex] === "array", "arr assert"); } evaluate(swapValues2); @@ -54,7 +57,10 @@ try { const arr2 = [3, 2, 1]; const arr3 = [1, 2, 3]; // do you remember why '===' won't work here? + arr2[0]=1; + arr2[2]=3; console.assert(evaluate.compareValues(arr1, arr2), 'arr: same values, different order'); + // debugger; console.assert(evaluate.compareValues(arr1, arr3), 'arr: same values, same order'); diff --git a/week-3-project/practice-problems/error-based-decisions.js b/week-3-project/practice-problems/error-based-decisions.js index f0b2f66..b334e9b 100644 --- a/week-3-project/practice-problems/error-based-decisions.js +++ b/week-3-project/practice-problems/error-based-decisions.js @@ -35,10 +35,12 @@ try { function exercise1(arg) { const result = mightReturnAnError(arg); - if (null) { // write this condition - // write me! + // debugger; + + if (result instanceof Error) { // write this condition + return false;// write me! } else { - // write me! + return true;// write me! } } @@ -59,10 +61,15 @@ try { ] function exercise2(arg) { const result = mightReturnAnError(arg); + + if (result instanceof Error) { // write this condition + return result.message;// write me! + } else { + return arg;// write me! + } - // write me! - - } + + } exercise2.display = true; evaluate(exercise2, exercise2Tests); @@ -81,10 +88,16 @@ try { ] function exercise3(arg) { const result = mightReturnAnError(arg); - - // write me! - - } + if (result instanceof Error) { // write this condition + let output = new Object(); + output[typeof arg]=result.message; + return output; + } else { + let output = new Object(); + output[typeof arg]=arg; + return output; + } +} exercise3.display = true; evaluate(exercise3, exercise3Tests); @@ -103,7 +116,15 @@ try { function exercise4(arg) { const result = mightReturnAnError(arg); - // write me! + if (result instanceof Error) { // write this condition + let output = []; + output[0]=result.message; + return output; + } else { + let output = []; + output=[null,arg]; + return output; + } } exercise4.display = true; diff --git a/week-3-project/practice-problems/getters-and-setters.js b/week-3-project/practice-problems/getters-and-setters.js index c5f2609..cc08c66 100644 --- a/week-3-project/practice-problems/getters-and-setters.js +++ b/week-3-project/practice-problems/getters-and-setters.js @@ -27,14 +27,14 @@ try { const obj2 = { name: 'obj2', get greeting() { - // write me! + return `hi, I'm ${this.name}` ; } } const obj1Greeting1 = obj1.getGreeting(); console.assert(obj1Greeting1 === `hi, I'm obj1`, `obj1's greeting is correct (1)`); - const obj2Greeting1 = null; // fix this line! + const obj2Greeting1 = obj2.greeting; // fix this line! console.assert(obj2Greeting1 === `hi, I'm obj2`, `obj2's greeting is correct (1)`); obj1.name = "first"; @@ -43,7 +43,7 @@ try { const obj1Greeting2 = obj1.getGreeting(); console.assert(obj1Greeting2 === `hi, I'm first`, `obj1's greeting is correct (2)`); - const obj2Greeting2 = null; // fix this line! + const obj2Greeting2 = obj2.greeting; // fix this line! console.assert(obj2Greeting2 === `hi, I'm second`, `obj2's greeting is correct (2)`); } @@ -65,16 +65,16 @@ try { numbers: [12, 4, 9, 36, 7, 0, -2], modulo: 3, get zeroMods() { - // write me! + return this.numbers.filter(x => x % this.modulo === 0);// write me! } } - const obj1mods3 = null; + const obj1mods3 = obj1.getZeroMods(); console.assert(obj1mods3[0] === 12, 'assert 1'); console.assert(obj1mods3[1] === 9, 'assert 2'); console.assert(obj1mods3[2] === 36, 'assert 3'); - const obj2mods3 = null; + const obj2mods3 = obj2.zeroMods; console.assert(obj2mods3[0] === 12, 'assert 4'); console.assert(obj2mods3[1] === 9, 'assert 5'); console.assert(obj2mods3[2] === 36, 'assert 6'); @@ -83,11 +83,11 @@ try { obj1.modulo = 6; obj2.modulo = 6; - const obj1mods3second = null; + const obj1mods3second = obj1.getZeroMods(); console.assert(obj1mods3second[0] === 12, 'assert 7'); console.assert(obj1mods3second[1] === 36, 'assert 8'); - const obj2mods3second = null; + const obj2mods3second = obj2.zeroMods; console.assert(obj2mods3second[0] === 12, 'assert 9'); console.assert(obj2mods3second[1] === 36, 'assert 10'); @@ -110,25 +110,25 @@ try { entries: { first: 'hi!', second: 'bye!' }, currentKey: 'second', get currentEntry() { - // write me! + return this.entries[this.currentKey];// write me! } } // replace the null's to pass the asserts: - const obj1current1 = null; + const obj1current1 = obj1.getCurrentEntry(); console.assert(obj1current1 === 'bye!', 'assert 1'); - const obj2current1 = null; + const obj2current1 = obj2.currentEntry; console.assert(obj2current1 === 'bye!', 'assert 2'); - obj1.currentKey = null; - obj2.currentKey = null; + obj1.currentKey = 'first'; + obj2.currentKey = 'first'; - const obj1current2 = null; + const obj1current2 = obj1.getCurrentEntry();; console.assert(obj1current2 === 'hi!', 'assert 3'); - const obj2current2 = null; + const obj2current2 = obj2.currentEntry; console.assert(obj2current2 === 'hi!', 'assert 4'); } @@ -149,20 +149,20 @@ try { const obj2 = { greeting: ``, set greetingName(newName) { - // write me! + this.greeting = `hi, I'm ${newName}!`;// write me! } }; obj1.setGreetingName('obj1'); console.assert(obj1.greeting === "hi, I'm obj1!", 'assert 1'); - ; // write me! + obj2.greetingName='obj2'; // write me! console.assert(obj2.greeting === "hi, I'm obj2!", 'assert 2'); obj1.setGreetingName('hi'); console.assert(obj1.greeting === "hi, I'm hi!", 'assert 3'); - ; // write me! + obj2.greetingName='bye'; // write me! console.assert(obj2.greeting === "hi, I'm bye!", 'assert 4'); } @@ -173,8 +173,6 @@ try { function setterRefactor2() { - - } setterRefactor2.display = true; evaluate(setterRefactor2); @@ -197,13 +195,19 @@ try { const obj2 = { entries: { first: 'hi!', second: 'bye!' }, current: {}, - // write me! + set currentEntry(key){ + if (this.entries.hasOwnProperty(key)) { + this.current = { [key]: this.entries[key] }; + } else { + this.current = { [key]: new Error(`no entry with key "${key}"`) } + } + }// write me! } obj1.setCurrentEntry('second'); console.assert(obj1.current.second === "bye!", 'assert 1'); - ; // write me! + obj2.currentEntry='second'; // write me! console.assert(obj2.current.second === "bye!", 'assert 2'); @@ -211,16 +215,15 @@ try { console.assert(obj1.current.first === "hi!", 'assert 3'); console.assert(obj1.current.hasOwnProperty('second') === false, 'assert 4'); - ; // write me! + obj2.currentEntry='first'; // write me! console.assert(obj2.current.first === "hi!", 'assert 5'); console.assert(obj2.current.hasOwnProperty('second') === false, 'assert 6'); - obj1.setCurrentEntry('hi'); console.assert(obj1.current.hi.message === 'no entry with key "hi"', 'assert 7'); console.assert(obj1.current.hasOwnProperty('first') === false, 'assert 8'); - ; // write me! + obj2.currentEntry='hi'; // write me! console.assert(obj2.current.hi.message === 'no entry with key "hi"', 'assert 9'); console.assert(obj2.current.hasOwnProperty('first') === false, 'assert 10'); diff --git a/week-3-project/tests/has-key.js b/week-3-project/tests/has-key.js index ff26be3..6fcbdf0 100644 --- a/week-3-project/tests/has-key.js +++ b/week-3-project/tests/has-key.js @@ -34,7 +34,19 @@ describe(`hasKey: determines if an object has a given key`, () => { }); }); }); + describe(`and returns false for non-existant entries.`, () => { + ['entries', 'hasKey', 'toSource', 'valueOf', 'hasOwnProperty', ''].forEach(arg => { + it(arg, () => { + const result = object.hasKey(object.entries, arg); + assert.strictEqual(result, false); + }); + }); + }); + describe(`or when there are no entries!`, () => { + before(() => { + object.entries = {}; + }); ['entries', 'hasKey', 'toSource', 'valueOf', 'hasOwnProperty', ''].forEach(arg => { it(arg, () => { const result = object.hasKey(object.entries, arg); @@ -43,6 +55,7 @@ describe(`hasKey: determines if an object has a given key`, () => { }); }); }); + describe(`or when there are no entries!`, () => { before(() => { object.entries = {}; @@ -55,3 +68,4 @@ describe(`hasKey: determines if an object has a given key`, () => { }); }); }); + diff --git a/week-3-project/tests/remove-entry.js b/week-3-project/tests/remove-entry.js index f3b310f..8a14f0c 100644 --- a/week-3-project/tests/remove-entry.js +++ b/week-3-project/tests/remove-entry.js @@ -38,7 +38,7 @@ describe(`removeEntry: should remove a key/value pair from this.entries`, () => describe(`... and actually removes the entries!`, () => { valuesToRemove.forEach(arg => { it(`object.hasKey(object.entries, ${arg}) === false`, () => { - assert.strictEqual(this.entries.hasOwnProperty(arg), false); + assert.strictEqual(object.entries.hasOwnProperty(arg), false); }); }); });