Loading...
More JavaScript Posts
arr = [] // empty arrayconst isEmpty = arr => !Array.isArray(arr) || arr.length === 0;// ExamplesisEmpty([]); // trueisEmpty([1, 2, 3]); // false
router.post("/", async (req, res) => {const { email, password } = req.body;try {if (!email) return res.status(400).json({ msg: "An email is required" });if (!password)return res.status(400).json({ msg: "A password is required" });const user = await User.findOne({ email }).select("_id password");if (!user) return res.status(400).json({ msg: "Invalid credentials" });const match = await bcrypt.compare(password, user.password);if (!match) return res.status(400).json({ msg: "Invalid credentials" });const accessToken = genAccessToken({ id: user._id });const refreshToken = genRefreshToken({ id: user._id });res.cookie("token", refreshToken, {expires: new Date(Date.now() + 604800),httpOnly: true,});res.json({ accessToken });} catch (err) {console.log(err.message);res.status(500).json({ msg: "Error logging in user" });}});
const compactObject = val => {const data = Array.isArray(val) ? val.filter(Boolean) : val;return Object.keys(data).reduce((acc, key) => {const value = data[key];if (Boolean(value))acc[key] = typeof value === 'object' ? compactObject(value) : value;return acc;},Array.isArray(val) ? [] : {});};const obj = {a: null,b: false,c: true,d: 0,e: 1,f: '',g: 'a',h: [null, false, '', true, 1, 'a'],i: { j: 0, k: false, l: 'a' }};compactObject(obj);// { c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }
function sortNumbers(arr) {return arr.slice().sort((a, b) => a - b);}const unsortedArray = [4, 1, 9, 6, 3, 5];const sortedArray = sortNumbers(unsortedArray);console.log("Unsorted Numbers:", unsortedArray);console.log("\n");console.log("Sorted Numbers:", sortedArray);
const hammingDistance = (num1, num2) =>((num1 ^ num2).toString(2).match(/1/g) || '').length;hammingDistance(2, 3); // 1
const linearSearch = (arr, item) => {for (const i in arr) {if (arr[i] === item) return +i;}return -1;};linearSearch([2, 9, 9], 9); // 1linearSearch([2, 9, 9], 7); // -1