DESCRIPTION

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

arrayDiff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

arrayDiff([1,2,2,2,3],[2]) == [1,3]

SOLUTION

  • 方法一:
1
2
3
function arrDiff(a, b) {
return a.filter((item) => !b.includes(item));
}
阅读全文 »


DESCRIPTION

Given an integral number, determine if it’s a square number:

In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

The tests will always use some integral number, so don’t worry about that in dynamic typed languages.

Examples

1
2
3
4
5
6
-1  =>  false
0 => true
3 => false
4 => true
25 => true
26 => false

SOLUTION

  • 方法一:
1
2
3
4
5
6
var isSquare = function (n) {
// 求平方根并取整
let roundSqrt = Math.round(Math.sqrt(n));
// 判断平方根相乘的结果是否与传入的数值相等
return n === roundSqrt * roundSqrt;
};
阅读全文 »


DESCRIPTION

In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

Example

1
2
3
filter_list([1, 2, "a", "b"]) == [1, 2];
filter_list([1, "a", "b", 0, 15]) == [1, 0, 15];
filter_list([1, 2, "aasf", "1", "123", 123]) == [1, 2, 123];

SOLUTION

  • 数组的 filter() 方法
1
2
3
4
function filter_list(l) {
// Return a new array with the strings filtered out
return l.filter((word) => typeof word === "number");
}
阅读全文 »


DESCRIPTION

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”.

Note: for this kata y isn’t considered a vowel.

SOLUTION

  • 方法一:字符串的 replace()replaceAll() 方法都可,这两个方法都是返回一个新的字符串。

replace() 字符串模式只会被替换一次。要执行全局搜索和替换,请使用带有 g 标志的正则表达式或使用 replaceAll()。

1
2
3
4
5
6
function disemvowel(str) {
let regex = /aeiou/gi;
let result = str.replace(regex, "");
// let result = str.replaceAll(regex, "");
return result;
}
阅读全文 »


for…in 语句以任意顺序迭代一个对象的除 Symbol 以外的可枚举属性,包括继承的可枚举属性。

语法

1
2
3
4
5
for (variable in object) {
if(object.hasOwnProperty(variable) {
...
}
}

variable
在每次迭代时,variable 会被赋值为不同的属性名。

object
非 Symbol 类型的可枚举属性被迭代的对象。

阅读全文 »
0%