0

LZWデコンプレッサをphpにあるJSendからjavascriptに変換しようとしていますが、理解できない関数に到達しました。

 private static function decompressLZW($aCodes) 
  {
    $sData = '';
    $oDictionary = range("\x0000", "\xff");
    foreach ($aCodes as $sKey => $iCode) 
    {
      $sElement = $oDictionary[$iCode]; 
      if (!isset($sElement))
          $sElement = $sWord . $sWord[0];
      $sData .= $sElement;
      if ($sKey)
          $oDictionary[] = $sWord . $sElement[0];
      $sWord = $sElement;
    }
    return $sData;
  }

これは私がこれまでにjavascriptで持っているものですが、これをjavascriptで実行すると、sWord定義されていないという文句が表示され、php関数を見ると、これがエラーを生成しない方法がわかりませんか?

これが私がこれまでにjavscriptに持っているものです:

function decompressLZW(aCodes) {
  var sData = '';
  var oDictionary = [];

  for (var i = 0; i < 256; i++) {
    oDictionary[String.fromCharCode(i)] = i; 
  }

  for(var i=0, iLn = aCodes.length; i < iLn; i++) {
    var sElement = oDictionary[aCodes[i]];

    if(!sElement) {
      sElement = sWord + sWord[0];
    }

    //some magic needs to happen here
  }

  return sData;
}
4

1 に答える 1

1

Well its kind of bad IMO but.... $sWord is essentially $sElement which is defined near the end of the iteration. They are counting on the first two if statements be true only after the at least a single run of the loop in which case $sWord would be the same as the previous iteration's $sElement.

Im not sure what the significance of that assumption is but if it were me i would still test for the existence of $sWord and throw an exception if that happened (even if it should theoretically never happen)...

So you need to figure out why sElement = oDictionary[aCodes[i]]; isnt evaluating to something truthy. It may be as simple as testing angainst undefined (which is more like doing isset()) instead of doing loose falsy check.

if(sElement === undefined) {
  sElement = sWord + sWord[0];
}
于 2012-10-30T22:12:33.227 に答える