1.题目描述
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (‘_‘).

Examples:

1
2
3
* 'abc' =>  ['ab', 'c_']
* 'abcdef' => ['ab', 'cd', 'ef']

2.我的解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function solution(str) {
const pair = [];
// 1.将字符串两两分割存入数组
// Array.prototype.slice(start,end)
// 如果 end >= array.length 或者省略了 end,则使用 array.length,提取所有元素直到末尾
for (let i = 0; i < str.length; i += 2) {
pair.push(str.slice(i, i + 2));
}
// 2.如果字符串长度为奇数,则为 pair 最后一个元素添加下划线
if (str.length % 2 === 1) {
pair[pair.length - 1] += "_";
}
return pair;
}
阅读全文 »


1.题目描述

编写一个类,它允许获取和设置键-值对,并且每个键都有一个 过期时间 。

该类有三个公共方法:

set(key, value, duration) :接收参数为整型键 key 、整型值 value 和以毫秒为单位的持续时间 duration 。一旦 duration 到期后,这个键就无法访问。如果相同的未过期键已经存在,该方法将返回 true ,否则返回 false 。如果该键已经存在,则它的值和持续时间都应该被覆盖。

get(key) :如果存在一个未过期的键,它应该返回这个键相关的值。否则返回 -1 。

count() :返回未过期键的总数。

阅读全文 »

1.题目描述

请你编写一个函数,它接受一个异步函数 fn 和一个以毫秒为单位的时间 t。它应根据限时函数返回一个有 限时 效果的函数。函数 fn 接受提供给 限时 函数的参数。

限时 函数应遵循以下规则:

如果 fn 在 t 毫秒的时间限制内完成,限时 函数应返回结果。
如果 fn 的执行超过时间限制,限时 函数应拒绝并返回字符串 “Time Limit Exceeded” 。

阅读全文 »


1.题目描述

现给定一个函数 fn ,一个参数数组 args 和一个以毫秒为单位的超时时间 t ,返回一个取消函数 cancelFn 。

在经过 t 毫秒的延迟后,应该调用 fn 函数,并将 args 作为参数传递。除非 在 t 毫秒的延迟过程中,在 cancelT 毫秒时调用了 cancelFn。并且在这种情况下,fn 函数不应该被调用。

阅读全文 »


1.题目描述

请你编写一个函数,它接收一个函数数组 [f1, f2, f3,…, fn] ,并返回一个新的函数 fn ,它是函数数组的 复合函数 。

[f(x), g(x), h(x)] 的 复合函数 为 fn(x) = f(g(h(x))) 。

一个空函数列表的 复合函数 是 恒等函数 f(x) = x 。

你可以假设数组中的每个函数接受一个整型参数作为输入,并返回一个整型作为输出。

2.题解

传统方法:

1
2
3
4
5
6
7
8
9
10
11
var compose = function (functions) {
return function (x) {
for (let i = functions.length - 1; i >= 0; i--) {
x = functions[i](x);
}
return x;
};
};

const fn = compose([(x) => x + 1, (x) => 2 * x]);
console.log(fn(4)); // 9
阅读全文 »
0%