算法中级:范围内的数字求和
function sumAll(arr) {
let max = Math.max(...arr);
let min = Math.min(...arr);
let temp = 0
for(let i=min; i<=max; i++){
temp += i;
}
// temp = (min + max)*(max - min + 1)/2
return temp;
}
sumAll([1, 4]);
算法中级:区分两个数组
function diffArray(arr1, arr2) {
let newArr = [];
function diff(a,b){
a.forEach(x => {
if(b.indexOf(x) === -1){
newArr.push(x);
}
})
}
diff(arr1,arr2);
diff(arr2, arr1);
return newArr;
// return arr1.filter(x => !arr2.includes(x)).concat(arr2.filter(x => !arr1.includes(x)));
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
算法中级:瞄准和消灭
function destroyer(arr) {
let args = Array.from(arguments).slice(1);
return arr.filter(x => !args.includes(x));
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);;
算法中级:罗密欧与朱丽叶
function whatIsInAName(collection, source) {
let srcKeys = Object.keys(source);
return collection.filter(obj => {
return srcKeys.every(key => {
return obj.hasOwnProperty(key) && obj[key] === source[key];
})
});
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
算法中级:短线连接格式
function spinalCase(str) {
return str.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/(?:_| )+/g).join("-");
}
spinalCase('This Is Spinal Tap');
算法中级:儿童黑话
function translatePigLatin(str) {
let regex = /[aeiou]/gi;
if(str[0].match(regex)){
return str + "way"
}else if(str.match(regex) === null){
return str + "ay"
}else {
let index = str.indexOf(str.match(regex)[0]);
return str.slice(index) + str.slice(0,index)+"ay";
}
}
// 或者
function translatePigLatin(str) {
let newArr = [];
let tempChar;
function isConsonant(char){
return !(/[aeiou]/).test(char);
}
if(!isConsonant(str.charAt(0))){
return str + "way";
}else {
newArr = str.split("");
while(isConsonant(newArr[0])){
tempChar = newArr.shift();
newArr.push(tempChar);
}
return newArr.join("")+"ay";
}
}
translatePigLatin("consonant");
算法中级:搜索和替换
function myReplace(str, before, after) {
after = /[A-Z]/.test(before[0])?after[0].toUpperCase()+after.slice(1):after;
return str.replace(before, after);
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
算法中级:DNA 配对
function pairElement(str) {
let pairs = {
"A": "T",
"T": "A",
"C": "G",
"G": "C"
}
return str.split("").map(x => [x, pairs[x]]);
}
pairElement("GCG");
算法中级:丢失的字母
function fearNotLetter(str) {
for(let i=1;i<str.length;i++){
if(str.charCodeAt(i) - str.charCodeAt(i-1) > 1){
return String.fromCharCode(str.charCodeAt(i - 1)+1);
}
}
}
fearNotLetter("abce");
算法中级:集合排序
function uniteUnique(arr) {
let concatArr = [];
let i = 0;
while(arguments[i]){
concatArr = concatArr.concat(arguments[i]);
i++;
}
return concatArr.filter((item,index) => {
return concatArr.indexOf(item) === index;
})
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
算法中级:转换HTML实体
function convertHTML(str) {
// :)
let rule = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"\'": "'"
}
return str.split("").map(x => {
return rule.hasOwnProperty(x)?rule[x]:x;
}).join("");
// return str.split("").map(x => rule[x] || x).join("");
}
convertHTML("Dolce & Gabbana");
算法中级:求斐波那契数组中的奇数之和
function sumFibs(num) {
let preNumber = 0;
let currNumber = 1;
let result = 0;
while(currNumber<=num){
if(currNumber%2 !== 0){
result += currNumber;
}
currNumber += preNumber;
preNumber = currNumber - preNumber;
}
return result;
}
function sumFibs(num) {
if (num < 0) return -1;
if (num === 0 || num === 1) return 1;
const arrFib = [1, 1];
let nextFib = 0;
while((nextFib = arrFib[0] + arrFib[1]) <= num) {
arrFib.unshift(nextFib);
}
return arrFib.reduce((acc, curr) => {
return acc + curr * (curr % 2);
},0);
}
sumFibs(4);
算法中级:对所有素数求和
function sumPrimes(num) {
let result = 0;
function isPrimes(a){
for(let i=2; i < a;i++){
if(a%i===0&&a!==i){
return false
}
}
return true;
}
if (num <= 1){
return 0;
}
for(let j=2;j<=num;j++){
if(isPrimes(j)){
result += j;
}
}
return result;
}
sumPrimes(10);
算法中级:最小公倍数
function gcd(a, b) {
while (b > 0) {
let tmp = a;
a = b;
b = tmp % b;
}
return a;
}
function lcm(a, b) {
return (a * b / gcd(a, b));
}
function smallestCommons(arr) {
let min = Math.min.apply(null, arr);
let max = Math.max.apply(null, arr);
let smallestCommon = lcm(min, min + 1);
while(min < max) {
min++;
smallestCommon = lcm(smallestCommon, min);
}
return smallestCommon;
}
smallestCommons([1,5]);
算法中级:放弃
function dropElements(arr, func) {
// 删掉那些该舍弃的元素
while(arr.length > 0 && !func(arr[0])) {
arr.shift();
}
return arr;
}
dropElements([1, 2, 3], function(n) {return n < 3; });
算法中级:扁平化
function steamrollArray(arr) {
let flattenedArray = [];
var flatten = function(arg) {
if (!Array.isArray(arg)) {
flattenedArray.push(arg);
} else {
for (var a in arg) {
flatten(arg[a]);
}
}
};
arr.forEach(flatten);
return flattenedArray;
// let flat = [].concat(...arr);
// return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
}
steamrollArray([1, [2], [3, [[4]]]]);
算法中级:二进制转化
function binaryAgent(str) {
let biString = str.split(' ');
let uniString = [];
for(let i=0;i < biString.length;i++){
uniString.push(String.fromCharCode(parseInt(biString[i], 2)));
}
return uniString.join('');
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
算法中级:真假值判断
function truthCheck(collection, pre) {
let counter = 0;
for (let c in collection) {
if (collection[c].hasOwnProperty(pre) && Boolean(collection[c][pre])) {
counter++;
}
}
return counter == collection.length;
// return collection.every(function (element) {
return element.hasOwnProperty(pre) && Boolean(element[pre]);
});
}
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
算法中级:可选参数
function addTogether() {
let args = Array.from(arguments);
return args.some(n => typeof n !== 'number') ?
undefined :
args.length > 1 ?
args.reduce((acc, n) => acc += n, 0) :
(n) => typeof n === "number" ?
n + args[0] :
undefined;
}
addTogether(2, 3);
算法中级:构造一个 Person 类
var Person = function(firstAndLast) {
var fullName = firstAndLast;
this.getFirstName = function() {
return fullName.split(" ")[0];
};
this.getLastName = function() {
return fullName.split(" ")[1];
};
this.getFullName = function() {
return fullName;
};
this.setFirstName = function(name) {
fullName = name + " " + fullName.split(" ")[1];
};
this.setLastName = function(name) {
fullName = fullName.split(" ")[0] + " " + name;
};
this.setFullName = function(name) {
fullName = name;
};
};
var bob = new Person('Bob Ross');
bob.getFullName();
算法中级:绘制碎片图
function orbitalPeriod(arr) {
var GM = 398600.4418;
var earthRadius = 6367.4447;
for(var prop in arr) {
var orbitalPer = Math.round(2 * Math.PI * Math.sqrt(Math.pow(arr[prop].avgAlt + earthRadius, 3) / GM));
delete arr[prop].avgAlt;
arr[prop].orbitalPeriod = orbitalPer;
}
return arr;
}
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);