Skip to content

Instantly share code, notes, and snippets.

@ogawatti
Created September 25, 2018 03:56
Show Gist options
  • Save ogawatti/e98d423481df3e3ba101e87bf4e3ed91 to your computer and use it in GitHub Desktop.
Save ogawatti/e98d423481df3e3ba101e87bf4e3ed91 to your computer and use it in GitHub Desktop.
Rubyist が Javascripter になり始めてやらかしたこと (備忘録) ref: https://qiita.com/ogawatti/items/65a48564f64651ed3574
def hoge
"hogehoge"
end
hoge #=> "hogehoge"
function hoge() {
"hogehoge";
};
hoge(); //=> undefined
class Baz {
asyncMyFunc() {
return new Promise(resolve => {
setTimeout(() => { resolve("qux"); }, 3000);
});
};
async qux() {
let val = this.asyncMyFunc();
console.log(val); // => Promise { <pending> }
let val2 = await this.asyncMyFunc();
console.log(val2); // => "qux"
};
};
(new Baz).qux();
foo().then(result => {
bar().then(result => {
baz().then(result => {
// ...
});
});
});
let result
result = await foo()
result = await bar()
result = await baz()
async function piyo() {
await asyncFunc()
}
piyo()
Foo.new.three #=> 3
class Foo
def three; "3"; end
end
Foo.new.three #=> "3"
(new Foo).three(); //=> 3
Foo.prototype.three = function() { return "3" };
(new Foo).three(); //=> "3"
const expect = require('chai').expect
describe('Foo', () => {
beforeEach(() => {
// ...
})
let foo = new Foo
describe('#hoge()', () => {
it ('return "hogehoge"', () => {
expect(foo.hoge()).to.equal("hogehoge");
});
});
// 非同期関数のテスト
describe('#fuga()', () => {
it ('return "hogehoge"', async () => {
expect(await foo.fuga()).to.equal("fugafuga");
});
});
// shared_example 的に使える
function piyo() {
it ('return "piyopiyo"', () => {
expect(Foo.piyo()).to.equal("piyopiyo");
});
};
describe('#piyo()', piyo);
context('when ...', () => {
// ...
});
});
$ ./node_modules/.bin/mocha
Foo
#hoge()
✓ return "hogehoge"
#fuga()
✓ return "hogehoge" (1006ms)
#piyo()
✓ return "piyopiyo"
3 passing (1s)
def func(*args)
p args #=> ["a", "b", "c"]
end
func('a', 'b', 'c')
function func(...args) {
console.log(args)
}
func('a', 'b', 'c') //=> [ 'a', 'b', 'c' ]
class Array
def forEach(func)
self.each do |n|
func.call(n)
end
end
end
[1, 2, 3].forEach(lambda {|n|
puts n
})
[1, 2, 3].forEach((n) => {
console.log(n);
});
class Foo
def three; 3; end
def bar
[1, 2, 3].each do |n|
puts n * self.three #=> 3, 6, 9
end
end
end
Foo.new.bar
class Foo {
three() { return 3; };
bar() {
/*
[1, 2, 3].forEach(function(n) {
console.log(n * this.three()); //=> TypeError: Cannot read property 'three' of undefined
});
*/
// 関数式にthisを指定する
[1, 2, 3].forEach(function(n) {
console.log(n * this.three()); //=> 3, 6, 9
}, this);
// アロー関数を使う
[1, 2, 3].forEach(n => {
console.log(n * this.three()); //=> 3, 6, 9
});
}
}
(new Foo).bar()
setTimeout(() => {}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment