[关闭]
@lizlalala 2015-12-05T22:05:40.000000Z 字数 2406 阅读 1463

codewars 3

codewars

@(高程)[codewars]


1,problem 1——Autocomplete! Yay!

It's time to create an autocomplete function! Yay!

The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return an empty array.

Example:

autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport']

For this kata, the dictionary will always be a valid array of strings. Please return all results in the order given in the dictionary, even if they're not always alphabetical. The search should NOT be case sensitive, but the case of the word should be preserved when it's returned.

For example, "Apple" and "airport" would both return for an input of 'a'. However, they should return as "Apple" and "airport" in their original cases.

Important note:

Any input that is NOT a letter should be treated as if it is not there. For example, an input of "$%^" should be treated as "" and an input of "ab*&1cd" should be treated as "abcd".

My solutions:

note:
* []空数组无法使用join()方法,因此要进行1处的判断
* string没有startWith的函数,因此需要用indexOf来替代。

  1. function autocomplete(input, dictionary){
  2. input = input.match(/[a-z]/gi)||[]; //1
  3. validInput = input.join("");
  4. var result = dictionary.filter(function(value){
  5. return value.toLowerCase().indexOf(validInput.toLowerCase())== 0;
  6. });
  7. return result.length<=5?result:result.slice(0,5);
  8. }
good solutions


2,problem2

Take the following IPv4 address: 128.32.10.1 This address has 4 octets
where each octet is a single byte (or 8 bits).

1st octet 128 has the binary representation: 10000000 2nd octet 32 has
the binary representation: 00100000 3rd octet 10 has the binary
representation: 00001010 4th octet 1 has the binary representation:
00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001

Because the above IP address has 32 bits, we can represent it as the
32 bit number: 2149583361.

Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an
IPv4 address and returns a 32 bit number.

ipToInt32("128.32.10.1") => 2149583361

My solutions:
  1. function ipToInt32(ip){
  2. return ip.split(".").reduce(function(sum,cur,index){
  3. return sum+= parseInt(cur)*Math.pow(256,(3-index));
  4. },0);
  5. }

3,problem3

My solutions:
  1. function createPhoneNumber(numbers){
  2. var pattern = /(\d{3})(\d{3})(\d+)/;
  3. if(pattern.test(numbers.join("")))
  4. {
  5. return "("+RegExp.$1+") "+RegExp.$2+"-"+RegExp.$3;
  6. }

note:
* $属性只能与test、match等在同一作用域才行,比如if语句,或者string的replace中,如:

  1. numbers.slice(0,3).join("").replace(/(\d+)/g,"($1)")

然后可以以利用replace进行替换,方法二:

  1. function createPhoneNumber(numbers){
  2. return numbers.join('').replace(/(...)(...)(.*)/, '($1) $2-$3');
  3. }
good/clever solutions

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注