Skip to content

Instantly share code, notes, and snippets.

@mingyun
Created February 21, 2014 09:47
Show Gist options
  • Save mingyun/9131515 to your computer and use it in GitHub Desktop.
Save mingyun/9131515 to your computer and use it in GitHub Desktop.
String.prototype.repeat = function(count) {
// Go for it
var a = "";
for (var i = count; i > 0; i--) {
a += this.valueOf();
}
return a;
};
//nice
String.prototype.repeat = function(count) {
return new Array(count + 1).join(this);
};
//斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
function nthFibo(n) {
if ( n == 1 ) { return 0; }
if ( n == 2 ) { return 1; }
return nthFibo(n-1)+nthFibo(n-2);
}nthFibo(4) == 2
function ipsBetween(start, end){
//TODO
var s = start.split('.');
var e = end.split('.');
return (((e[0] - s[0])*256 + (e[1] - s[1]))*256 + (e[2] - s[2]))*256 - (- e[3]) - s[3];
}
ipsBetween("10.0.0.0", "10.0.0.50") => returns 50
ipsBetween("10.0.0.0", "10.0.1.0") => returns 256
ipsBetween("20.0.0.10", "20.0.1.0") => returns 246
//nice
function ipsBetween(start, end){
function parse(addr) {return addr.split(".").reduce(function(sum,byte) {return sum*256+1*byte;},0);}
return parse(end)-parse(start);
}
solution('abc') // should return ['ab', 'c_']
solution('abcdef') // should return ['ab', 'cd', 'ef']
function solution(str){
str=str.length%2?str+'_':str;
return str.match(/.{2}/g);
}
function numbers () {
if (arguments[0] == null) return false;
var tmp = true;
for (var i = 0; i < arguments.length - 1; i++) {
if (typeof arguments[i] != 'number') {
tmp = false;
}
}
return tmp;
}
console.log(numbers(null));
//类数组对象arguments有length属性,也可以通过下标访问成员,这些特点跟数组非常像,因此你可以用call或者apply方法让它借用数组的迭代方法,这就是Array.prototype.every.call(arguments)做的事情。类似的,你通过Array.prototype.slice.call(arguments)得到了一个由arguments成员构成的数组,所以它可以直接调用every方法。
function numbers(){
return Array.prototype.slice.call(arguments).every(function(i){
return typeof i == 'number'
});
}
function numbers() {
return arguments.length === 0 ? false : Array.prototype.every.call(arguments, function(n) {
return typeof n === 'number'
})
}
var odds = reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });=> [1, 3, 5]
function reject(array, iterator) {
//
var a = [];
for (var i in array) {
if(!iterator(array[i])) {
a.push(array[i]);
}
}
return a;
}
function reject(array, iterator) {
return array.filter(function(val){ return !iterator(val) })
}
function isLeapYear(year) {
// TODO
if (year%400 == 0) {
return true;
} else if (year%100 == 0){
return false;
} else if (year%4 == 0) {
return true;
} else {
return false;
}
}
function isLeapYear(year) {
return new Date(year, 1, 29).getDate() == 29;
}
function solution(string,limit){
return string.length > limit ? string.substr(0,limit) + "..." : string;
}
solution('Testing String',8) // should return 'Testing ...'
//via:http://www.html-js.com/article/column/98
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment