JS 实现 python 中 Array.count

来源:互联网 发布:我知你非血肉之躯 编辑:程序博客网 时间:2024/06/04 17:44

来源

由codewar中一道题引发的惨案,题目原型如下:

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones – everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. [‘n’, ‘s’, ‘w’, ‘e’]). You know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don’t want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Note: you will always receive a valid array containing a random assortment of direction letters (‘n’, ‘s’, ‘e’, or ‘w’ only). It will never give you an empty array (that’s not a walk, that’s standing still!).

解析后大意是:

每次给你包含’w’||’s’||’e’||’n’的非空数组(元素代表东西南北方向),判断 长度==10 && 方向向量==(0,0)

python

利用 pythonArray.count 不知道有多好写哦2333:

def takeAWalk(walk):    return len(walk)==10 && walk.count('n')==walk.count('s') && walk.count('w')==walk.count('e')

哈哈,是不是 Pythonic 大法打遍天下2333.

JS

javascript没有 Array.count 这种东西,但是我们可以通过 filter 伪造一个:

let takeAWalk = function(walk) {    function count(val) {        return walk.filter((item) => {item == val;}).lenth;    }    return walk.length==10 && count('n')==count('s') && count('w')==count('e')}
原创粉丝点击