My personal website: Tuoba front inn ~ understand a ha. Here is the original address, if you find my article there is a mistake, please feel free to ridicule me, we learn together progress φ(>ω<*)

primers

If you want to be mundane, writing code for you can be Ctrl+C and Ctrl+V; Writing code can be an art if you are creative. We often come across some code snippets that are considered elegant and spiritual, and here are just some of the ones I’ve seen.

Below for the convenience of reading, I will put the code of the topic and mang fu solution together, elegant and spiritual solution at the bottom, I hope to cause a certain impact on you, the officers can try, the topic is not difficult.

Of course, there are thousands of roads to Rome, and perhaps your solution is better. If so, I hope you can show it in the comments section, let more people see ~

Note: All of the following titles are from CodeWars

Topic & Mang fu solution

  1. Create Phone Number

    Title: Write a function that takes an array of 10 integers (between 0 and 9) and returns a string of those numbers in the form of a phone number in the form of (123) 456-7890.

    Example:

    createPhoneNumber([1.2.3.4.5.6.7.8.9.0]) // => returns "(123) 456-7890"1111
    Copy the code

    Mang fu solution:

    const createPhoneNumber = n= > "(" + n[0] + n[1] + n[2] + ")" + n[3] + n[4] + n[5] + "-" + n[6] + n[7] + n[8] + n[9]
    Copy the code
  2. Find the odd int

    Given an array, find an odd number of occurrences.

    PS: there will always be only one integer that occurs odd times.

    Example:

    findOdd([1.1.2.2 -.5.2.4.4.- 1.2 -.5]); // => returns -1
    Copy the code

    Mang fu solution:

    function findOdd(A) {
        let count = 0;
        do {
            let i = A.splice(count,1.'p') [0];
            if(i ! = ='p') {let result = [i];
                A.forEach(function (e, index) {
                    if (e === i){
                        i === result[0]? result.pop(): result.push(i); A.splice(index,1.'p'); }});if (result.length > 0) {return result[0]
                }
            }
            count ++;
        } while (A.length > count);
    }
    Copy the code
  3. Who likes it?

    Title: You probably know the “like” system of Facebook and other sites. People can “like” blog posts, images or other items. We want to create a text that appears next to such an item.

    Implements a function whose input is an array containing the names of people who like the project. The return value is text in the following format:

    likes [] // must be "no one likes this"
    likes ["Peter"] // must be "Peter likes this"
    likes ["Jacob"."Alex"] // must be "Jacob and Alex like this"
    likes ["Max"."John"."Mark"] // must be "Max, John and Mark like this"
    likes ["Alex"."Jacob"."Mark"."Max"] // must be "Alex, Jacob and 2 others like this"
    Copy the code

    Mang fu solution:

    const likes = names= > {
        switch (names.length) {
            case 0: return 'no one likes this'
            case 1: return names[0] + ' likes this'
            case 2: return names[0] + ' and ' + names[1] + ' like this'
            case 3: return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'
            default: return names[0] + ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this'}}Copy the code
  4. Shortest Word

    Given a list of words, return the length of the shortest word.

    Strings are never empty, and you don’t need to consider different data types.

    Example:

    findShort("bitcoin take over the world maybe who knows perhaps") // Returns 3, since the shortest words are the and who, the length is 3
    Copy the code

    Mang fu solution:

    // It's not too rude
    const findShort = s= > s.split(' ').map(w= > w.length).sort((a,b) = > a-b)[0];
    Copy the code
  5. Sum of Digits / Digital Root

    Title: Create a function that calculates digital root.

    The digital root is the recursive sum of the digits in a number. Given n, take the sum of n digits. If the value is two digits or more, the recursion continues in this manner until one digit is produced, which is the digital root. This only applies to natural numbers.

    Example:

    digital_root(16) = >1 + 6= >7
    
    digital_root(942) = >9 + 4 + 2= >15. = >1 + 5= >6
    
    digital_root(132189) = >1 + 3 + 2 + 1 + 8 + 9= >24. = >2 + 4= >6
    
    digital_root(493193) = >4 + 9 + 3 + 1 + 9 + 3= >29. = >2 + 9= >11. = >1 + 1= >2
    Copy the code

    Mang fu solution:

    function digital_root(n) {
        let num = n;
        if (num < 10) {return num
        }else {
            return arguments.callee((num+' ').split(' ').reduce(function (a,b) {
                return parseInt(a) + parseInt(b)
            }))
        }
    }
    Copy the code

Elegance & spirituality

  1. Create Phone Number

    function createPhoneNumber(numbers){
        var format = "(xxx) xxx-xxxx";
        for(var i = 0; i < numbers.length; i++){
            format = format.replace('x', numbers[i]);
        }
        return format;
    }
    Copy the code

    Using a format template, replace all the X bits in the format by loop, elegant and readable, dazzling.

  2. Find the odd int

    const findOdd = (xs) = > xs.reduce((a, b) = > a ^ b);
    Copy the code

    My guess is that at least 70% of people are shocked. Remember, when was the last time you used bitwise operations? In this case, the reduce() and bitwise xor operation is used, which is equivalent to that all the digits that occur even times are xor or 0, and then the digits that occur odd times are xor or themselves.

  3. Who likes it?

    function likes (names) {
        var templates = [
            'no one likes this'.'{name} likes this'.'{name} and {name} like this'.'{name}, {name} and {name} like this'.'{name}, {name} and {n} others like this'
        ];
        var idx = Math.min(names.length, 4);
        
        return templates[idx].replace(/{name}|{n}/g.function (val) {
            return val === '{name}' ? names.shift() : names.length;
        });
    }
    Copy the code

    No need to explain this, use template strings, don’t silly manual spelling.

  4. Shortest Word

    function findShort(s){
        return Math.min.apply(null, s.split(' ').map(w= > w.length));
    }
    Copy the code

    Interview questions like the difference between Apply and Call often come up, but how many people have actually written code using them in their jobs?

  5. Sum of Digits / Digital Root

    function digital_root(n) {
        return (n - 1) % 9 + 1;
    }
    Copy the code

    The solution was a stroke of genius. For those of you who don’t understand it, it makes use of a theorem we learned in elementary school, “A number whose digits add up to a multiple of 9 is divisible by 9.” You probably don’t remember that, but you probably know that a number whose digits add up to a multiple of 3 is divisible by 3, and it’s the same thing. The reason why n minus 1 goes into 9 plus 1 is to prevent multiples of 9 from solving for 0.

summary

It’s amazing how these five pieces of code can be used to solve problems using replace, bit operations, template strings, apply and even the theorem that “all digits that add up to a multiple of nine are divisible by nine.”

Some moves are inspired and some moves can be learned. All we have to do is take what we can learn and use it for ourselves next time, that’s enough.

The resources

1. Create Phone Number

2. Find the odd int

3. Who likes it?

4. Shortest Word

5. Sum of Digits / Digital Root