简体   繁体   中英

what is the i and 0 doing here? can anybody explain?

I am taking the challenges from code-wars and I am looking at a solution and I don't understand it. Can somebody explain what s is doing as well as o ?

function duplicateEncode(word) {
  word = word.toLowerCase();
  var c = '', s = '', o = '';

  for (i = 0; i < word.length; i++) {
    s = word.slice(i + 1);
    o = s + word.slice(0, i);
    c += (o.indexOf(word[i]) > -1) ? ')' : '(';
  }

  return c;
}

From String.prototype.slice MDN documentation :

beginIndex

The zero-based index at which to begin extraction. If negative, it is treated as strLength + (beginIndex) where strLength is the length of the string (for example, if beginIndex is -3 it is treated as strLength - 3). If beginIndex is greater than or equal to the length of the string, slice() returns an empty string.

endIndex

Optional. The zero-based index before which to end extraction. The character at this index will not be included. If endIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as strLength + endIndex where strLength is the length of the string (for example, if endIndex is -3 it is treated as strLength - 3).

    s = word.slice(i + 1);
    o = s + word.slice(0, i);

these two lines get what's after the current character and what's before it and concatenate these two pieces. In other words, they build a string equal to the source string with the current char omitted. For example, if word is abcde and i=2 , then o will be de + ab = deab . Of course, they could have simply written

    o = word.slice(0, i) + word.slice(i + 1)

with the same effect.

As a side note, this algorithm appears quite inefficient as it builds word.length temporary strings just to check the uniqueness. A more idiomatic approach would be to use (last)indexOf along the lines of

function duplicateEncode(word) {
    let w = [...word.toLowerCase()];
    return w
        .map(c => w.indexOf(c) === w.lastIndexOf(c) ? '(' : ')')
        .join('')
}

s will contain all the characters in word after the character at the current iteration

o will contain all the characters in word except the one at the current iteration ( s + [all the characters in word from start till the one at the current iteration]).

This means that the (o.indexOf(word[i]) > -1 ) expression will only be true if the character at the current iteration has a duplicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM