• Nov 19, 2022 •CodeCatch
0 likes • 0 views
const head = arr => (arr && arr.length ? arr[0] : undefined); head([1, 2, 3]); // 1 head([]); // undefined head(null); // undefined head(undefined); // undefined
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); // Examples toFixed(25.198726354, 1); // 25.1 toFixed(25.198726354, 2); // 25.19 toFixed(25.198726354, 3); // 25.198 toFixed(25.198726354, 4); // 25.1987 toFixed(25.198726354, 5); // 25.19872 toFixed(25.198726354, 6); // 25.198726
const heapsort = arr => { const a = [...arr]; let l = a.length; const heapify = (a, i) => { const left = 2 * i + 1; const right = 2 * i + 2; let max = i; if (left < l && a[left] > a[max]) max = left; if (right < l && a[right] > a[max]) max = right; if (max !== i) { [a[max], a[i]] = [a[i], a[max]]; heapify(a, max); } }; for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i); for (i = a.length - 1; i > 0; i--) { [a[0], a[i]] = [a[i], a[0]]; l--; heapify(a, 0); } return a; }; heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]
const countSubstrings = (str, searchValue) => { let count = 0, i = 0; while (true) { const r = str.indexOf(searchValue, i); if (r !== -1) [count, i] = [count + 1, r + 1]; else return count; } }; countSubstrings('tiktok tok tok tik tok tik', 'tik'); // 3 countSubstrings('tutut tut tut', 'tut'); // 4
• Jan 26, 2023 •AustinLeath
0 likes • 5 views
function printHeap(heap, index, level) { if (index >= heap.length) { return; } console.log(" ".repeat(level) + heap[index]); printHeap(heap, 2 * index + 1, level + 1); printHeap(heap, 2 * index + 2, level + 1); } //You can call this function by passing in the heap array and the index of the root node, which is typically 0, and level = 0. let heap = [3, 8, 7, 15, 17, 30, 35, 2, 4, 5, 9]; printHeap(heap,0,0)
0 likes • 2 views
const getSubsets = arr => arr.reduce((prev, curr) => prev.concat(prev.map(k => k.concat(curr))), [[]]); // Examples getSubsets([1, 2]); // [[], [1], [2], [1, 2]] getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]