Tag · JavaScript

Born to be chained | 4kyu

  • 对于 Object 的遍历;

Details

Function composition is a powerful technique. For example:

function sum(x, y) {
  return x + y;
}

function double(x) {
  return sum(x, x);
}

function minus (x, y) {
  return x - y;
}

function addOne(x) {
  return sum(x, 1);
}

double(sum(2, 3)); // 10

But in complex expressions, composition may be difficult to understand. For example:

double(double(addOne(sum(7, minus(sum(5, sum(4, 5)), 4))))); // 72

In this kata, we will implement a function that allows us to perform this by applying a fluid style:

c.sum(4, 5).sum(5).minus(4).sum(7).addOne().double().double().execute(); // 72

Your job is implement the chain function:

function chain(fns) {
}

var c = chain({sum: sum, minus: minus, double: double, addOne: addOne});

As you can see, this function receives the methods to be chained and returns an object that allows you to call the chained methods. The result is obtained by calling the executemethod.

Chained functions receive an arbitrary number of arguments. The first function in the chain receives all its arguments. In the other functions, the first argument is the result of the previous function and then it only receives the remainder arguments (second, third, etc.). The tests always pass the appropriate arguments and you do not have to worry about checking this.

Note that the chain can be reused (the internal state is not stored):

Argument Mapper | 5kyu

Details

As part of a broader functionality you need to develop an argument mapper.

The function receives a function object as first parameter and an unknown number of arguments [zero to many]. You have to return an associative array that maps the name of an argument and its related value.

The usage is:

function func1(arg1, arg2) { ... }

var map = createArgumentMap(func1,'valueOfArg1', 'valueOfArg2');
console.log(map['arg1']);  // writes 'valueOfArg1'
console.log(map['arg2']);  // writes 'valueOfArg2'

The passed values are in the same order as they appear in the function object.

Invalid inputs, e.g. non-function objects, or wrong number of arguments, are not considered.

Hajime!

@wraps | 6kyu

要点

  • decorator 装饰器用法
  • tryexceptelse control flow
  • getattr()setattr()
  • __dict__.update()

Details

Implement the functools.wraps decorator, which is used to preserve the name and docstring of a decorated function. Your decorator must not modify the behavior of the decorated function. Here’s an example :

def identity(func):
  @wraps(func)
  def wrapper(*args, **kwargs):
    """Wraps func"""
    return func(*args, **kwargs)
  return wrapper

@identity
def return_one():
  """Return one"""
  return 1

return_one.__name__ == 'return_one' # If wraps hadn't been used, __name__ would be equal to 'wrapper'
return_one.__doc__ == 'Return one' # If wraps hadn't been used, __doc__ would be equal to 'Wraps func'

Note: of course, you may not use the functools module for this kata.

题目要求,经过一次二重的装饰器,保留原来函数的 __name____doc__。二重装饰器 decorator,就是用一个 decorator 去 decorate 另一个 decorator。该二重装饰器装饰后的函数, 输出的是一重装饰器装饰过的函数,但是 __name____doc__ 得到保留,及为原函数的值。

依照题目给的例子,就是输出是被 decorator wraps 修饰过的 wrapper 函数,即函数主体和功能还是 wrapper,但因为被 wraps 装饰了,输出的 wrapper 函数的 __name____doc__ 值为原函数 return_one 的值。

Default Arguments | 4kyu

Details

Write a function defaultArguments. It takes a function as an argument, along with an object containing default values for that function’s arguments, and returns another function which defaults to the right values.

You cannot assume that the function’s arguments have any particular names.

You should be able to call defaultArguments repeatedly to change the defaults.

function add(a,b) { return a+b;};

var add_ = defaultArguments(add,{b:9});
add_(10); // returns 19
add_(10,7); // returns 17
add_(); // returns NaN

add_ = defaultArguments(add_,{b:3, a:2});
add_(10); // returns 13 now
add_(); // returns 5

add_ = defaultArguments(add_,{c:3}); // doesn't do anything, since c isn't an argument
add_(10); // returns NaN
add_(10,10); // returns 20

HINT: This problem requires using Fuction.prototype.toString() in order to extract a function’s argument list

Hexo Theme 开发不完全记录

决定建立一个静态 Blog,已经是 2016 年的事了。在那之前,也就是在 2016 年 4 月 5 日,自己曾经使用 Pelican 进行过短暂的尝试。生活在互联网时代,当你决定将一切电子化,义无反顾地投入比特的世界时,最大的好处便是,这以后发生的每一起事件,都有着清楚的记录。建立 Blog 这件事也不例外。但仅过 1 天,我就删除了 github 上的 repo。当时的自己这样写道:

两天的尝试发现:没有足够的知识积累,挑战就是「摸着石头过河」,到处都是困难,耐心被一点一点消磨,直到像一只无头苍蝇乱撞,而无法再耐心地解决问题。所以,博客平台搭建计划暂停。

那时自己才刚开始学 Python,也才刚开始接触 Github。其他方面更是经验甚少,处处碰壁。一年以后, 2017 年 3 月,自己使用 Hexo 建立了这个 Blog,并在 Godaddy 上购买了域名,采用 Hexo 预置主题 Next 。全面,简洁,美观大方。这个主题足够好用。当时的主题并不多,所以经常看到其他使用 Hexo 搭建的 Blog ,往往都是差不多的样式,我当时也只是改了以下 banner,才显得稍有不同。这也让我想试着自己去写一个主题。

目前看到的这个 theme 所有样式,并非我本人设计。它来自于一款付费的 WordPress theme typology。我是一次偶然的机会看到它。考虑到可能的版权问题。自己可能不会把它发布到 Themes | Hexo 或开源到 Github 上(无法联系到这个 theme 的作者)。以下我所做的大部分工作,不过是以 Hexo 的形式对 typology 的再现。为了方便。我把这个模仿之作命名为 hagoromo(羽衣)。至于为什么会叫这个名字,Google 会给你答案。

Catching Car Mileage Numbers

Kata

“7777…8?!??!“, exclaimed Bob, “I missed it again! Argh!” Every time there’s an interesting number coming up, he notices and then promptly forgets. Who doesn’t like catching those one-off interesting mileage numbers?

Let’s make it so Bob never misses another interesting number. We’ve hacked into his car’s computer, and we have a box hooked up that reads mileage numbers. We’ve got a box glued to his dash that lights up yellow or green depending on whether it receives a 1 or a 2 (respectively).

It’s up to you, intrepid warrior, to glue the parts together. Write the function that parses the mileage number input, and returns a 2 if the number is “interesting” (see below), a 1 if an interesting number occurs within the next two miles, or a 0 if the number is not interesting.

Wrapped Function

Kata

Create a function method that allow you to wrap an existing function. The method signature would look something like this:

Usage Example:

function speak(name){
   return "Hello " + name;
}

speak = speak.wrap(function(original, yourName, myName){
   greeting = original(yourName);
   return greeting + ", my name is " + myName;
})

var greeting = speak("Mary", "Kate");

ES5 Generators(i) 和闭包 closure

Kata

Description:

This is the first part of three (part2, part3).

Generators and Iterators are new ES6 features that will allow things like this:

function* fibonacci() {
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

Using them in this way, we can do amazing things:

let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8

This is powerful, but until a few months later, ES6 will not be born.

The goal of this kata is to implement pseudo-generators with ES5.

分类

标签