• Nov 19, 2022 •CodeCatch
0 likes • 0 views
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
arr = [] // empty array const isEmpty = arr => !Array.isArray(arr) || arr.length === 0; // Examples isEmpty([]); // true isEmpty([1, 2, 3]); // false
• Feb 5, 2021 •LeifMessinger
0 likes • 2 views
class Timer{ start(){ this.startTime = Date.now(); } stop(){ const dt = Date.now() - this.startTime; console.log(dt); return dt; } getExecTime(fun, asynchronous){ return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun); } getSyncExecTime(fun){ this.start(); fun(); return this.stop(); } async getAsyncExecTime(fun){ this.start(); await fun(); return this.stop(); } static average(fun, numTimes, asynchronous = false){ const times = []; const promises = []; let timer = new Timer(); if(asynchronous){ for(let i = 0; i < numTimes; i++){ timer.getAsyncExecTime(fun); } }else{ for(let i = 0; i < numTimes; i++){ timer.getSyncExecTime(fun); } } return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length); } static async timeAsync(fun, numTimes){ if(numTimes <= 1) return new Timer().getAsyncExecTime(fun); const promises = []; let timer = new Timer(true); for(let i = 0; i < numTimes; i++){ promises.push(fun().catch((e)=>{})); } try{ await Promise.all(promises).catch((e)=>{}); }catch(e){ //do absolutely nothing } return timer.stop(); } constructor(start = false){ if(start) this.start(); } }
• Sep 13, 2023 •C S
0 likes • 11 views
/** * @param {number[]} nums * @return {number[]} */ var productExceptSelf = function(nums) { var output = []; var leftMult = 1; var rightMult = 1; for (var i=nums.length - 1; i >= 0; i--) { output[i] = rightMult; rightMult *= nums[i]; console.log({output: JSON.stringify(output), i}) } for (var j=0; j < nums.length; j++) { output[j] *= leftMult; leftMult *= nums[j]; console.log({output: JSON.stringify(output), j}) } return output; }; console.log(productExceptSelf([1, 2, 3, 4]))
• Mar 11, 2021 •C S
1 like • 1 view
if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "client", "build", "index.html")); }); }
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; hammingDistance(2, 3); // 1