background
JavaScript algorithms and data structures, intermediate algorithms
code
Sum of numbers in range
function sumAll([num1, num2]) {
const count = Math.abs(num2 - num1) +1;
const res = (num1 + num2) * count >> 1
return res;
}
sumAll([1.4]);
Copy the code
Array symmetry difference
function diffArray(arr1, arr2) {
return arr1.concat(arr2).filter(item= > {
return! arr1.includes(item) || ! arr2.includes(item) }); } diffArray([1.2.3.5], [1.2.3.4.5]);
Copy the code
Filter array elements
function destroyer(arr, ... args) {
return arr.filter(item= > {
return! args.includes(item); }); } destroyer([1.2.3.1.2.3].2.3.4);
Copy the code
Find the object that contains a particular key-value pair
function whatIsInAName(collection, source) {
const arr = [];
// Change only the code below this line
const keys = Object.keys(source);
// Change only the code above this line
return collection.filter(item= > {
return keys.every((key) = > {
return item.hasOwnProperty(key) && item[key] === source[key]
})
});
}
whatIsInAName([{ first: "Romeo".last: "Montague" }, { first: "Mercutio".last: null }, { first: "Tybalt".last: "Capulet"}, {last: "Capulet" });
Copy the code
Short line connection format
function spinalCase(str) {
let reg = /\s+|_+/g
// Fill out the Spaces first
str = str.replace(/([a-z])([A-Z])/g.'$1 $2');
return str.replace(reg, The '-').toLowerCase();
}
spinalCase('This Is Spinal Tap');
Copy the code
Pig Latin
function translatePigLatin(str) {
const yuan = 'aeiou';
if (yuan.includes(str.charAt(0))) {
return str + 'way'
} else {
let index = 0;
while(! yuan.includes(str.charAt(index))) { index++; }return str.slice(index) + str.slice(0, index) + 'ay'
}
}
translatePigLatin("consonant");
Copy the code
Search and replace
function myReplace(str, before, after) {
let reg = /^[A-Z]/g
if (reg.test(before)) {
after = after.charAt(0).toUpperCase() + after.slice(1);
} else {
after = after.charAt(0).toLowerCase() + after.slice(1);
}
return str.replace(before, after);
}
myReplace("A quick brown fox jumped over the lazy dog"."jumped"."leaped");
Copy the code
DNA matching
function pairElement(str) {
const obj = {
'A': 'T'.'T': 'A'.'C': 'G'.'G': 'C',}const res = []
for(let i = 0; i < str.length; i++) {
let a = [str[i], obj[str[i]]];
res.push(a);
}
return res;
}
pairElement("GCG");
Copy the code
Look for missing letters
function fearNotLetter(str) {
for(let i = 0; i< str.length; i++) {
let code = str.charCodeAt(i);
if(code ! == str.charCodeAt(0) + i) {
return String.fromCharCode(code - 1); }}return undefined
}
fearNotLetter("abce");
Copy the code
Collection sorting
function uniteUnique(. args) {
const arr = args.flat(Infinity);
const set = new Set(arr);
return [...set];
}
uniteUnique([1.3.2], [5.2.1.4], [2.1]);
Copy the code
Convert HTML character entities
function convertHTML(str) {
const htmlEntities = {
"&": "&"."<": "<".">": ">".'"': """."'": "'"
};
return str.replace(/([&<>\"'])/g.m= > {
return htmlEntities[m];
});
}
convertHTML("Dolce & Gabbana");
Copy the code
Find the sum of odd numbers in the Fibonacci sequence
function sumFibs(num) {
let prev = 0;
let cur = 1;
let res = 0;
while(cur <= num) {
if (cur % 2! =0) {
/ / odd
res += cur;
}
cur = prev + cur;
prev = cur - prev;
}
return res;
}
sumFibs(4);
Copy the code
Prime Numbers sum
function sumPrimes(num) {
let res = 0;
let cur = 2;
function isPrime (num) {
for(let i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false}}return true;
}
while (cur <= num) {
if(isPrime(cur)) {
res += cur;
}
cur += 1;
}
return res;
}
sumPrimes(10);
Copy the code
Find the least common multiple in the range of numbers
function smallestCommons(arr) {
const [min, max] = arr.sort((a,b) = > a-b);
// Create a sorted array
const rangeArr = Array(max-min+1).fill(0).map((item, index) = > {
return min+index;
});
// Compute a product of all values
const upper = rangeArr.reduce((prev, cur) = > {
return prev * cur;
});
// find the lowest common multiple
for (let i = max; i <= upper; i+=max ) {
const p = rangeArr.every(item= > {
return i % item === 0;
});
if (p) {
return i;
}
}
}
smallestCommons([1.5]);
Copy the code
Removes array elements based on arguments
function dropElements(arr, func) {
while(arr.length && ! func(arr[0])) {
arr.shift();
}
return arr;
}
dropElements([1.2.3].function(n) {return n < 3; });
Copy the code
Array flattening
Can’t use arr. Flat (Infinity)
So you have to do it recursively, so you can use a for loop to see if there’s data in the element, and then recurse
Here’s another recursion
function steamrollArray(arr) {
constres = [].concat(... arr);return res.some(item= > {
return Array.isArray(item)
}) ? steamrollArray(res) : res
}
steamrollArray([1[2], [3The [[4]]]]);
Copy the code
Translating binary strings
Translating binary strings
function binaryAgent(str) {
let res = [];
const arr = str.split(' ');
return arr.map(item= > {
let asciiCode = parseInt(item, 2);
let charValue = String.fromCharCode(asciiCode);
return charValue
}).join(' ');
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
Copy the code
// String to binary
function strToBinary (str) {
let list = str.split(' ');
return list.map(item= > {
return item.charCodeAt().toString(2);
}).join(' ');
}
strToBinary('我们')
Copy the code
Everything is True
function truthCheck(collection, pre) {
return collection.every(item= > {
return item[pre]
});
}
truthCheck([{"user": "Tinky-Winky"."sex": "male"}, {"user": "Dipsy"."sex": "male"}, {"user": "Laa-Laa"."sex": "female"}, {"user": "Po"."sex": "female"}]."sex");
Copy the code
Optional parameters
function addTogether(. args) {
if (args.length === 1) {
let a = args[0]
if (typeof a === 'number') {
return function (b) {
return typeof b === 'number' ? a+b : undefined; }}}else {
if (typeof args[0= = ='number' && typeof args[1= = ='number') {
return args[0] + args[1]}}return undefined;
}
addTogether(2.3);
Copy the code
Create a staff object
const Person = function(firstAndLast) {
// Change only the code below this line
// Complete the following method, the rest is similar
var firstAndLast = firstAndLast;
this.getFullName = function() {
return firstAndLast;
};
this.getFirstName = function() {
return firstAndLast.split(' ') [0];
};
this.getLastName = function() {
return firstAndLast.split(' ') [1];
};
this.setFirstName = function(str) {
firstAndLast = `${str} ${firstAndLast.split(' ') [1]}`
};
this.setLastName = function(str) {
firstAndLast = `${firstAndLast.split(' ') [0]} ${str}`
};
this.setFullName = function(str) {
firstAndLast = str;
};
};
const bob = new Person('Bob Ross');
bob.getFullName();
Copy the code
Calculate orbital period
function orbitalPeriod(arr) {
const GM = 398600.4418;
const earthRadius = 6367.4447;
const newArr = JSON.parse(JSON.stringify(arr));
newArr.forEach(function(item) {
const tmp = Math.round(
2 * Math.PI * Math.sqrt(Math.pow(earthRadius + item.avgAlt, 3) / GM)
);
delete item.avgAlt;
item.orbitalPeriod = tmp;
});
return newArr;
}
orbitalPeriod([{name : "sputnik".avgAlt : 35873.5553}]);
Copy the code