- Sum All Numbers in a Range ```javascript // 解法1, 遍历求和 function sumAll(arr) { let res = 0; let max = Math.max(arr[0], arr[1]) let min = Math.min(arr[0], arr[1]) for(let i = min; i <= max; i++) { res += i } return res; }
sumAll([1, 4]);
// 解法2,高斯求和 function sumAll(arr) { return ((arr[0] + arr[1]) * (Math.abs(arr[1] - arr[0]) + 1 ))/ 2 }
sumAll([1, 4]);
2. **Diff Two Arrays**```javascript// 解法1function diffArray(arr1, arr2) {var newArr = [];for (let i = 0; i < arr1.length; i++) {if (!arr2.includes(arr1[i])) {newArr.push(arr1[i])}}for (let i = 0; i < arr2.length; i++) {if (!arr1.includes(arr2[i])) {newArr.push(arr2[i])}}return newArr;}diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);// 解法2function diffArray(arr1, arr2) {return arr1.filter(e => !arr2.includes(e)).concat(arr2.filter(e => !arr1.includes(e)))}diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);// 解法3function diffArray(arr1, arr2) {return arr1.concat(arr2).filter(e => !arr1.includes(e) || !arr2.includes(e))}diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
- Seek and Destroy
```javascript
// 解法1
function destroyer(arr) {
arr = Array.from(arguments)
let [source, …toDelete] = arr; let res = [] for (let i = 0; i < source.length; i++) { if (!toDelete.includes(source[i])) { res.push(source[i]) } } return res }
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // [1,1]
function destroyer(arr) { arr = Array.from(arguments); let source = arr[0] let target = new Set(arr.slice(1)) return source.filter(e => !target.has(e)) }
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // [1,1]
4. **Wherefore art thou**```javascript// 解法1function whatIsInAName(collection, source) {let res = [];// Only change code below this linefor (let i = 0; i < collection.length; i++) {let shouldKeep = true;let current = collection[i]for (let key in source) {if (source[key] !== current[key]) {shouldKeep = false}}if (shouldKeep) {res.push(current)}}// Only change code above this linereturn res;}whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });// 解法2function whatIsInAName(collection, source) {return collection.filter(current =>Object.keys(source).every(key => source[key] === current[key]))}whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });// 解法三function whatIsInAName(collection, source) {return collection.filter(current =>Object.keys(source).reduce((acc, cur) => acc && current[cur] === source[cur], true))}whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Spinal Tap Case ```javascript // 解法1 function spinalCase(str) { let res = ‘’ for (let i = 0; i < str.length; i++) { let current = str[i]
if (/[A-Z]/.test(current)) { if (str[i-1] && /[a-z]/.test(str[i-1])) {
res += '-'
} }
if (current === ‘ ‘ || current === ‘_’) { res += ‘-‘ } else { res += current.toLowerCase() } } return res; }
spinalCase(‘This Is Spinal Tap’);
// 解法2 function spinalCase(str) { return str.replace(/ |_/g, ‘-‘) .replace(/([a-z])([A-Z])/g, ‘$1-$2’) .toLowerCase() }
spinalCase(‘This Is Spinal Tap’);
// 解法3 function spinalCase(str) { return str .split(/\s|_|(?<=[a-z])\B(?=[A-Z])/) .join(‘-‘) .toLowerCase()
}
spinalCase(‘This Is Spinal Tap’);
6. **Pig Latin**```javascript// 解法1function translatePigLatin(str) {let vowelIndex = -1for (let i = 0; i < str.length; i++) {if(/[aeiou]/.test(str[i])) {vowelIndex = i;break;}}if (vowelIndex === -1) {return str + 'ay'} else if (vowelIndex === 0) {return str + 'way'} else {return str.slice(vowelIndex) + str.slice(0, vowelIndex)+ 'ay'}}translatePigLatin("consonant");// 解法2, 正则function translatePigLatin(str) {return str.replace(/([^aeiou]*)([aeiou]?)(\w*)/, (match, before, vowel, after) => {if (before) {return vowel + after + before+ 'ay'} else {return vowel + after + 'way'}})}translatePigLatin("consonant");function translatePigLatin(str) {return str.replace(/([^aeiou]*)([aeiou]?)(\w*)/, (match, before, vowel, after) => {return `${vowel}${after}${before || 'w'}ay`})}translatePigLatin("consonant");function translatePigLatin(str) {return str.replace(/([^aeiou]*)(\w*)/, (match, before, after) => {return `${after}${before || 'w'}ay`})}translatePigLatin("consonant");function translatePigLatin(str) {return str.replace(/(^[aeiou]\w+$)/, '$1way').replace(/^([^aeiou]+)(\w*)$/, '$2$1ay')}translatePigLatin("consonant");
- Search and Replace ```javascript // 解法1 function myReplace(str, before, after) { if (/[A-Z]/.test(before[0])) { after = after[0].toUpperCase() + after.slice(1) } else { after = after[0].toLowerCase() + after.slice(1) } return str.replace(before, after) }
myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”);
// 解法2 function myReplace(str, before, after) { let arr = str.split(‘ ‘) for (let i = 0; i < arr.length; i++) { if (arr[i] === before) { if (/^[A-Z]/.test(before)) { arr[i] = after[0].toUpperCase() + after.slice(1) } else { arr[i] = after[0].toLowerCase() + after.slice(1) } } }
return arr.join(‘ ‘) }
myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”);
function myReplace(str, before, after) { let arr = str.split(‘ ‘), target; if (/^[A-Z]/.test(before)) { target = after[0].toUpperCase() + after.slice(1) } else { target = after[0].toLowerCase() + after.slice(1) } for (let i = 0; i < arr.length; i++) { if (arr[i] === before) { arr[i] = target } }
return arr.join(‘ ‘) }
myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”);
// 解法3 function myReplace(str, before, after) { let arr = str.split(‘ ‘), target; if (/^[A-Z]/.test(before)) { target = after[0].toUpperCase() + after.slice(1) } else { target = after[0].toLowerCase() + after.slice(1) }
return arr.reduce(
(acc, cur) => ${acc} ${cur === before ? target : cur}
)
}
myReplace(“A quick brown fox jumped over the lazy dog”, “jumped”, “leaped”);
8. **DNA Pairing**```javascript// 解法1function pairElement(str) {let res = []for (let i = 0; i < str.length; i++) {let curr = str[i]if (curr === 'A') {res.push(['A', 'T'])} else if(curr === 'T') {res.push(['T', 'A'])}else if(curr === 'C') {res.push(['C', 'G'])}else if(curr === 'G') {res.push(['G', 'C'])}}return res;}pairElement("GCG");// 解法2function pairElement(str) {let res = []let map = new Map([["A","T"],["T","A"],["C","G"],["G","C"]])for (let char of str) {res.push([char, map.get(char)])}return res;}pairElement("GCG");
- Missing letters ```javascript // 解法1 function fearNotLetter(str) { for (let i = 0; i < str.length - 1; i++) { let cur = str[i].charCodeAt() let next = str[i+1].charCodeAt() if (next !== cur + 1) { return String.fromCharCode(cur+1) } } }
fearNotLetter(“abce”);
// 解法2 function fearNotLetter(str) { let prev = str.charCodeAt(0); for (let i = 1; i < str.length; i++) { let cur = str[i].charCodeAt() if (cur !== prev + 1) { return String.fromCharCode(prev+1) } prev = cur } }
fearNotLetter(“abce”);
// 解法3 function fearNotLetter(str) { let start = str.charCodeAt(0) let end = str.charCodeAt(str.length - 1) return Array.from({length: end - start +1 }, (_, i) => String.fromCharCode(start+i)).filter(char => !str.includes(char))[0] }
fearNotLetter(“abce”);
10. **Sorted Union**```javascript// 解法1function uniteUnique(arr) {arr = [...arguments]let res = []for (let item of arr) {for (let subItem of item) {if (!res.includes(subItem)) {res.push(subItem)}}}return res;}uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);// 解法2function uniteUnique(arr) {arr = [...arguments]return arr.reduce((acc, cur) => acc.concat(cur.filter(e => !acc.includes(e))), [])}uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);// 解法3function uniteUnique(arr) {arr = [...arguments]return arr.reduce((acc, cur) => acc.concat(cur)).filter((e, i, combined) => combined.indexOf(e) === i)}uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);// 解法4function uniteUnique(arr) {return [...new Set([...arguments].flat())]}uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
- Convert HTML Entities ```javascript // 解法1 function convertHTML(str) { let entitiesMap = { ‘&’: ‘&’, ‘<’: ‘<’, ‘>’: ‘>’, ‘“‘: ‘"’, ‘\’’: ‘'’, } return str.replace(/[&<>”‘]/g, match => entitiesMap[match]) }
convertHTML(“Dolce & Gabbana”);
// 解法2 function convertHTML(str) { let entitiesMap = { ‘&’: ‘&’, ‘<’: ‘<’, ‘>’: ‘>’, ‘“‘: ‘"’, ‘\’’: ‘'’, } return str.split(‘’).reduce((acc, cur) => acc+= (entitiesMap[cur] || cur ) , ‘’) }
convertHTML(“Dolce & Gabbana”);
14. **Binary Agents**```javascriptfunction binaryAgent(str) {let arr = str.split(' ')return arr.reduce((acc, cur) => acc += String.fromCharCode(parseInt(cur, 2)), '')}binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
- Everything Be True ```javascript function truthCheck(collection, pre) { for (let i = 0; i < collection.length; i++) { let cur = collection[i] if (!cur[pre]) return false; } return true; }
truthCheck([{“user”: “Tinky-Winky”, “sex”: “male”}, {“user”: “Dipsy”, “sex”: “male”}, {“user”: “Laa-Laa”, “sex”: “female”}, {“user”: “Po”, “sex”: “female”}], “sex”);
function truthCheck(collection, pre) { return collection.every(o => o[pre]) }
16. **Arguments Optional**```javascriptfunction addTogether() {let args = [...arguments]let isNumbers = (numbers) => numbers.every(num => typeof num === 'number')if (!isNumbers(args)) return;if (args.length === 2) {return args[0] + args[1]}return function () {if (!isNumbers([...arguments])) returnreturn args[0] + arguments[0]}}addTogether(2,3);
- Sum All Odd Fibonacci Numbers ```javascript // 解法1: 转化成数组 function sumFibs(num) { let fibs = [1,1] while(true) { let len = fibs.length; let next = fibs[len -1] + fibs[len -2] if (next <= num) { fibs.push(next); } else { break; } } return fibs.reduce((acc, cur) => (cur % 2 === 1 ? acc+ cur: acc),0) }
sumFibs(4);
// 解法2 function sumFibs(num) { let thePrev = 1, prev = 1; let res = 2; while(thePrev + prev <= num) { let next = thePrev + prev; if (next % 2 === 1) { res += next } thePrev = prev; prev = next; } return res; }
sumFibs(4);
function sumFibs(num) { let prev = 1, cur = 1; let res = 1;
while(cur <= num) { if (cur % 2 === 1) { res += cur; } cur += prev; prev = cur - prev; } return res; }
sumFibs(4);
// 解法3 function sumFibs(num) { return getSum(1,1,1, num); }
function getSum(prev, cur, sum, num) { if (cur > num) { return sum } if (cur % 2 === 1) { sum += cur } // cur = prev + cur return getSum(cur, prev+cur, sum, num) }
sumFibs(4);
18. **Smallest Common Multiple**```javascript// 解法1;function smallestCommons(arr) {let smaller = Math.min(...arr)let larger = Math.max(...arr)let res = 1;for (let i = smaller; i <= larger; i++) {res = getSCM(i, res);}return res;}function getSCM(left, right) {if (left === 0 || right === 0) {return}if (left === right) {return right}let res = rightwhile(res <= left * right) {if (res % left === 0) {return res}res += right}}smallestCommons([1,5]);// 解法2, 辗转相除法获取x,y最大公约数c,最小公倍数 m = x * y / cfunction smallestCommons(arr) {let smaller = Math.min(...arr)let larger = Math.max(...arr)let res = 1;while(smaller <= larger) {res = smaller * res / getGCD(smaller, res)smaller++}return res;}function getGCD(a, b) {while (b != 0) {let temp = bb = a % ba = temp;}return a}smallestCommons([1,5]);
- Drop it ```javascript // 解法1 function dropElements(arr, func) { while(arr.length > 0) { if(!func(arr[0])){ arr.shift() } } return arr; }
dropElements([1, 2, 3], function(n) {return n < 3; });
// 解法2 function dropElements(arr, func) { while(arr.length > 0) { if(!func(arr[0])){ arr = arr.slice(1) } } return arr; }
dropElements([1, 2, 3], function(n) {return n < 3; });
// 解法3 function dropElements(arr, func) { if (arr.length === 0) { return [] } return !func(arr[0]) ? dropElements(arr.slice(1), func) :arr }
dropElements([1, 2, 3], function(n) {return n < 3; });
20. **Steamroller**```javascript// 解法1function steamrollArray(arr) {let res = []for (let item of arr) {if (!Array.isArray(item)) {res.push(item)} else {res = res.concat(steamrollArray(item))}}return res}steamrollArray([1, [2], [3, [[4]]]]);function steamrollArray(arr) {let res = []helper(arr, res)return res}function helper(arr, res) {for(let item of arr) {Array.isArray(item) ? helper(item, res): res.push(item)}}steamrollArray([1, [2], [3, [[4]]]]);// 解法2function steamrollArray(arr) {return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? steamrollArray(cur) : cur), [])}
Sum All Primes
function sumPrimes(num) {if (num < 2) return 1;let res = 0;for(let i = 2; i <= num; i++) {if (isPrime(i)) {res += i}}return res;}function isPrime(n) {for (let i= 2; i < n; i++) {if (n % i === 0) {return false;}}return true;}// 2,3, 5, 7sumPrimes(10);
Make a Person ```javascript var Person = function(firstAndLast) { // Only change code below this line // Complete the method below and implement the others similarly let fullName = firstAndLast
this.getFullName = function() { return fullName; };
this.getFirstName = function() { return fullName.split(‘ ‘)[0] }
this.getLastName = function() { return fullName.split(‘ ‘)[1] }
this.setFirstName = function (name) { fullName = name + ‘ ‘ + this.getLastName() }
this.setLastName = function (name) { fullName = this.getFirstName() + ‘ ‘ + name }
this.setFullName = function (name) { fullName = name; }
return this; };
var bob = new Person(‘Bob Ross’); bob.getFullName();
22. **Map the Debris**```javascriptfunction orbitalPeriod(arr) {const GM = 398600.4418;const earthRadius = 6367.4447;return arr.map(({ name, avgAlt }) => {const earth = earthRadius + avgAlt;const orbitalPeriod = Math.round(2 * Math.PI * Math.sqrt(Math.pow(earth, 3)/GM));return { name, orbitalPeriod };});}orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
