= Javascript 常用技巧
== 如何确认给定的日期是否是当前日期
[source,javascript]
----
const isCurrentDay = (date) => new Date().toISOString().slice(0, 10) === date.toISOString().slice(0, 10);
----

== 如何确定一个日期是否在两个日期之间
[source,javascript]
----
const isBetweenTwoDates = ( min, max, date) => date.getTime() >= min.getTime() && date.getTime() <= max.getTime();
----

== 如何确认一个日期是否在周末
[source,javascript]
----
const isWeekend = ( date ) => date.getDay() === 6 || date.getDay() === 0;
----

== 检查一个日期是否在某年内
[source,javascript]
----
const isInAYear = (date, year) => date.getUTCFullYear() === new Date(`${year}`).getUTCFullYear();
----

== 将小时转换为 AM-PM 格式
[source,javascript]
----
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
----

== 将句子的第一个字母大写
[source,javascript]
----
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`;
----

== 将英文字母转成对应的emoji形式
[source,javascript]
----
const letterToEmoji = c => String.fromCodePoint(c.toLowerCase().charCodeAt() + 127365);
----

== 如何判断一个字符串是不是回文
[source,javascript]
----
const isPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
----

== 如何计算一个数的阶乘
[source,javascript]
----
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
----

== 如何计算一个斐波那契数列第N项（Fibonacci）？
[source,javascript]
----
const getFibonacci = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
----

== 数组复制
[source,javascript]
----
const copyToArray = (arr) => [...arr];
----

== 简单数组去重
[source,javascript]
----
const getUnique = (arr) => [...new Set(arr)];
----

== 洗牌算法（随机数组）
[source,javascript]
----
const shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
----

== 按属性对数组进行聚合分组（类似 SQL 的 group by）
[source,javascript]
----
const groupBy = (arr, groupFn) =>
arr.reduce( (grouped, obj) =>
           ({...grouped,
             [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }),
           {});
----

== 反转字符串
[source,javascript]
----
const reverseString = (str) => str.split('').reverse().join('');
----

== 检查两个数组是否包含相同的值
[source,javascript]
----
const containSameValues= (arr1, arr2) => arr1.sort().join(',') === arr2.sort().join(',');
----

== 温度转换(符号℉。华氏度 = 32+ 摄氏度× 1.8)
[source,javascript]
----
const toFahrenheit= (celsius) => (celsius * 9)/5 + 32;
const toCelsius= (fahrenheit) => (fahrenheit - 32) * 5 / 9;
----

== 如何清除浏览器中的所有 cookie
[source,javascript]
----
const clearAllCookies = () => document.cookie.split(';')
.forEach((c) => (document.cookie = c.replace(/^ +/, '')
                .replace(/=.*/, `=;expires=${new Date().toUTCString()};
                path=/`)));
----

== 如何从 HEX 转换为 RGB 色值
[source,javascript]
----
const toRGB= (hex) =>
    hex
        .replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,
                 (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`)
        .substring(1)
        .match(/.{2}/g)
        .map((x) => parseInt(x, 16));
----

== 如何将 RGB 转换为 HEX
[source,javascript]
----
const toHEX = (r,g,b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
----

== 检查函数是否为异步函数
[source,javascript]
----
const isAsyncFunction = (f) => Object.prototype.toString.call(f) === '[object AsyncFunction]';
----

== 如何确认代码是否在浏览器中运行
[source,javascript]
----
const runningInBrowser = typeof window === 'object' && typeof document === 'object';
----

== 如何确认代码是否在 Node 中运行
[source,javascript]
----
const runningInNode= typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
----

== 检测系统是否是暗模式
[source,javascript]
----
const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
----

== 滚动到顶部
[source,javascript]
----
const toTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
----

== 滚动到底部
[source,javascript]
----
const toBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
----

== 将 JSON 转换为 MAP
[source,javascript]
----
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
----

== 生成 128 位 UUID
[source,javascript]
----
const generateUUID = (a) => a?
      (a ^ ((Math.random() * 16) >> (a / 4))).toString(16):([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g,generateUUID);
----



