Js higher-order function solution with concise and easy to understand code


  • 10
    T

    reduce is just for this: take a list of strings and reduce them to one string

    var longestCommonPrefix = function(strs) {
        'use strict';
        if (strs === undefined || strs.length === 0) { return ''; }
        
        return strs.reduce((prev, next) => {
            let i = 0;
            while (prev[i] && next[i] && prev[i] === next[i]) i++;
            return prev.slice(0, i);
        });
    };

  • 0

    what a gorgeous solution!


  • 0
    L

    your solution concise,but I cant understand ,maybe its because i dont familiar with ES6.
    what prev,next stands for?


  • 0
    L

    I try to track prev & next in Chrome Debugger,but there is nothing i can see....


  • 0
    T

    @liuqiao The first argument in the callback function (prev) is the looping value. It's initial value is the second argument of reduce, which is default value in mine; prev get the returned value for each loop. next is a bad name, it should probably be named as currentVal or so because it means the current value in the array, like arr[i].

    In terms of the Chrome dev tool, I think you can set breakpoint at line let i = 0; and type prev or next in the console to see their values.

    Hope it helps :)


  • 0
    L

    @tinirlove thanks for your explaination, I got a lot from your solution.hope you can add some description next time :)


  • 0
    N

    @tinirlove said in Js higher-order function solution with concise and easy to understand code:

    return strs.reduce((prev, next) => {
        let i = 0;
        while (prev[i] && next[i] && prev[i] === next[i]) i++;
        return prev.slice(0, i);
    });
    

    I don't understand (return strs.reduce((prev, next) => {)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.