// code for the scope problem var mod = new Module(), request; request = function (env, callback) { return callback.apply(env); }; function Module () { this.foo = 'bar'; }; Module.prototype.method = function() { return this.foo; }; Module.prototype.req = function() { //gotta pass the entire environment because by default 'this' will just reference the window return request(this, this.method); }; // code for the copy-object problem var obj = {name: 'Ahmed', age: 27, skills: ['cycling', 'walking', 'eating']}; var nestedObj = {name: 'Ahmed', age: 27, skills: ['cycling', 'walking', 'eating'], bazoink: {beep: "beep", boop: "boop"}}; function clone (obj){ //clone an object, ie copy all the contents of one object into another. //important to note that pass by reference means that if you modify a value within the cloned //it will effect the cloned. //this will clone nested objects const isObject = function(a) { return (!!a) && (a.constructor === Object); }; let clone = {}; let fun = function (obj) { let keys = Object.keys(obj); keys.forEach(key => isObject(clone[key]) ? fun(clone[key]) : clone[key] = obj[key]); }; fun(obj); return clone; } function clone2 (obj) { //create an entirely new version of the object and return it let str = JSON.stringify(obj); let clone = JSON.parse(str); return clone; } // code for the flatten array problem function flattenAndSortR (array) { //recursive flatten and sort algorithm const firstArray = array => array.length == 0 ? array : array[0]; const restArray = array => array.length == 0 ? array : array.slice(1,array.length); let res = []; let rec = function (arr) { // console.log(arr); if (arr == null) { return null; } else if (Array.isArray(arr) && arr.length !== 0) { rec(firstArray(arr)); rec(restArray(arr)); } else if (!Array.isArray(arr) && arr.length !== 0) { res.push(arr); }; }; rec(array); return res.sort(); } function flattenAndSortI (array) { //iterative version of flattenAndSort let res = []; let fun = function (arr) { arr.forEach(ele => Array.isArray(ele) ? fun(ele) : res.push(ele)); }; fun(array); return res.sort(); }