[Advanced JS] Exercise: Prototypal Chain and Inheritance in JavaScript
Някой желае ли да сподели решението на упражнението?
Някой желае ли да сподели решението на упражнението?
Това е моят extension method:
Object.prototype.getRandom = function () {
if(this instanceof Array || this instanceof String){
return this[this.length * Math.random() << 0];
}
var keys = Object.keys(this);
var rand = Math.random();
var result = {};
result[keys[ keys.length * rand << 0]] = this[keys[ keys.length * rand << 0]];
return result;
};
4-та:
var SortedList = (function () {
function SortedList(){
this._innerArr = [];
this.length = 0;
}
SortedList.prototype.add = function (num){
this._innerArr.push(num);
this.length+=1;
this._innerArr.sort(function (a,b){
return a>b;})
};
SortedList.prototype.get = function (index){
return this._innerArr[index];
};
return SortedList;
})();
Math.random = function() {
return 3;
}
function getRandomNum() {
var randomNum = Math.floor(Math.random() * 10);
return randomNum;
}
var mysteryNum = getRandomNum();
for (var i = 0; i < 10; i++) {
var currentMysteryNum = getRandomNum();
if (currentMysteryNum !== mysteryNum) {
throw new Error("No chance for you today!");
}
}
Object.prototype.getRandom = function () {
if (this instanceof Array || typeof this === "string") {
return this[Math.floor(Math.random() * this.length)];
}
var keys = Object.keys(this);
var obj = {};
var random = Math.random();
obj[keys[keys.length * random << 0]] = this[keys[keys.length * random << 0]];
return obj;
};
Function.prototype.call = function (obj) {
var newArg = [];
for (var i = 1; i < arguments.length; i++) {
newArg.push(arguments[i]);
}
this.apply(obj, newArg);
}
Array.prototype.sortNum = function () {
return this.sort(function (a, b) { return a - b });
}
var ListOfNumbers = {
init: function(arr) {
this._arr = arr.sortNum();
this.length = this._arr.length;
},
add: function(num) {
this._arr.push(num);
this._arr = this._arr.sortNum();
this.length = this._arr.length;
},
get: function(index) {
return this._arr[index];
}
};