function reverseString(s) { // Create the result list const result = []; // Start from the end of the string and iterate towards the start for (let i = s.length-1; i >= 0; i -= 1) { // Push the current char in the list result.push(s[i]); } // Combine the result in a string return result.join(''); } // Examples console.log(reverseString("")) console.log(reverseString("abc")) console.log(reverseString("aaabbbcccd"))
function filterNumbers(arr) { // Create the result list const result = arr.filter(function(value, i) { // Filter based on the rules for checking the input is number if (isNaN(value) || isBoolean(value) || isEmptyString(value) || value === null) { return false; } return true; }); // Return numbers only list return result; } function isBoolean(value) { return typeof value === 'boolean'; } function isEmptyString(value) { return typeof value === 'string' && value.trim().length === 0; } console.log(filterNumbers([1, "2", " ", NaN, Number.POSITIVE_INFINITY, 66, "ab1", false, null]))
function linearSearch(arr, x) { let lo = 0; let hi = arr.length-1; // Iterate from start until the end of list while (lo <= hi) { // If item was found then return index if (arr[lo] === x) { return lo; } else { lo += 1 } } // Return -1 to denote the item was not found return -1; } let arr = [1,3,5,7,9,11,14,18,22]; console.info("Item was found at index: " + linearSearch(arr, 22));
function multiplier(first) { let a = first; return function(b) { return a * b; }; } let multiplyBy2 = multiplier(2); console.info(multiplyBy2(4)); console.info(multiplyBy2(5));
function flatten(arr=[]) { // Create the result list; let result = []; for (let item of arr) { // If item is an array we concat the contents if (Array.isArray(item)) { result = result.concat(flatten(item)); } else { result = result.concat(item); } } return result; } console.info(flatten([[1, 2, [3]], 4]));
function binarySearch(arr, x) { let lo = 0; let hi = arr.length-1; while (lo <= hi) { // Find mid element let m = Math.floor((lo + hi) / 2); // Check if equal to target if (arr[m] === x) { return m; // Reduce array search space by half } else if (arr[m] < x) { lo = m + 1; } else { hi = m - 1; } } // Item not found return -1; } let arr = [1,3,5,7,9,11,14,18,22]; console.info(console.info("Item was found at index: " + binarySearch(arr, 22)));
8. 编写一个函数,接受两个数字a和,并返回和的b除法以及和的模。abab
这很简单。这里我们需要返回两个值:
a / b和a % b。
function divMod(a, b) { // Be careful for division by zero if (b !== 0 ) { return [a / b, a % b]; } return [0, 0]; } console.info(divMod(16, 5)); console.info(divMod(20, 0));
function computeFrequency(s) { // Create the freq hashtable const freqTable = new Map(); // for each char in the string for (ch of s) { // Check if we have seen it already if (!freqTable.has(ch)) { freqTable.set(ch, 1); } else { // Just increase the existing entry freqTable.set(ch, freqTable.get(ch) + 1); } } // Return result return freqTable; } console.info(computeFrequency("abrakatabra"));