LoginSignup
1
1

More than 5 years have passed since last update.

[Javascriptメモ] prototypeを使ってOOPっぽく書く

Posted at

問題

文字列がある。この文字列を連続したものにするために加える必要がある文字を返せ。

例えば

abce -> b
abcdefghjklmno -> i
bcd -> undefined(連続してるので何も返さない)
yz -> undefined(上と同様)

jasmineのテストコードは以下

describe('description', function() {
    it('description', function() {
        expect(fearNotLetter('abce')).toEqual('d');
        expect(fearNotLetter('abcdefghjklmno')).toEqual('i');
        expect(fearNotLetter('bcd')).toEqual(undefined);
        expect(fearNotLetter('yz')).toEqual(undefined);
    });
});

出展: FreeCodeCampこの問題から

pseudocode

1 文字列から文字配列を作製
2 文字配列の最初と最後の文字コードをとる
1-1 文字配列をすべて文字コードにした配列を作る
2-1 最初と最後の文字コードから連続した文字コードの配列を作る

1-1 と 2-1 を比較して片方にしか無い物を返す

(あんま効率よくないですね。本当はもっといいやり方があるみたいです。)

解法1 ベタ書き


var _ = require('underscore');

function fearNotLetter(str) {
    var strAr = _.toArray(str);
    var charFirst = strAr[0].charCodeAt();
    var charLast = _.last(strAr).charCodeAt();
    var charAr = _.map(strAr, function(value) {
        return value.charCodeAt();
    });
    var compareAr = _.range(charFirst, charLast + 1);
    var resultChar = _.difference(compareAr, charAr).join('');
    if (resultChar === '') {
        return undefined;
    }
    return String.fromCharCode(resultChar);
}

varだらけで見栄えが良くないですね。
これだと例えば「underscoreを使わないで記述せよ」と言われた時にものすごくやりづらそうです。

解法2 prototypeを使ってみる

var _ = require('underscore');

function Runner(str) {
    this.strAr = _.toArray(str);
    this.charFirst = this.strAr[0].charCodeAt();
    this.charLast = _.last(this.strAr).charCodeAt();
    this.charAr = this.generateCharAr();
    this.compareAr = this.generateCompAr();
    this.resultChar = this.generateResuChar();
}

Runner.prototype.generateCharAr = function() {
    return _.map(this.strAr, function(value) {
        return value.charCodeAt();
    });
};

Runner.prototype.generateCompAr = function() {
    return _.range(this.charFirst, this.charLast);
};

Runner.prototype.generateResuChar = function() {
    return _.difference(this.compareAr, this.charAr).join('');
};

function fearNotLetter(str) {
    var doRun = new Runner(str);
    if (doRun.resultChar === '') {
        return undefined;
    }
    return String.fromCharCode(doRun.resultChar);
}

少しマシになったと思います。

補足

FreeCodeCampはHTMLとJSを学ぶのにとても素晴らしいサイトだと思います。
CodeAcademy形式でCodeAcademyよりも難しい問題がたくさんあります。
http://www.freecodecamp.com/

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1