跳到主要内容

自定义函数

手写一个倒计时xx时xx分xx秒

function countDown(hours, minutes, seconds) {
let totalSeconds = hours * 3600 + minutes * 60 + seconds;

let timer = setInterval(() => {
if (totalSeconds <= 0) {
clearInterval(timer);
console.log('倒计时结束');
return;
}

let h = Math.floor(totalSeconds / 3600);
let m = Math.floor((totalSeconds % 3600) / 60);
let s = totalSeconds % 60;

console.log(`${h}${m}${s}`);

totalSeconds--;
}, 1000);
}

// 示例调用,设置 1 小时 30 分 10 秒倒计时
countDown(1, 30, 10);

写代码实现一个 cut 函数?(考察正则的用法)

function cut(str, pattern) {
// 使用正则表达式的replace方法移除匹配的部分
return str.replace(pattern, '');
}

// 示例使用
const text = "Hello, world! Hello, universe!";
const pattern = /Hello/g; // 正则表达式匹配所有"Hello"

const result = cut(text, pattern);
console.log(result); // 输出: ", world! , universe!"

开平方题

function mySqrt(x) {
if (x === 0 || x === 1) {
return x;
}
let left = 1, right = x, mid, sqrt;
while (left <= right) {
mid = Math.floor((left + right) / 2);
sqrt = x / mid;
if (sqrt === mid) {
return mid;
} else if (sqrt < mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}

类似 ['1.1.1.1.1', '6', '2.3.1', '2.1.1', '6.4.3.2'] 的版本号排序

function compareVersions(a, b) {
// 将版本号分割成数组
const versionA = a.split('.').map(Number);
const versionB = b.split('.').map(Number);

// 比较两个版本号数组
for (let i = 0; i < versionA.length || i < versionB.length; i++) {
// 如果数组长度不同,则较短的数组视为较小
if (versionA[i] === undefined) return -1;
if (versionB[i] === undefined) return 1;

// 比较当前数字
if (versionA[i] < versionB[i]) return -1;
if (versionA[i] > versionB[i]) return 1;
}

// 如果所有数字都相同,则认为版本号相同
return 0;
}

const versions = ['1.1.1.1.1', '6', '2.3.1', '2.1.1', '6.4.3.2'];
versions.sort(compareVersions);

console.log(versions); // 输出排序后的版本号数组

calc 的实现,即输出一个数的最多乘积的数组

function calc(arr) {
// 计算数组的总和
const totalSum = arr.reduce((sum, num) => sum + num, 0);
// 初始化一个数组来存储所有可能的乘积组合
const result = [];

// 动态规划求解
function dp(index, currentSum, currentProduct) {
// 如果已经到达数组末尾,检查当前乘积是否等于总和
if (index === arr.length) {
if (currentSum === totalSum) {
result.push(currentProduct);
}
return;
}

// 不选择当前元素
dp(index + 1, currentSum, currentProduct);

// 选择当前元素
dp(index + 1, currentSum + arr[index], currentProduct * arr[index]);
}

// 从数组的第一个元素开始递归
dp(0, 0, 1);

return result;
}

// 示例使用
const inputArray = [1, 2, 3, 4];
const outputArray = calc(inputArray);
console.log(outputArray); // 输出所有可能的乘积组合

TS 实现两个数相加(TS 函数重载)

// 函数重载声明
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
// 这里是函数实现,它将根据传入的参数类型来决定如何相加
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else if (typeof a === 'string' && typeof b === 'string') {
return a + b;
} else {
throw new Error('参数类型不匹配');
}
}

// 使用示例
const sum = add(1, 2); // 返回 3
const concatenated = add('Hello, ', 'world!'); // 返回 'Hello, world!'

红绿灯问题,先用JS写,后用react实现

<div id="traffic-light">red</div>

<script>
function trafficLight() {
const colors = ['red', 'yellow', 'green'];
let index = 0; // 当前颜色的索引
function changeLight() {
const light = document.getElementById('traffic-light');
light.innerText = colors[index];
index = (index + 1) % colors.length; // 更新索引,循环切换颜色
}
// 每隔一段时间切换一次颜色
setInterval(changeLight, 3000); // 每3秒切换一次颜色
}
trafficLight();
</script>
//2
function TrafficLight() {
const colors = ['red', 'yellow', 'green'];
const [currentColor, setCurrentColor] = useState('red');
const [index, setIndex] = useState(0);
useEffect(() => {
const changeLight = () => {
setIndex((index + 1) % colors.length)
setCurrentColor(colors[index]);
};
const intervalId = setInterval(changeLight, 3000);
return () => clearInterval(intervalId);
}, [currentColor]);
return (
<div id="traffic-light" style={{ color: currentColor }}>
{currentColor}
</div>
);
}

一定规律的点阵:第一行为 3 个点分布居中排列,第二行为 2 个点分布居中排列,第三行为 3 个点分布居中排列... 算出该点阵共有多少个点

function countDots(n) {
// 计算完整周期的数量
const fullCycles = Math.floor(n / 2);
// 计算最后一个不完整周期中的点数
const lastCycleDots = n % 2 === 0 ? 2 : 3;
// 计算总点数
return fullCycles * 5 + lastCycleDots;
}

// 示例:计算前10行的点数
console.log(countDots(10)); // 输出:27(5个完整周期,每个周期5个点,加上最后一个周期的2个点)

手机号

// 适合纯11位手机
const splitMobile = (mobile, format = '-') => {
return String(mobile).replace(/(?=(\d{4})+$)/g, format)
}
// 适合11位以内的分割
const splitMobile2 = (mobile, format = '-') => {
return String(mobile).replace(/(?<=(\d{3}))/, format).replace(/(?<=([\d\-]{8}))/, format)
}

const match = (mobile) => {
return String(mobile).match(/^1[3-9]\d{9}$/);
}

console.log(splitMobile(18379802267))
console.log(splitMobile2(18379876545))
console.log(match(4))
console.log(match(18379802267))

实现一个线程池

class ThreadPool {
constructor(size) {
this.size = size;
this.tasks = [];
this.workers = [];
this.running = 0;
}

addTask(task) {
this.tasks.push(task);
this.runNext();
}

runNext() {
if (this.running < this.size && this.tasks.length) {
const task = this.tasks.shift();
this.running++;
task().then(() => {
this.running--;
this.runNext();
});
}
}
}

实现一个管道函数

function pipe(...fns) {
return (input) => fns.reduce((acc, fn) => fn(acc), input);
}

// Example usage
const addOne = x => x + 1;
const double = x => x * 2;
const pipedFunction = pipe(addOne, double);
console.log(pipedFunction(2)); // 6

大文件上传

async function uploadFile(file) {
const chunkSize = 1 * 1024 * 1024; // 1MB
const totalChunks = Math.ceil(file.size / chunkSize);
for (let i = 0; i < totalChunks; i++) {
const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
await uploadChunk(chunk, i); // 这里你需要实现 uploadChunk 函数
}
}

async function uploadChunk(chunk, index) {
const formData = new FormData();
formData.append('file', chunk);
formData.append('index', index);
// 使用 fetch 或其他方式上传
await fetch('/upload', {
method: 'POST',
body: formData
});
}