Skip to content

Commit 5c55196

Browse files
committed
Improve once() method.
github: #37
1 parent 5e92586 commit 5c55196

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

src/main/java/com/github/underscore/$.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/*
22
* The MIT License (MIT)
33
*
4-
* Copyright 2015 Valentyn Kolesnikov
4+
* Copyright 2016 Valentyn Kolesnikov
55
*
66
* Permission is hereby granted, free of charge, to any person obtaining a copy
77
* of this software and associated documentation files (the "Software"), to deal
@@ -1344,13 +1344,14 @@ public E apply() {
13441344
public static <T> Function<T> once(final Function<T> function) {
13451345
return new Function<T>() {
13461346
private volatile boolean executed;
1347+
private T result;
13471348
@Override
13481349
public T apply() {
13491350
if (!executed) {
13501351
executed = true;
1351-
delay(function, 0);
1352+
result = function.apply();
13521353
}
1353-
return null;
1354+
return result;
13541355
}
13551356
};
13561357
}

src/test/java/com/github/underscore/FunctionsTest.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,13 +146,14 @@ public void defer() throws Exception {
146146
@Test
147147
public void once() throws Exception {
148148
final Integer[] counter = new Integer[] {0};
149-
Function<Void> incr = new Function<Void>() { public Void apply() {
150-
counter[0]++; return null; } };
151-
Function<Void> onceIncr = $.once(incr);
149+
Function<Integer> incr = new Function<Integer>() { public Integer apply() {
150+
counter[0]++; return counter[0]; } };
151+
Function<Integer> onceIncr = $.once(incr);
152152
onceIncr.apply();
153153
onceIncr.apply();
154154
Thread.sleep(60);
155155
assertEquals("incr was called only once", 1, counter[0].intValue());
156+
assertEquals("stores a memo to the last value", 1, onceIncr.apply().intValue());
156157
}
157158

158159
/*

src/test/javascript/functions_spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,13 @@
6262
_.delay(debouncedIncr, 16);
6363
_.delay(function(){ equal(counter, 1, 'incr was debounced'); }, 96);
6464
});
65+
66+
describe('once', function() {
67+
var num = 0;
68+
var increment = _.once(function(){ return ++num; });
69+
increment();
70+
increment();
71+
equal(num, 1);
72+
73+
equal(increment(), 1, 'stores a memo to the last value');
74+
});

0 commit comments

Comments
 (0)