JSFiddle - React, Tailwind, and code Playground
by paulL
JavaScript
/* find the largest number in an array */
(function() {
//Find the largest absolute value in an array of numbers
function maxMagnitude(array) {
var i, n, abs = Math.abs,
max = Math.max,
largest = -Infinity;
for (i = -1, n = array.length; ++i < n;) {
largest = max(largest, abs(array[i]));
}
return largest;
}
//other call here calls magnitude on a large array
}());
//add a lot of stuff using argument
var sum = function() {
var i, sum = 0;
for (i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
};
console.log(sum(2, 4, 6, 8)); //20
// Add a method conditionally
Function.prototype.method = function(name, fn) {
if (!this.prototype[name]) {
this.prototype[name] = fn;
return this;
}
};
//tower of Hanoi
var hanoi = function hanoi(disc, src, aux, dst) {
if (disc > 0) {
hanoi(disc - 1, src, dst, aux);
console.log('Move disc' + disc + 'from' + src + 'to' + dst);
hanoi(disc - 1, aux, src, dst);
}
};
hanoi(3, 'Src', 'Aux', 'Dst');
/* result
Move disc1fromSrctoDst
Move disc2fromSrctoAux
Move disc1fromDsttoAux
Move disc3fromSrctoDst
Move disc1fromAuxtoSrc
Move disc2fromAuxtoDst
Move disc1fromSrctoDst
*/
//identifying an array
var is_array = function(value) {
return value && typeof value === 'object' && value.constructor === Array;
};
//problem cannot identify the array from different window or frame
var is_Array = function(value) {
return Object.prototype.toString.apply(value) === '[object Array]';
};